Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

487 Zeilen
15KB

  1. /*
  2. * This sketch will format an SD or SDHC card.
  3. * Warning all data will be deleted!
  4. *
  5. * For SD/SDHC cards larger than 64 MB this
  6. * sketch attempts to match the format
  7. * generated by SDFormatter available here:
  8. *
  9. * http://www.sdcard.org/consumers/formatter/
  10. *
  11. * For smaller cards this sketch uses FAT16
  12. * and SDFormatter uses FAT12.
  13. */
  14. // Print extra info for debug if DEBUG_PRINT is nonzero
  15. #define DEBUG_PRINT 0
  16. #include <SdFat.h>
  17. #if DEBUG_PRINT
  18. #include <SdFatUtil.h>
  19. #endif // DEBUG_PRINT
  20. //
  21. // Change the value of chipSelect if your hardware does
  22. // not use the default value, SS. Common values are:
  23. // Arduino Ethernet shield: pin 4
  24. // Sparkfun SD shield: pin 8
  25. // Adafruit SD shields and modules: pin 10
  26. const uint8_t chipSelect = SS;
  27. // Change spiSpeed to SPI_FULL_SPEED for better performance
  28. // Use SPI_QUARTER_SPEED for even slower SPI bus speed
  29. const uint8_t spiSpeed = SPI_HALF_SPEED;
  30. // Serial output stream
  31. ArduinoOutStream cout(Serial);
  32. Sd2Card card;
  33. uint32_t cardSizeBlocks;
  34. uint16_t cardCapacityMB;
  35. // cache for SD block
  36. cache_t cache;
  37. // MBR information
  38. uint8_t partType;
  39. uint32_t relSector;
  40. uint32_t partSize;
  41. // Fake disk geometry
  42. uint8_t numberOfHeads;
  43. uint8_t sectorsPerTrack;
  44. // FAT parameters
  45. uint16_t reservedSectors;
  46. uint8_t sectorsPerCluster;
  47. uint32_t fatStart;
  48. uint32_t fatSize;
  49. uint32_t dataStart;
  50. // constants for file system structure
  51. uint16_t const BU16 = 128;
  52. uint16_t const BU32 = 8192;
  53. // strings needed in file system structures
  54. char noName[] = "NO NAME ";
  55. char fat16str[] = "FAT16 ";
  56. char fat32str[] = "FAT32 ";
  57. //------------------------------------------------------------------------------
  58. #define sdError(msg) sdError_P(PSTR(msg))
  59. void sdError_P(const char* str) {
  60. cout << pstr("error: ");
  61. cout << pgm(str) << endl;
  62. if (card.errorCode()) {
  63. cout << pstr("SD error: ") << hex << int(card.errorCode());
  64. cout << ',' << int(card.errorData()) << dec << endl;
  65. }
  66. while (1);
  67. }
  68. //------------------------------------------------------------------------------
  69. #if DEBUG_PRINT
  70. void debugPrint() {
  71. cout << pstr("FreeRam: ") << FreeRam() << endl;
  72. cout << pstr("partStart: ") << relSector << endl;
  73. cout << pstr("partSize: ") << partSize << endl;
  74. cout << pstr("reserved: ") << reservedSectors << endl;
  75. cout << pstr("fatStart: ") << fatStart << endl;
  76. cout << pstr("fatSize: ") << fatSize << endl;
  77. cout << pstr("dataStart: ") << dataStart << endl;
  78. cout << pstr("clusterCount: ");
  79. cout << ((relSector + partSize - dataStart)/sectorsPerCluster) << endl;
  80. cout << endl;
  81. cout << pstr("Heads: ") << int(numberOfHeads) << endl;
  82. cout << pstr("Sectors: ") << int(sectorsPerTrack) << endl;
  83. cout << pstr("Cylinders: ");
  84. cout << cardSizeBlocks/(numberOfHeads*sectorsPerTrack) << endl;
  85. }
  86. #endif // DEBUG_PRINT
  87. //------------------------------------------------------------------------------
  88. // write cached block to the card
  89. uint8_t writeCache(uint32_t lbn) {
  90. return card.writeBlock(lbn, cache.data);
  91. }
  92. //------------------------------------------------------------------------------
  93. // initialize appropriate sizes for SD capacity
  94. void initSizes() {
  95. if (cardCapacityMB <= 6) {
  96. sdError("Card is too small.");
  97. } else if (cardCapacityMB <= 16) {
  98. sectorsPerCluster = 2;
  99. } else if (cardCapacityMB <= 32) {
  100. sectorsPerCluster = 4;
  101. } else if (cardCapacityMB <= 64) {
  102. sectorsPerCluster = 8;
  103. } else if (cardCapacityMB <= 128) {
  104. sectorsPerCluster = 16;
  105. } else if (cardCapacityMB <= 1024) {
  106. sectorsPerCluster = 32;
  107. } else if (cardCapacityMB <= 32768) {
  108. sectorsPerCluster = 64;
  109. } else {
  110. // SDXC cards
  111. sectorsPerCluster = 128;
  112. }
  113. cout << pstr("Blocks/Cluster: ") << int(sectorsPerCluster) << endl;
  114. // set fake disk geometry
  115. sectorsPerTrack = cardCapacityMB <= 256 ? 32 : 63;
  116. if (cardCapacityMB <= 16) {
  117. numberOfHeads = 2;
  118. } else if (cardCapacityMB <= 32) {
  119. numberOfHeads = 4;
  120. } else if (cardCapacityMB <= 128) {
  121. numberOfHeads = 8;
  122. } else if (cardCapacityMB <= 504) {
  123. numberOfHeads = 16;
  124. } else if (cardCapacityMB <= 1008) {
  125. numberOfHeads = 32;
  126. } else if (cardCapacityMB <= 2016) {
  127. numberOfHeads = 64;
  128. } else if (cardCapacityMB <= 4032) {
  129. numberOfHeads = 128;
  130. } else {
  131. numberOfHeads = 255;
  132. }
  133. }
  134. //------------------------------------------------------------------------------
  135. // zero cache and optionally set the sector signature
  136. void clearCache(uint8_t addSig) {
  137. memset(&cache, 0, sizeof(cache));
  138. if (addSig) {
  139. cache.mbr.mbrSig0 = BOOTSIG0;
  140. cache.mbr.mbrSig1 = BOOTSIG1;
  141. }
  142. }
  143. //------------------------------------------------------------------------------
  144. // zero FAT and root dir area on SD
  145. void clearFatDir(uint32_t bgn, uint32_t count) {
  146. clearCache(false);
  147. if (!card.writeStart(bgn, count)) {
  148. sdError("Clear FAT/DIR writeStart failed");
  149. }
  150. for (uint32_t i = 0; i < count; i++) {
  151. if ((i & 0XFF) == 0) cout << '.';
  152. if (!card.writeData(cache.data)) {
  153. sdError("Clear FAT/DIR writeData failed");
  154. }
  155. }
  156. if (!card.writeStop()) {
  157. sdError("Clear FAT/DIR writeStop failed");
  158. }
  159. cout << endl;
  160. }
  161. //------------------------------------------------------------------------------
  162. // return cylinder number for a logical block number
  163. uint16_t lbnToCylinder(uint32_t lbn) {
  164. return lbn / (numberOfHeads * sectorsPerTrack);
  165. }
  166. //------------------------------------------------------------------------------
  167. // return head number for a logical block number
  168. uint8_t lbnToHead(uint32_t lbn) {
  169. return (lbn % (numberOfHeads * sectorsPerTrack)) / sectorsPerTrack;
  170. }
  171. //------------------------------------------------------------------------------
  172. // return sector number for a logical block number
  173. uint8_t lbnToSector(uint32_t lbn) {
  174. return (lbn % sectorsPerTrack) + 1;
  175. }
  176. //------------------------------------------------------------------------------
  177. // format and write the Master Boot Record
  178. void writeMbr() {
  179. clearCache(true);
  180. part_t* p = cache.mbr.part;
  181. p->boot = 0;
  182. uint16_t c = lbnToCylinder(relSector);
  183. if (c > 1023) sdError("MBR CHS");
  184. p->beginCylinderHigh = c >> 8;
  185. p->beginCylinderLow = c & 0XFF;
  186. p->beginHead = lbnToHead(relSector);
  187. p->beginSector = lbnToSector(relSector);
  188. p->type = partType;
  189. uint32_t endLbn = relSector + partSize - 1;
  190. c = lbnToCylinder(endLbn);
  191. if (c <= 1023) {
  192. p->endCylinderHigh = c >> 8;
  193. p->endCylinderLow = c & 0XFF;
  194. p->endHead = lbnToHead(endLbn);
  195. p->endSector = lbnToSector(endLbn);
  196. } else {
  197. // Too big flag, c = 1023, h = 254, s = 63
  198. p->endCylinderHigh = 3;
  199. p->endCylinderLow = 255;
  200. p->endHead = 254;
  201. p->endSector = 63;
  202. }
  203. p->firstSector = relSector;
  204. p->totalSectors = partSize;
  205. if (!writeCache(0)) sdError("write MBR");
  206. }
  207. //------------------------------------------------------------------------------
  208. // generate serial number from card size and micros since boot
  209. uint32_t volSerialNumber() {
  210. return (cardSizeBlocks << 8) + micros();
  211. }
  212. //------------------------------------------------------------------------------
  213. // format the SD as FAT16
  214. void makeFat16() {
  215. uint32_t nc;
  216. for (dataStart = 2 * BU16;; dataStart += BU16) {
  217. nc = (cardSizeBlocks - dataStart)/sectorsPerCluster;
  218. fatSize = (nc + 2 + 255)/256;
  219. uint32_t r = BU16 + 1 + 2 * fatSize + 32;
  220. if (dataStart < r) continue;
  221. relSector = dataStart - r + BU16;
  222. break;
  223. }
  224. // check valid cluster count for FAT16 volume
  225. if (nc < 4085 || nc >= 65525) sdError("Bad cluster count");
  226. reservedSectors = 1;
  227. fatStart = relSector + reservedSectors;
  228. partSize = nc * sectorsPerCluster + 2 * fatSize + reservedSectors + 32;
  229. if (partSize < 32680) {
  230. partType = 0X01;
  231. } else if (partSize < 65536) {
  232. partType = 0X04;
  233. } else {
  234. partType = 0X06;
  235. }
  236. // write MBR
  237. writeMbr();
  238. clearCache(true);
  239. fat_boot_t* pb = &cache.fbs;
  240. pb->jump[0] = 0XEB;
  241. pb->jump[1] = 0X00;
  242. pb->jump[2] = 0X90;
  243. for (uint8_t i = 0; i < sizeof(pb->oemId); i++) {
  244. pb->oemId[i] = ' ';
  245. }
  246. pb->bytesPerSector = 512;
  247. pb->sectorsPerCluster = sectorsPerCluster;
  248. pb->reservedSectorCount = reservedSectors;
  249. pb->fatCount = 2;
  250. pb->rootDirEntryCount = 512;
  251. pb->mediaType = 0XF8;
  252. pb->sectorsPerFat16 = fatSize;
  253. pb->sectorsPerTrack = sectorsPerTrack;
  254. pb->headCount = numberOfHeads;
  255. pb->hidddenSectors = relSector;
  256. pb->totalSectors32 = partSize;
  257. pb->driveNumber = 0X80;
  258. pb->bootSignature = EXTENDED_BOOT_SIG;
  259. pb->volumeSerialNumber = volSerialNumber();
  260. memcpy(pb->volumeLabel, noName, sizeof(pb->volumeLabel));
  261. memcpy(pb->fileSystemType, fat16str, sizeof(pb->fileSystemType));
  262. // write partition boot sector
  263. if (!writeCache(relSector)) {
  264. sdError("FAT16 write PBS failed");
  265. }
  266. // clear FAT and root directory
  267. clearFatDir(fatStart, dataStart - fatStart);
  268. clearCache(false);
  269. cache.fat16[0] = 0XFFF8;
  270. cache.fat16[1] = 0XFFFF;
  271. // write first block of FAT and backup for reserved clusters
  272. if (!writeCache(fatStart)
  273. || !writeCache(fatStart + fatSize)) {
  274. sdError("FAT16 reserve failed");
  275. }
  276. }
  277. //------------------------------------------------------------------------------
  278. // format the SD as FAT32
  279. void makeFat32() {
  280. uint32_t nc;
  281. relSector = BU32;
  282. for (dataStart = 2 * BU32;; dataStart += BU32) {
  283. nc = (cardSizeBlocks - dataStart)/sectorsPerCluster;
  284. fatSize = (nc + 2 + 127)/128;
  285. uint32_t r = relSector + 9 + 2 * fatSize;
  286. if (dataStart >= r) break;
  287. }
  288. // error if too few clusters in FAT32 volume
  289. if (nc < 65525) sdError("Bad cluster count");
  290. reservedSectors = dataStart - relSector - 2 * fatSize;
  291. fatStart = relSector + reservedSectors;
  292. partSize = nc * sectorsPerCluster + dataStart - relSector;
  293. // type depends on address of end sector
  294. // max CHS has lbn = 16450560 = 1024*255*63
  295. if ((relSector + partSize) <= 16450560) {
  296. // FAT32
  297. partType = 0X0B;
  298. } else {
  299. // FAT32 with INT 13
  300. partType = 0X0C;
  301. }
  302. writeMbr();
  303. clearCache(true);
  304. fat32_boot_t* pb = &cache.fbs32;
  305. pb->jump[0] = 0XEB;
  306. pb->jump[1] = 0X00;
  307. pb->jump[2] = 0X90;
  308. for (uint8_t i = 0; i < sizeof(pb->oemId); i++) {
  309. pb->oemId[i] = ' ';
  310. }
  311. pb->bytesPerSector = 512;
  312. pb->sectorsPerCluster = sectorsPerCluster;
  313. pb->reservedSectorCount = reservedSectors;
  314. pb->fatCount = 2;
  315. pb->mediaType = 0XF8;
  316. pb->sectorsPerTrack = sectorsPerTrack;
  317. pb->headCount = numberOfHeads;
  318. pb->hidddenSectors = relSector;
  319. pb->totalSectors32 = partSize;
  320. pb->sectorsPerFat32 = fatSize;
  321. pb->fat32RootCluster = 2;
  322. pb->fat32FSInfo = 1;
  323. pb->fat32BackBootBlock = 6;
  324. pb->driveNumber = 0X80;
  325. pb->bootSignature = EXTENDED_BOOT_SIG;
  326. pb->volumeSerialNumber = volSerialNumber();
  327. memcpy(pb->volumeLabel, noName, sizeof(pb->volumeLabel));
  328. memcpy(pb->fileSystemType, fat32str, sizeof(pb->fileSystemType));
  329. // write partition boot sector and backup
  330. if (!writeCache(relSector)
  331. || !writeCache(relSector + 6)) {
  332. sdError("FAT32 write PBS failed");
  333. }
  334. clearCache(true);
  335. // write extra boot area and backup
  336. if (!writeCache(relSector + 2)
  337. || !writeCache(relSector + 8)) {
  338. sdError("FAT32 PBS ext failed");
  339. }
  340. fat32_fsinfo_t* pf = &cache.fsinfo;
  341. pf->leadSignature = FSINFO_LEAD_SIG;
  342. pf->structSignature = FSINFO_STRUCT_SIG;
  343. pf->freeCount = 0XFFFFFFFF;
  344. pf->nextFree = 0XFFFFFFFF;
  345. // write FSINFO sector and backup
  346. if (!writeCache(relSector + 1)
  347. || !writeCache(relSector + 7)) {
  348. sdError("FAT32 FSINFO failed");
  349. }
  350. clearFatDir(fatStart, 2 * fatSize + sectorsPerCluster);
  351. clearCache(false);
  352. cache.fat32[0] = 0x0FFFFFF8;
  353. cache.fat32[1] = 0x0FFFFFFF;
  354. cache.fat32[2] = 0x0FFFFFFF;
  355. // write first block of FAT and backup for reserved clusters
  356. if (!writeCache(fatStart)
  357. || !writeCache(fatStart + fatSize)) {
  358. sdError("FAT32 reserve failed");
  359. }
  360. }
  361. //------------------------------------------------------------------------------
  362. // flash erase all data
  363. uint32_t const ERASE_SIZE = 262144L;
  364. void eraseCard() {
  365. cout << endl << pstr("Erasing\n");
  366. uint32_t firstBlock = 0;
  367. uint32_t lastBlock;
  368. uint16_t n = 0;
  369. do {
  370. lastBlock = firstBlock + ERASE_SIZE - 1;
  371. if (lastBlock >= cardSizeBlocks) lastBlock = cardSizeBlocks - 1;
  372. if (!card.erase(firstBlock, lastBlock)) sdError("erase failed");
  373. cout << '.';
  374. if ((n++)%32 == 31) cout << endl;
  375. firstBlock += ERASE_SIZE;
  376. } while (firstBlock < cardSizeBlocks);
  377. cout << endl;
  378. if (!card.readBlock(0, cache.data)) sdError("readBlock");
  379. cout << hex << showbase << setfill('0') << internal;
  380. cout << pstr("All data set to ") << setw(4) << int(cache.data[0]) << endl;
  381. cout << dec << noshowbase << setfill(' ') << right;
  382. cout << pstr("Erase done\n");
  383. }
  384. //------------------------------------------------------------------------------
  385. void formatCard() {
  386. cout << endl;
  387. cout << pstr("Formatting\n");
  388. initSizes();
  389. if (card.type() != SD_CARD_TYPE_SDHC) {
  390. cout << pstr("FAT16\n");
  391. makeFat16();
  392. } else {
  393. cout << pstr("FAT32\n");
  394. makeFat32();
  395. }
  396. #if DEBUG_PRINT
  397. debugPrint();
  398. #endif // DEBUG_PRINT
  399. cout << pstr("Format done\n");
  400. }
  401. //------------------------------------------------------------------------------
  402. void setup() {
  403. char c;
  404. Serial.begin(9600);
  405. while (!Serial) {} // wait for Leonardo
  406. cout << pstr(
  407. "\n"
  408. "This sketch can erase and/or format SD/SDHC cards.\n"
  409. "\n"
  410. "Erase uses the card's fast flash erase command.\n"
  411. "Flash erase sets all data to 0X00 for most cards\n"
  412. "and 0XFF for a few vendor's cards.\n"
  413. "\n"
  414. "Cards larger than 2 GB will be formatted FAT32 and\n"
  415. "smaller cards will be formatted FAT16.\n"
  416. "\n"
  417. "Warning, all data on the card will be erased.\n"
  418. "Enter 'Y' to continue: ");
  419. while (!Serial.available()) {}
  420. delay(400); // catch Due restart problem
  421. c = Serial.read();
  422. cout << c << endl;
  423. if (c != 'Y') {
  424. cout << pstr("Quiting, you did not enter 'Y'.\n");
  425. return;
  426. }
  427. // read any existing Serial data
  428. while (Serial.read() >= 0) {}
  429. cout << pstr(
  430. "\n"
  431. "Options are:\n"
  432. "E - erase the card and skip formatting.\n"
  433. "F - erase and then format the card. (recommended)\n"
  434. "Q - quick format the card without erase.\n"
  435. "\n"
  436. "Enter option: ");
  437. while (!Serial.available()) {}
  438. c = Serial.read();
  439. cout << c << endl;
  440. if (!strchr("EFQ", c)) {
  441. cout << pstr("Quiting, invalid option entered.") << endl;
  442. return;
  443. }
  444. if (!card.init(spiSpeed, chipSelect)) {
  445. cout << pstr(
  446. "\nSD initialization failure!\n"
  447. "Is the SD card inserted correctly?\n"
  448. "Is chip select correct at the top of this sketch?\n");
  449. sdError("card.init failed");
  450. }
  451. cardSizeBlocks = card.cardSize();
  452. if (cardSizeBlocks == 0) sdError("cardSize");
  453. cardCapacityMB = (cardSizeBlocks + 2047)/2048;
  454. cout << pstr("Card Size: ") << cardCapacityMB;
  455. cout << pstr(" MB, (MB = 1,048,576 bytes)") << endl;
  456. if (c == 'E' || c == 'F') {
  457. eraseCard();
  458. }
  459. if (c == 'F' || c == 'Q') {
  460. formatCard();
  461. }
  462. }
  463. //------------------------------------------------------------------------------
  464. void loop() {}