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.

SdFormatter.ino 16KB

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