You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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