Patch SD lib files for readability

2.0.x
Scott Lahteine 7 years ago
parent e70b44dc0b
commit 9f8b4c5ee8

@ -35,7 +35,6 @@
#include "../Marlin.h" #include "../Marlin.h"
//------------------------------------------------------------------------------
// send command and return error code. Return zero for OK // send command and return error code. Return zero for OK
uint8_t Sd2Card::cardCommand(uint8_t cmd, uint32_t arg) { uint8_t Sd2Card::cardCommand(uint8_t cmd, uint32_t arg) {
// select card // select card
@ -63,7 +62,7 @@ uint8_t Sd2Card::cardCommand(uint8_t cmd, uint32_t arg) {
for (uint8_t i = 0; ((status_ = spiRec()) & 0x80) && i != 0xFF; i++) { /* Intentionally left empty */ } for (uint8_t i = 0; ((status_ = spiRec()) & 0x80) && i != 0xFF; i++) { /* Intentionally left empty */ }
return status_; return status_;
} }
//------------------------------------------------------------------------------
/** /**
* Determine the size of an SD flash memory card. * Determine the size of an SD flash memory card.
* *
@ -91,19 +90,20 @@ uint32_t Sd2Card::cardSize() {
return 0; return 0;
} }
} }
//------------------------------------------------------------------------------
void Sd2Card::chipSelectHigh() { void Sd2Card::chipSelectHigh() {
digitalWrite(chipSelectPin_, HIGH); digitalWrite(chipSelectPin_, HIGH);
} }
//------------------------------------------------------------------------------
void Sd2Card::chipSelectLow() { void Sd2Card::chipSelectLow() {
#if DISABLED(SOFTWARE_SPI) #if DISABLED(SOFTWARE_SPI)
spiInit(spiRate_); spiInit(spiRate_);
#endif // SOFTWARE_SPI #endif // SOFTWARE_SPI
digitalWrite(chipSelectPin_, LOW); digitalWrite(chipSelectPin_, LOW);
} }
//------------------------------------------------------------------------------
/** Erase a range of blocks. /**
* Erase a range of blocks.
* *
* \param[in] firstBlock The address of the first block in the range. * \param[in] firstBlock The address of the first block in the range.
* \param[in] lastBlock The address of the last block in the range. * \param[in] lastBlock The address of the last block in the range.
@ -113,8 +113,7 @@ void Sd2Card::chipSelectLow() {
* either 0 or 1, depends on the card vendor. The card must support * either 0 or 1, depends on the card vendor. The card must support
* single block erase. * single block erase.
* *
* \return The value one, true, is returned for success and * \return true for success, false for failure.
* the value zero, false, is returned for failure.
*/ */
bool Sd2Card::erase(uint32_t firstBlock, uint32_t lastBlock) { bool Sd2Card::erase(uint32_t firstBlock, uint32_t lastBlock) {
csd_t csd; csd_t csd;
@ -149,26 +148,26 @@ bool Sd2Card::erase(uint32_t firstBlock, uint32_t lastBlock) {
chipSelectHigh(); chipSelectHigh();
return false; return false;
} }
//------------------------------------------------------------------------------
/** Determine if card supports single block erase. /**
* Determine if card supports single block erase.
* *
* \return The value one, true, is returned if single block erase is supported. * \return true if single block erase is supported.
* The value zero, false, is returned if single block erase is not supported. * false if single block erase is not supported.
*/ */
bool Sd2Card::eraseSingleBlockEnable() { bool Sd2Card::eraseSingleBlockEnable() {
csd_t csd; csd_t csd;
return readCSD(&csd) ? csd.v1.erase_blk_en : false; return readCSD(&csd) ? csd.v1.erase_blk_en : false;
} }
//------------------------------------------------------------------------------
/** /**
* Initialize an SD flash memory card. * Initialize an SD flash memory card.
* *
* \param[in] sckRateID SPI clock rate selector. See setSckRate(). * \param[in] sckRateID SPI clock rate selector. See setSckRate().
* \param[in] chipSelectPin SD chip select pin number. * \param[in] chipSelectPin SD chip select pin number.
* *
* \return The value one, true, is returned for success and * \return true for success, false for failure.
* the value zero, false, is returned for failure. The reason for failure * The reason for failure can be determined by calling errorCode() and errorData().
* can be determined by calling errorCode() and errorData().
*/ */
bool Sd2Card::init(uint8_t sckRateID, pin_t chipSelectPin) { bool Sd2Card::init(uint8_t sckRateID, pin_t chipSelectPin) {
errorCode_ = type_ = 0; errorCode_ = type_ = 0;
@ -247,14 +246,13 @@ bool Sd2Card::init(uint8_t sckRateID, pin_t chipSelectPin) {
chipSelectHigh(); chipSelectHigh();
return false; return false;
} }
//------------------------------------------------------------------------------
/** /**
* Read a 512 byte block from an SD card. * Read a 512 byte block from an SD card.
* *
* \param[in] blockNumber Logical block to be read. * \param[in] blockNumber Logical block to be read.
* \param[out] dst Pointer to the location that will receive the data. * \param[out] dst Pointer to the location that will receive the data.
* \return The value one, true, is returned for success and * \return true for success, false for failure.
* the value zero, false, is returned for failure.
*/ */
bool Sd2Card::readBlock(uint32_t blockNumber, uint8_t* dst) { bool Sd2Card::readBlock(uint32_t blockNumber, uint8_t* dst) {
// use address if not SDHC card // use address if not SDHC card
@ -262,19 +260,18 @@ bool Sd2Card::readBlock(uint32_t blockNumber, uint8_t* dst) {
#if ENABLED(SD_CHECK_AND_RETRY) #if ENABLED(SD_CHECK_AND_RETRY)
uint8_t retryCnt = 3; uint8_t retryCnt = 3;
do { for(;;) {
if (!cardCommand(CMD17, blockNumber)) { if (cardCommand(CMD17, blockNumber))
if (readData(dst, 512)) return true;
}
else
error(SD_CARD_ERROR_CMD17); error(SD_CARD_ERROR_CMD17);
else if (readData(dst, 512))
return true;
if (!--retryCnt) break; if (!--retryCnt) break;
chipSelectHigh(); chipSelectHigh();
cardCommand(CMD12, 0); // Try sending a stop command, ignore the result. cardCommand(CMD12, 0); // Try sending a stop command, ignore the result.
errorCode_ = 0; errorCode_ = 0;
} while (true); }
#else #else
if (cardCommand(CMD17, blockNumber)) if (cardCommand(CMD17, blockNumber))
error(SD_CARD_ERROR_CMD17); error(SD_CARD_ERROR_CMD17);
@ -285,13 +282,13 @@ bool Sd2Card::readBlock(uint32_t blockNumber, uint8_t* dst) {
chipSelectHigh(); chipSelectHigh();
return false; return false;
} }
//------------------------------------------------------------------------------
/** Read one data block in a multiple block read sequence /**
* Read one data block in a multiple block read sequence
* *
* \param[in] dst Pointer to the location for the data to be read. * \param[in] dst Pointer to the location for the data to be read.
* *
* \return The value one, true, is returned for success and * \return true for success, false for failure.
* the value zero, false, is returned for failure.
*/ */
bool Sd2Card::readData(uint8_t* dst) { bool Sd2Card::readData(uint8_t* dst) {
chipSelectLow(); chipSelectLow();
@ -299,50 +296,49 @@ bool Sd2Card::readData(uint8_t* dst) {
} }
#if ENABLED(SD_CHECK_AND_RETRY) #if ENABLED(SD_CHECK_AND_RETRY)
static const uint16_t crctab[] PROGMEM = { static const uint16_t crctab[] PROGMEM = {
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
}; };
static uint16_t CRC_CCITT(const uint8_t* data, size_t n) { static uint16_t CRC_CCITT(const uint8_t* data, size_t n) {
uint16_t crc = 0; uint16_t crc = 0;
for (size_t i = 0; i < n; i++) { for (size_t i = 0; i < n; i++) {
crc = pgm_read_word(&crctab[(crc >> 8 ^ data[i]) & 0xFF]) ^ (crc << 8); crc = pgm_read_word(&crctab[(crc >> 8 ^ data[i]) & 0xFF]) ^ (crc << 8);
}
return crc;
} }
return crc; #endif // SD_CHECK_AND_RETRY
}
#endif
//------------------------------------------------------------------------------
bool Sd2Card::readData(uint8_t* dst, uint16_t count) { bool Sd2Card::readData(uint8_t* dst, uint16_t count) {
// wait for start block token // wait for start block token
uint16_t t0 = millis(); uint16_t t0 = millis();
@ -384,61 +380,55 @@ bool Sd2Card::readData(uint8_t* dst, uint16_t count) {
spiSend(0XFF); spiSend(0XFF);
return false; return false;
} }
//------------------------------------------------------------------------------
/** read CID or CSR register */ /** read CID or CSR register */
bool Sd2Card::readRegister(uint8_t cmd, void* buf) { bool Sd2Card::readRegister(uint8_t cmd, void* buf) {
uint8_t* dst = reinterpret_cast<uint8_t*>(buf); uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
if (cardCommand(cmd, 0)) { if (cardCommand(cmd, 0)) {
error(SD_CARD_ERROR_READ_REG); error(SD_CARD_ERROR_READ_REG);
goto FAIL; chipSelectHigh();
return false;
} }
return readData(dst, 16); return readData(dst, 16);
FAIL:
chipSelectHigh();
return false;
} }
//------------------------------------------------------------------------------
/** Start a read multiple blocks sequence. /**
* Start a read multiple blocks sequence.
* *
* \param[in] blockNumber Address of first block in sequence. * \param[in] blockNumber Address of first block in sequence.
* *
* \note This function is used with readData() and readStop() for optimized * \note This function is used with readData() and readStop() for optimized
* multiple block reads. SPI chipSelect must be low for the entire sequence. * multiple block reads. SPI chipSelect must be low for the entire sequence.
* *
* \return The value one, true, is returned for success and * \return true for success, false for failure.
* the value zero, false, is returned for failure.
*/ */
bool Sd2Card::readStart(uint32_t blockNumber) { bool Sd2Card::readStart(uint32_t blockNumber) {
if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9; if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9;
if (cardCommand(CMD18, blockNumber)) { if (cardCommand(CMD18, blockNumber)) {
error(SD_CARD_ERROR_CMD18); error(SD_CARD_ERROR_CMD18);
goto FAIL; chipSelectHigh();
return false;
} }
chipSelectHigh(); chipSelectHigh();
return true; return true;
FAIL:
chipSelectHigh();
return false;
} }
//------------------------------------------------------------------------------
/** End a read multiple blocks sequence. /**
* End a read multiple blocks sequence.
* *
* \return The value one, true, is returned for success and * \return true for success, false for failure.
* the value zero, false, is returned for failure.
*/ */
bool Sd2Card::readStop() { bool Sd2Card::readStop() {
chipSelectLow(); chipSelectLow();
if (cardCommand(CMD12, 0)) { if (cardCommand(CMD12, 0)) {
error(SD_CARD_ERROR_CMD12); error(SD_CARD_ERROR_CMD12);
goto FAIL; chipSelectHigh();
return false;
} }
chipSelectHigh(); chipSelectHigh();
return true; return true;
FAIL:
chipSelectHigh();
return false;
} }
//------------------------------------------------------------------------------
/** /**
* Set the SPI clock rate. * Set the SPI clock rate.
* *
@ -459,25 +449,22 @@ bool Sd2Card::setSckRate(uint8_t sckRateID) {
spiRate_ = sckRateID; spiRate_ = sckRateID;
return true; return true;
} }
//------------------------------------------------------------------------------
// wait for card to go not busy // wait for card to go not busy
bool Sd2Card::waitNotBusy(uint16_t timeoutMillis) { bool Sd2Card::waitNotBusy(uint16_t timeoutMillis) {
uint16_t t0 = millis(); uint16_t t0 = millis();
while (spiRec() != 0XFF) { while (spiRec() != 0XFF)
if (((uint16_t)millis() - t0) >= timeoutMillis) goto FAIL; if (((uint16_t)millis() - t0) >= timeoutMillis) return false;
}
return true; return true;
FAIL:
return false;
} }
//------------------------------------------------------------------------------
/** /**
* Writes a 512 byte block to an SD card. * Writes a 512 byte block to an SD card.
* *
* \param[in] blockNumber Logical block to be written. * \param[in] blockNumber Logical block to be written.
* \param[in] src Pointer to the location of the data to be written. * \param[in] src Pointer to the location of the data to be written.
* \return The value one, true, is returned for success and * \return true for success, false for failure.
* the value zero, false, is returned for failure.
*/ */
bool Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src) { bool Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src) {
// use address if not SDHC card // use address if not SDHC card
@ -504,25 +491,24 @@ bool Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src) {
chipSelectHigh(); chipSelectHigh();
return false; return false;
} }
//------------------------------------------------------------------------------
/** Write one data block in a multiple block write sequence /**
* Write one data block in a multiple block write sequence
* \param[in] src Pointer to the location of the data to be written. * \param[in] src Pointer to the location of the data to be written.
* \return The value one, true, is returned for success and * \return true for success, false for failure.
* the value zero, false, is returned for failure.
*/ */
bool Sd2Card::writeData(const uint8_t* src) { bool Sd2Card::writeData(const uint8_t* src) {
chipSelectLow(); chipSelectLow();
// wait for previous write to finish // wait for previous write to finish
if (!waitNotBusy(SD_WRITE_TIMEOUT)) goto FAIL; if (!waitNotBusy(SD_WRITE_TIMEOUT) || !writeData(WRITE_MULTIPLE_TOKEN, src)) {
if (!writeData(WRITE_MULTIPLE_TOKEN, src)) goto FAIL; error(SD_CARD_ERROR_WRITE_MULTIPLE);
chipSelectHigh();
return false;
}
chipSelectHigh(); chipSelectHigh();
return true; return true;
FAIL:
error(SD_CARD_ERROR_WRITE_MULTIPLE);
chipSelectHigh();
return false;
} }
//------------------------------------------------------------------------------
// send one block of data for write block or write multiple blocks // send one block of data for write block or write multiple blocks
bool Sd2Card::writeData(uint8_t token, const uint8_t* src) { bool Sd2Card::writeData(uint8_t token, const uint8_t* src) {
spiSendBlock(token, src); spiSendBlock(token, src);
@ -533,15 +519,14 @@ bool Sd2Card::writeData(uint8_t token, const uint8_t* src) {
status_ = spiRec(); status_ = spiRec();
if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) { if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) {
error(SD_CARD_ERROR_WRITE); error(SD_CARD_ERROR_WRITE);
goto FAIL; chipSelectHigh();
return false;
} }
return true; return true;
FAIL:
chipSelectHigh();
return false;
} }
//------------------------------------------------------------------------------
/** Start a write multiple blocks sequence. /**
* Start a write multiple blocks sequence.
* *
* \param[in] blockNumber Address of first block in sequence. * \param[in] blockNumber Address of first block in sequence.
* \param[in] eraseCount The number of blocks to be pre-erased. * \param[in] eraseCount The number of blocks to be pre-erased.
@ -549,8 +534,7 @@ bool Sd2Card::writeData(uint8_t token, const uint8_t* src) {
* \note This function is used with writeData() and writeStop() * \note This function is used with writeData() and writeStop()
* for optimized multiple block writes. * for optimized multiple block writes.
* *
* \return The value one, true, is returned for success and * \return true for success, false for failure.
* the value zero, false, is returned for failure.
*/ */
bool Sd2Card::writeStart(uint32_t blockNumber, uint32_t eraseCount) { bool Sd2Card::writeStart(uint32_t blockNumber, uint32_t eraseCount) {
// send pre-erase count // send pre-erase count
@ -570,11 +554,11 @@ bool Sd2Card::writeStart(uint32_t blockNumber, uint32_t eraseCount) {
chipSelectHigh(); chipSelectHigh();
return false; return false;
} }
//------------------------------------------------------------------------------
/** End a write multiple blocks sequence. /**
* End a write multiple blocks sequence.
* *
* \return The value one, true, is returned for success and * \return true for success, false for failure.
* the value zero, false, is returned for failure.
*/ */
bool Sd2Card::writeStop() { bool Sd2Card::writeStop() {
chipSelectLow(); chipSelectLow();
@ -589,4 +573,4 @@ bool Sd2Card::writeStop() {
return false; return false;
} }
#endif #endif // SDSUPPORT

@ -20,100 +20,67 @@
* *
*/ */
/**
* \file
* \brief Sd2Card class for V2 SD/SDHC cards
*/
/** /**
* Arduino Sd2Card Library * Arduino Sd2Card Library
* Copyright (C) 2009 by William Greiman * Copyright (C) 2009 by William Greiman
* *
* This file is part of the Arduino Sd2Card Library * This file is part of the Arduino Sd2Card Library
*/ */
#ifndef _SD2CARD_H_
#define _SD2CARD_H_
#ifndef SD2CARD_H
#define SD2CARD_H
/**
* \file
* \brief Sd2Card class for V2 SD/SDHC cards
*/
#include "SdFatConfig.h" #include "SdFatConfig.h"
#include "SdInfo.h" #include "SdInfo.h"
#include <stdint.h> #include <stdint.h>
//------------------------------------------------------------------------------ uint16_t const SD_INIT_TIMEOUT = 2000, // init timeout ms
/** init timeout ms */ SD_ERASE_TIMEOUT = 10000, // erase timeout ms
uint16_t const SD_INIT_TIMEOUT = 2000; SD_READ_TIMEOUT = 300, // read timeout ms
/** erase timeout ms */ SD_WRITE_TIMEOUT = 600; // write time out ms
uint16_t const SD_ERASE_TIMEOUT = 10000;
/** read timeout ms */
uint16_t const SD_READ_TIMEOUT = 300;
/** write time out ms */
uint16_t const SD_WRITE_TIMEOUT = 600;
//------------------------------------------------------------------------------
// SD card errors // SD card errors
/** timeout error for command CMD0 (initialize card in SPI mode) */ uint8_t const SD_CARD_ERROR_CMD0 = 0X1, // timeout error for command CMD0 (initialize card in SPI mode)
uint8_t const SD_CARD_ERROR_CMD0 = 0X1; SD_CARD_ERROR_CMD8 = 0X2, // CMD8 was not accepted - not a valid SD card
/** CMD8 was not accepted - not a valid SD card*/ SD_CARD_ERROR_CMD12 = 0X3, // card returned an error response for CMD12 (write stop)
uint8_t const SD_CARD_ERROR_CMD8 = 0X2; SD_CARD_ERROR_CMD17 = 0X4, // card returned an error response for CMD17 (read block)
/** card returned an error response for CMD12 (write stop) */ SD_CARD_ERROR_CMD18 = 0X5, // card returned an error response for CMD18 (read multiple block)
uint8_t const SD_CARD_ERROR_CMD12 = 0X3; SD_CARD_ERROR_CMD24 = 0X6, // card returned an error response for CMD24 (write block)
/** card returned an error response for CMD17 (read block) */ SD_CARD_ERROR_CMD25 = 0X7, // WRITE_MULTIPLE_BLOCKS command failed
uint8_t const SD_CARD_ERROR_CMD17 = 0X4; SD_CARD_ERROR_CMD58 = 0X8, // card returned an error response for CMD58 (read OCR)
/** card returned an error response for CMD18 (read multiple block) */ SD_CARD_ERROR_ACMD23 = 0X9, // SET_WR_BLK_ERASE_COUNT failed
uint8_t const SD_CARD_ERROR_CMD18 = 0X5; SD_CARD_ERROR_ACMD41 = 0XA, // ACMD41 initialization process timeout
/** card returned an error response for CMD24 (write block) */ SD_CARD_ERROR_BAD_CSD = 0XB, // card returned a bad CSR version field
uint8_t const SD_CARD_ERROR_CMD24 = 0X6; SD_CARD_ERROR_ERASE = 0XC, // erase block group command failed
/** WRITE_MULTIPLE_BLOCKS command failed */ SD_CARD_ERROR_ERASE_SINGLE_BLOCK = 0XD, // card not capable of single block erase
uint8_t const SD_CARD_ERROR_CMD25 = 0X7; SD_CARD_ERROR_ERASE_TIMEOUT = 0XE, // Erase sequence timed out
/** card returned an error response for CMD58 (read OCR) */ SD_CARD_ERROR_READ = 0XF, // card returned an error token instead of read data
uint8_t const SD_CARD_ERROR_CMD58 = 0X8; SD_CARD_ERROR_READ_REG = 0x10, // read CID or CSD failed
/** SET_WR_BLK_ERASE_COUNT failed */ SD_CARD_ERROR_READ_TIMEOUT = 0x11, // timeout while waiting for start of read data
uint8_t const SD_CARD_ERROR_ACMD23 = 0X9; SD_CARD_ERROR_STOP_TRAN = 0x12, // card did not accept STOP_TRAN_TOKEN
/** ACMD41 initialization process timeout */ SD_CARD_ERROR_WRITE = 0x13, // card returned an error token as a response to a write operation
uint8_t const SD_CARD_ERROR_ACMD41 = 0XA; SD_CARD_ERROR_WRITE_BLOCK_ZERO = 0x14, // REMOVE - not used ... attempt to write protected block zero
/** card returned a bad CSR version field */ SD_CARD_ERROR_WRITE_MULTIPLE = 0x15, // card did not go ready for a multiple block write
uint8_t const SD_CARD_ERROR_BAD_CSD = 0XB; SD_CARD_ERROR_WRITE_PROGRAMMING = 0x16, // card returned an error to a CMD13 status check after a write
/** erase block group command failed */ SD_CARD_ERROR_WRITE_TIMEOUT = 0x17, // timeout occurred during write programming
uint8_t const SD_CARD_ERROR_ERASE = 0XC; SD_CARD_ERROR_SCK_RATE = 0x18, // incorrect rate selected
/** card not capable of single block erase */ SD_CARD_ERROR_INIT_NOT_CALLED = 0x19, // init() not called
uint8_t const SD_CARD_ERROR_ERASE_SINGLE_BLOCK = 0XD; SD_CARD_ERROR_CRC = 0x20; // crc check error
/** Erase sequence timed out */
uint8_t const SD_CARD_ERROR_ERASE_TIMEOUT = 0XE;
/** card returned an error token instead of read data */
uint8_t const SD_CARD_ERROR_READ = 0XF;
/** read CID or CSD failed */
uint8_t const SD_CARD_ERROR_READ_REG = 0x10;
/** timeout while waiting for start of read data */
uint8_t const SD_CARD_ERROR_READ_TIMEOUT = 0x11;
/** card did not accept STOP_TRAN_TOKEN */
uint8_t const SD_CARD_ERROR_STOP_TRAN = 0x12;
/** card returned an error token as a response to a write operation */
uint8_t const SD_CARD_ERROR_WRITE = 0x13;
/** attempt to write protected block zero */
uint8_t const SD_CARD_ERROR_WRITE_BLOCK_ZERO = 0x14; // REMOVE - not used
/** card did not go ready for a multiple block write */
uint8_t const SD_CARD_ERROR_WRITE_MULTIPLE = 0x15;
/** card returned an error to a CMD13 status check after a write */
uint8_t const SD_CARD_ERROR_WRITE_PROGRAMMING = 0x16;
/** timeout occurred during write programming */
uint8_t const SD_CARD_ERROR_WRITE_TIMEOUT = 0x17;
/** incorrect rate selected */
uint8_t const SD_CARD_ERROR_SCK_RATE = 0x18;
/** init() not called */
uint8_t const SD_CARD_ERROR_INIT_NOT_CALLED = 0x19;
/** crc check error */
uint8_t const SD_CARD_ERROR_CRC = 0x20;
//------------------------------------------------------------------------------
// card types // card types
/** Standard capacity V1 SD card */ uint8_t const SD_CARD_TYPE_SD1 = 1, // Standard capacity V1 SD card
uint8_t const SD_CARD_TYPE_SD1 = 1; SD_CARD_TYPE_SD2 = 2, // Standard capacity V2 SD card
/** Standard capacity V2 SD card */ SD_CARD_TYPE_SDHC = 3; // High Capacity SD card
uint8_t const SD_CARD_TYPE_SD2 = 2;
/** High Capacity SD card */
uint8_t const SD_CARD_TYPE_SDHC = 3;
/** /**
* define SOFTWARE_SPI to use bit-bang SPI * define SOFTWARE_SPI to use bit-bang SPI
*/ */
//------------------------------------------------------------------------------
#if MEGA_SOFT_SPI #if MEGA_SOFT_SPI
#define SOFTWARE_SPI #define SOFTWARE_SPI
#elif USE_SOFTWARE_SPI #elif USE_SOFTWARE_SPI
@ -127,53 +94,47 @@ uint8_t const SD_CARD_TYPE_SDHC = 3;
#if 0 #if 0
#if DISABLED(SOFTWARE_SPI) #if DISABLED(SOFTWARE_SPI)
// hardware pin defs // hardware pin defs
/** The default chip select pin for the SD card is SS. */ #define SD_CHIP_SELECT_PIN SS_PIN // The default chip select pin for the SD card is SS.
#define SD_CHIP_SELECT_PIN SS_PIN
// The following three pins must not be redefined for hardware SPI. // The following three pins must not be redefined for hardware SPI.
/** SPI Master Out Slave In pin */ #define SPI_MOSI_PIN MOSI_PIN // SPI Master Out Slave In pin
#define SPI_MOSI_PIN MOSI_PIN #define SPI_MISO_PIN MISO_PIN // SPI Master In Slave Out pin
/** SPI Master In Slave Out pin */ #define SPI_SCK_PIN SCK_PIN // SPI Clock pin
#define SPI_MISO_PIN MISO_PIN
/** SPI Clock pin */
#define SPI_SCK_PIN SCK_PIN
#else // SOFTWARE_SPI #else // SOFTWARE_SPI
#define SD_CHIP_SELECT_PIN SOFT_SPI_CS_PIN // SPI chip select pin
/** SPI chip select pin */ #define SPI_MOSI_PIN SOFT_SPI_MOSI_PIN // SPI Master Out Slave In pin
#define SD_CHIP_SELECT_PIN SOFT_SPI_CS_PIN #define SPI_MISO_PIN SOFT_SPI_MISO_PIN // SPI Master In Slave Out pin
/** SPI Master Out Slave In pin */ #define SPI_SCK_PIN SOFT_SPI_SCK_PIN // SPI Clock pin
#define SPI_MOSI_PIN SOFT_SPI_MOSI_PIN
/** SPI Master In Slave Out pin */
#define SPI_MISO_PIN SOFT_SPI_MISO_PIN
/** SPI Clock pin */
#define SPI_SCK_PIN SOFT_SPI_SCK_PIN
#endif // SOFTWARE_SPI #endif // SOFTWARE_SPI
#endif #endif
//------------------------------------------------------------------------------
/** /**
* \class Sd2Card * \class Sd2Card
* \brief Raw access to SD and SDHC flash memory cards. * \brief Raw access to SD and SDHC flash memory cards.
*/ */
class Sd2Card { class Sd2Card {
public: public:
/** Construct an instance of Sd2Card. */
Sd2Card() : errorCode_(SD_CARD_ERROR_INIT_NOT_CALLED), type_(0) {} Sd2Card() : errorCode_(SD_CARD_ERROR_INIT_NOT_CALLED), type_(0) {}
uint32_t cardSize(); uint32_t cardSize();
bool erase(uint32_t firstBlock, uint32_t lastBlock); bool erase(uint32_t firstBlock, uint32_t lastBlock);
bool eraseSingleBlockEnable(); bool eraseSingleBlockEnable();
/** /**
* Set SD error code. * Set SD error code.
* \param[in] code value for error code. * \param[in] code value for error code.
*/ */
void error(uint8_t code) {errorCode_ = code;} void error(uint8_t code) {errorCode_ = code;}
/** /**
* \return error code for last error. See Sd2Card.h for a list of error codes. * \return error code for last error. See Sd2Card.h for a list of error codes.
*/ */
int errorCode() const {return errorCode_;} int errorCode() const {return errorCode_;}
/** \return error data for last error. */ /** \return error data for last error. */
int errorData() const {return status_;} int errorData() const {return status_;}
/** /**
* Initialize an SD flash memory card with default clock rate and chip * Initialize an SD flash memory card with default clock rate and chip
* select pin. See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). * select pin. See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin).
@ -183,6 +144,7 @@ class Sd2Card {
bool init(uint8_t sckRateID = SPI_FULL_SPEED, bool init(uint8_t sckRateID = SPI_FULL_SPEED,
pin_t chipSelectPin = SD_CHIP_SELECT_PIN); pin_t chipSelectPin = SD_CHIP_SELECT_PIN);
bool readBlock(uint32_t block, uint8_t* dst); bool readBlock(uint32_t block, uint8_t* dst);
/** /**
* Read a card's CID register. The CID contains card identification * Read a card's CID register. The CID contains card identification
* information such as Manufacturer ID, Product name, Product serial * information such as Manufacturer ID, Product name, Product serial
@ -192,9 +154,8 @@ class Sd2Card {
* *
* \return true for success or false for failure. * \return true for success or false for failure.
*/ */
bool readCID(cid_t* cid) { bool readCID(cid_t* cid) { return readRegister(CMD10, cid); }
return readRegister(CMD10, cid);
}
/** /**
* Read a card's CSD register. The CSD contains Card-Specific Data that * Read a card's CSD register. The CSD contains Card-Specific Data that
* provides information regarding access to the card's contents. * provides information regarding access to the card's contents.
@ -203,14 +164,14 @@ class Sd2Card {
* *
* \return true for success or false for failure. * \return true for success or false for failure.
*/ */
bool readCSD(csd_t* csd) { bool readCSD(csd_t* csd) { return readRegister(CMD9, csd); }
return readRegister(CMD9, csd);
}
bool readData(uint8_t* dst); bool readData(uint8_t* dst);
bool readStart(uint32_t blockNumber); bool readStart(uint32_t blockNumber);
bool readStop(); bool readStop();
bool setSckRate(uint8_t sckRateID); bool setSckRate(uint8_t sckRateID);
/** Return the card type: SD V1, SD V2 or SDHC /**
* Return the card type: SD V1, SD V2 or SDHC
* \return 0 - SD V1, 1 - SD V2, or 3 - SDHC. * \return 0 - SD V1, 1 - SD V2, or 3 - SDHC.
*/ */
int type() const {return type_;} int type() const {return type_;}
@ -218,13 +179,14 @@ class Sd2Card {
bool writeData(const uint8_t* src); bool writeData(const uint8_t* src);
bool writeStart(uint32_t blockNumber, uint32_t eraseCount); bool writeStart(uint32_t blockNumber, uint32_t eraseCount);
bool writeStop(); bool writeStop();
private:
//---------------------------------------------------------------------------- private:
pin_t chipSelectPin_; uint8_t chipSelectPin_,
uint8_t errorCode_; errorCode_,
uint8_t spiRate_; spiRate_,
uint8_t status_; status_,
uint8_t type_; type_;
// private functions // private functions
uint8_t cardAcmd(uint8_t cmd, uint32_t arg) { uint8_t cardAcmd(uint8_t cmd, uint32_t arg) {
cardCommand(CMD55, 0); cardCommand(CMD55, 0);
@ -236,9 +198,9 @@ class Sd2Card {
bool readRegister(uint8_t cmd, void* buf); bool readRegister(uint8_t cmd, void* buf);
void chipSelectHigh(); void chipSelectHigh();
void chipSelectLow(); void chipSelectLow();
void type(uint8_t value) {type_ = value;} void type(uint8_t value) { type_ = value; }
bool waitNotBusy(uint16_t timeoutMillis); bool waitNotBusy(uint16_t timeoutMillis);
bool writeData(uint8_t token, const uint8_t* src); bool writeData(uint8_t token, const uint8_t* src);
}; };
#endif // SD2CARD_H #endif // _SD2CARD_H_

File diff suppressed because it is too large Load Diff

@ -20,209 +20,199 @@
* *
*/ */
/**
* \file
* \brief SdBaseFile class
*/
/** /**
* Arduino SdFat Library * Arduino SdFat Library
* Copyright (C) 2009 by William Greiman * Copyright (C) 2009 by William Greiman
* *
* This file is part of the Arduino Sd2Card Library * This file is part of the Arduino Sd2Card Library
*/ */
#ifndef _SDBASEFILE_H_
#define _SDBASEFILE_H_
#ifndef SDBASEFILE_H
#define SDBASEFILE_H
/**
* \file
* \brief SdBaseFile class
*/
#include "SdFatConfig.h" #include "SdFatConfig.h"
#include "SdVolume.h" #include "SdVolume.h"
#include <stdint.h> #include <stdint.h>
//------------------------------------------------------------------------------
/** /**
* \struct filepos_t * \struct filepos_t
* \brief internal type for istream * \brief internal type for istream
* do not use in user apps * do not use in user apps
*/ */
struct filepos_t { struct filepos_t {
/** stream position */ uint32_t position; // stream byte position
uint32_t position; uint32_t cluster; // cluster of position
/** cluster for position */
uint32_t cluster;
filepos_t() : position(0), cluster(0) {} filepos_t() : position(0), cluster(0) {}
}; };
// use the gnu style oflag in open() // use the gnu style oflag in open()
/** open() oflag for reading */ uint8_t const O_READ = 0x01, // open() oflag for reading
uint8_t const O_READ = 0x01; O_RDONLY = O_READ, // open() oflag - same as O_IN
/** open() oflag - same as O_IN */ O_WRITE = 0x02, // open() oflag for write
uint8_t const O_RDONLY = O_READ; O_WRONLY = O_WRITE, // open() oflag - same as O_WRITE
/** open() oflag for write */ O_RDWR = (O_READ | O_WRITE), // open() oflag for reading and writing
uint8_t const O_WRITE = 0x02; O_ACCMODE = (O_READ | O_WRITE), // open() oflag mask for access modes
/** open() oflag - same as O_WRITE */ O_APPEND = 0x04, // The file offset shall be set to the end of the file prior to each write.
uint8_t const O_WRONLY = O_WRITE; O_SYNC = 0x08, // Synchronous writes - call sync() after each write
/** open() oflag for reading and writing */ O_TRUNC = 0x10, // Truncate the file to zero length
uint8_t const O_RDWR = (O_READ | O_WRITE); O_AT_END = 0x20, // Set the initial position at the end of the file
/** open() oflag mask for access modes */ O_CREAT = 0x40, // Create the file if nonexistent
uint8_t const O_ACCMODE = (O_READ | O_WRITE); O_EXCL = 0x80; // If O_CREAT and O_EXCL are set, open() shall fail if the file exists
/** The file offset shall be set to the end of the file prior to each write. */
uint8_t const O_APPEND = 0x04;
/** synchronous writes - call sync() after each write */
uint8_t const O_SYNC = 0x08;
/** truncate the file to zero length */
uint8_t const O_TRUNC = 0x10;
/** set the initial position at the end of the file */
uint8_t const O_AT_END = 0x20;
/** create the file if nonexistent */
uint8_t const O_CREAT = 0x40;
/** If O_CREAT and O_EXCL are set, open() shall fail if the file exists */
uint8_t const O_EXCL = 0x80;
// SdBaseFile class static and const definitions // SdBaseFile class static and const definitions
// flags for ls() // flags for ls()
/** ls() flag to print modify date */ uint8_t const LS_DATE = 1, // ls() flag to print modify date
uint8_t const LS_DATE = 1; LS_SIZE = 2, // ls() flag to print file size
/** ls() flag to print file size */ LS_R = 4; // ls() flag for recursive list of subdirectories
uint8_t const LS_SIZE = 2;
/** ls() flag for recursive list of subdirectories */
uint8_t const LS_R = 4;
// flags for timestamp // flags for timestamp
/** set the file's last access date */ uint8_t const T_ACCESS = 1, // Set the file's last access date
uint8_t const T_ACCESS = 1; T_CREATE = 2, // Set the file's creation date and time
/** set the file's creation date and time */ T_WRITE = 4; // Set the file's write date and time
uint8_t const T_CREATE = 2;
/** Set the file's write date and time */
uint8_t const T_WRITE = 4;
// values for type_ // values for type_
/** This file has not been opened. */ uint8_t const FAT_FILE_TYPE_CLOSED = 0, // This file has not been opened.
uint8_t const FAT_FILE_TYPE_CLOSED = 0; FAT_FILE_TYPE_NORMAL = 1, // A normal file
/** A normal file */ FAT_FILE_TYPE_ROOT_FIXED = 2, // A FAT12 or FAT16 root directory
uint8_t const FAT_FILE_TYPE_NORMAL = 1; FAT_FILE_TYPE_ROOT32 = 3, // A FAT32 root directory
/** A FAT12 or FAT16 root directory */ FAT_FILE_TYPE_SUBDIR = 4, // A subdirectory file
uint8_t const FAT_FILE_TYPE_ROOT_FIXED = 2; FAT_FILE_TYPE_MIN_DIR = FAT_FILE_TYPE_ROOT_FIXED; // Test value for directory type
/** A FAT32 root directory */
uint8_t const FAT_FILE_TYPE_ROOT32 = 3; /**
/** A subdirectory file*/ * date field for FAT directory entry
uint8_t const FAT_FILE_TYPE_SUBDIR = 4;
/** Test value for directory type */
uint8_t const FAT_FILE_TYPE_MIN_DIR = FAT_FILE_TYPE_ROOT_FIXED;
/** date field for FAT directory entry
* \param[in] year [1980,2107] * \param[in] year [1980,2107]
* \param[in] month [1,12] * \param[in] month [1,12]
* \param[in] day [1,31] * \param[in] day [1,31]
* *
* \return Packed date for dir_t entry. * \return Packed date for dir_t entry.
*/ */
static inline uint16_t FAT_DATE(uint16_t year, uint8_t month, uint8_t day) { static inline uint16_t FAT_DATE(uint16_t year, uint8_t month, uint8_t day) { return (year - 1980) << 9 | month << 5 | day; }
return (year - 1980) << 9 | month << 5 | day;
} /**
/** year part of FAT directory date field * year part of FAT directory date field
* \param[in] fatDate Date in packed dir format. * \param[in] fatDate Date in packed dir format.
* *
* \return Extracted year [1980,2107] * \return Extracted year [1980,2107]
*/ */
static inline uint16_t FAT_YEAR(uint16_t fatDate) { static inline uint16_t FAT_YEAR(uint16_t fatDate) { return 1980 + (fatDate >> 9); }
return 1980 + (fatDate >> 9);
} /**
/** month part of FAT directory date field * month part of FAT directory date field
* \param[in] fatDate Date in packed dir format. * \param[in] fatDate Date in packed dir format.
* *
* \return Extracted month [1,12] * \return Extracted month [1,12]
*/ */
static inline uint8_t FAT_MONTH(uint16_t fatDate) { static inline uint8_t FAT_MONTH(uint16_t fatDate) { return (fatDate >> 5) & 0XF; }
return (fatDate >> 5) & 0XF;
} /**
/** day part of FAT directory date field * day part of FAT directory date field
* \param[in] fatDate Date in packed dir format. * \param[in] fatDate Date in packed dir format.
* *
* \return Extracted day [1,31] * \return Extracted day [1,31]
*/ */
static inline uint8_t FAT_DAY(uint16_t fatDate) { static inline uint8_t FAT_DAY(uint16_t fatDate) { return fatDate & 0x1F; }
return fatDate & 0x1F;
} /**
/** time field for FAT directory entry * time field for FAT directory entry
* \param[in] hour [0,23] * \param[in] hour [0,23]
* \param[in] minute [0,59] * \param[in] minute [0,59]
* \param[in] second [0,59] * \param[in] second [0,59]
* *
* \return Packed time for dir_t entry. * \return Packed time for dir_t entry.
*/ */
static inline uint16_t FAT_TIME(uint8_t hour, uint8_t minute, uint8_t second) { static inline uint16_t FAT_TIME(uint8_t hour, uint8_t minute, uint8_t second) { return hour << 11 | minute << 5 | second >> 1; }
return hour << 11 | minute << 5 | second >> 1;
} /**
/** hour part of FAT directory time field * hour part of FAT directory time field
* \param[in] fatTime Time in packed dir format. * \param[in] fatTime Time in packed dir format.
* *
* \return Extracted hour [0,23] * \return Extracted hour [0,23]
*/ */
static inline uint8_t FAT_HOUR(uint16_t fatTime) { static inline uint8_t FAT_HOUR(uint16_t fatTime) { return fatTime >> 11; }
return fatTime >> 11;
} /**
/** minute part of FAT directory time field * minute part of FAT directory time field
* \param[in] fatTime Time in packed dir format. * \param[in] fatTime Time in packed dir format.
* *
* \return Extracted minute [0,59] * \return Extracted minute [0,59]
*/ */
static inline uint8_t FAT_MINUTE(uint16_t fatTime) { static inline uint8_t FAT_MINUTE(uint16_t fatTime) { return (fatTime >> 5) & 0x3F; }
return (fatTime >> 5) & 0x3F;
} /**
/** second part of FAT directory time field * second part of FAT directory time field
* Note second/2 is stored in packed time. * Note second/2 is stored in packed time.
* *
* \param[in] fatTime Time in packed dir format. * \param[in] fatTime Time in packed dir format.
* *
* \return Extracted second [0,58] * \return Extracted second [0,58]
*/ */
static inline uint8_t FAT_SECOND(uint16_t fatTime) { static inline uint8_t FAT_SECOND(uint16_t fatTime) { return 2 * (fatTime & 0x1F); }
return 2 * (fatTime & 0x1F);
} // Default date for file timestamps is 1 Jan 2000
/** Default date for file timestamps is 1 Jan 2000 */
uint16_t const FAT_DEFAULT_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1; uint16_t const FAT_DEFAULT_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1;
/** Default time for file timestamp is 1 am */ // Default time for file timestamp is 1 am
uint16_t const FAT_DEFAULT_TIME = (1 << 11); uint16_t const FAT_DEFAULT_TIME = (1 << 11);
//------------------------------------------------------------------------------
/** /**
* \class SdBaseFile * \class SdBaseFile
* \brief Base class for SdFile with Print and C++ streams. * \brief Base class for SdFile with Print and C++ streams.
*/ */
class SdBaseFile { class SdBaseFile {
public: public:
/** Create an instance. */
SdBaseFile() : writeError(false), type_(FAT_FILE_TYPE_CLOSED) {} SdBaseFile() : writeError(false), type_(FAT_FILE_TYPE_CLOSED) {}
SdBaseFile(const char* path, uint8_t oflag); SdBaseFile(const char* path, uint8_t oflag);
~SdBaseFile() {if (isOpen()) close();} ~SdBaseFile() { if (isOpen()) close(); }
/** /**
* writeError is set to true if an error occurs during a write(). * writeError is set to true if an error occurs during a write().
* Set writeError to false before calling print() and/or write() and check * Set writeError to false before calling print() and/or write() and check
* for true after calls to print() and/or write(). * for true after calls to print() and/or write().
*/ */
bool writeError; bool writeError;
//----------------------------------------------------------------------------
// helpers for stream classes // helpers for stream classes
/** get position for streams
/**
* get position for streams
* \param[out] pos struct to receive position * \param[out] pos struct to receive position
*/ */
void getpos(filepos_t* pos); void getpos(filepos_t* pos);
/** set position for streams
/**
* set position for streams
* \param[out] pos struct with value for new position * \param[out] pos struct with value for new position
*/ */
void setpos(filepos_t* pos); void setpos(filepos_t* pos);
//----------------------------------------------------------------------------
bool close(); bool close();
bool contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); bool contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock);
bool createContiguous(SdBaseFile* dirFile, bool createContiguous(SdBaseFile* dirFile,
const char* path, uint32_t size); const char* path, uint32_t size);
/** \return The current cluster number for a file or directory. */ /**
uint32_t curCluster() const {return curCluster_;} * \return The current cluster number for a file or directory.
/** \return The current position for a file or directory. */ */
uint32_t curPosition() const {return curPosition_;} uint32_t curCluster() const { return curCluster_; }
/** \return Current working directory */
static SdBaseFile* cwd() {return cwd_;} /**
/** Set the date/time callback function * \return The current position for a file or directory.
*/
uint32_t curPosition() const { return curPosition_; }
/**
* \return Current working directory
*/
static SdBaseFile* cwd() { return cwd_; }
/**
* Set the date/time callback function
* *
* \param[in] dateTime The user's call back function. The callback * \param[in] dateTime The user's call back function. The callback
* function is of the form: * function is of the form:
@ -253,35 +243,55 @@ class SdBaseFile {
void (*dateTime)(uint16_t* date, uint16_t* time)) { void (*dateTime)(uint16_t* date, uint16_t* time)) {
dateTime_ = dateTime; dateTime_ = dateTime;
} }
/** Cancel the date/time callback function. */
static void dateTimeCallbackCancel() {dateTime_ = 0;} /**
* Cancel the date/time callback function.
*/
static void dateTimeCallbackCancel() { dateTime_ = 0; }
bool dirEntry(dir_t* dir); bool dirEntry(dir_t* dir);
static void dirName(const dir_t& dir, char* name); static void dirName(const dir_t& dir, char* name);
bool exists(const char* name); bool exists(const char* name);
int16_t fgets(char* str, int16_t num, char* delim = 0); int16_t fgets(char* str, int16_t num, char* delim = 0);
/** \return The total number of bytes in a file or directory. */
uint32_t fileSize() const {return fileSize_;} /**
/** \return The first cluster number for a file or directory. */ * \return The total number of bytes in a file or directory.
uint32_t firstCluster() const {return firstCluster_;} */
bool getFilename(char* name); uint32_t fileSize() const { return fileSize_; }
/** \return True if this is a directory else false. */
bool isDir() const {return type_ >= FAT_FILE_TYPE_MIN_DIR;} /**
/** \return True if this is a normal file else false. */ * \return The first cluster number for a file or directory.
bool isFile() const {return type_ == FAT_FILE_TYPE_NORMAL;} */
/** \return True if this is an open file/directory else false. */ uint32_t firstCluster() const { return firstCluster_; }
bool isOpen() const {return type_ != FAT_FILE_TYPE_CLOSED;}
/** \return True if this is a subdirectory else false. */ /**
bool isSubDir() const {return type_ == FAT_FILE_TYPE_SUBDIR;} * \return True if this is a directory else false.
/** \return True if this is the root directory. */ */
bool isRoot() const { bool isDir() const { return type_ >= FAT_FILE_TYPE_MIN_DIR; }
return type_ == FAT_FILE_TYPE_ROOT_FIXED || type_ == FAT_FILE_TYPE_ROOT32;
} /**
* \return True if this is a normal file else false.
*/
bool isFile() const { return type_ == FAT_FILE_TYPE_NORMAL; }
/**
* \return True if this is an open file/directory else false.
*/
bool isOpen() const { return type_ != FAT_FILE_TYPE_CLOSED; }
/**
* \return True if this is a subdirectory else false.
*/
bool isSubDir() const { return type_ == FAT_FILE_TYPE_SUBDIR; }
/**
* \return True if this is the root directory.
*/
bool isRoot() const { return type_ == FAT_FILE_TYPE_ROOT_FIXED || type_ == FAT_FILE_TYPE_ROOT32; }
bool getFilename(char * const name);
void ls(uint8_t flags = 0, uint8_t indent = 0); void ls(uint8_t flags = 0, uint8_t indent = 0);
bool mkdir(SdBaseFile* dir, const char* path, bool pFlag = true); bool mkdir(SdBaseFile* dir, const char* path, bool pFlag = true);
// alias for backward compactability
bool makeDir(SdBaseFile* dir, const char* path) {
return mkdir(dir, path, false);
}
bool open(SdBaseFile* dirFile, uint16_t index, uint8_t oflag); bool open(SdBaseFile* dirFile, uint16_t index, uint8_t oflag);
bool open(SdBaseFile* dirFile, const char* path, uint8_t oflag); bool open(SdBaseFile* dirFile, const char* path, uint8_t oflag);
bool open(const char* path, uint8_t oflag = O_READ); bool open(const char* path, uint8_t oflag = O_READ);
@ -296,53 +306,58 @@ class SdBaseFile {
int8_t readDir(dir_t* dir, char* longFilename); int8_t readDir(dir_t* dir, char* longFilename);
static bool remove(SdBaseFile* dirFile, const char* path); static bool remove(SdBaseFile* dirFile, const char* path);
bool remove(); bool remove();
/** Set the file's current position to zero. */
void rewind() {seekSet(0);} /**
* Set the file's current position to zero.
*/
void rewind() { seekSet(0); }
bool rename(SdBaseFile* dirFile, const char* newPath); bool rename(SdBaseFile* dirFile, const char* newPath);
bool rmdir(); bool rmdir();
// for backward compatibility
bool rmDir() {return rmdir();}
bool rmRfStar(); bool rmRfStar();
/** Set the files position to current position + \a pos. See seekSet().
/**
* Set the files position to current position + \a pos. See seekSet().
* \param[in] offset The new position in bytes from the current position. * \param[in] offset The new position in bytes from the current position.
* \return true for success or false for failure. * \return true for success or false for failure.
*/ */
bool seekCur(int32_t offset) { bool seekCur(const int32_t offset) { return seekSet(curPosition_ + offset); }
return seekSet(curPosition_ + offset);
} /**
/** Set the files position to end-of-file + \a offset. See seekSet(). * Set the files position to end-of-file + \a offset. See seekSet().
* \param[in] offset The new position in bytes from end-of-file. * \param[in] offset The new position in bytes from end-of-file.
* \return true for success or false for failure. * \return true for success or false for failure.
*/ */
bool seekEnd(int32_t offset = 0) {return seekSet(fileSize_ + offset);} bool seekEnd(const int32_t offset = 0) { return seekSet(fileSize_ + offset); }
bool seekSet(uint32_t pos); bool seekSet(const uint32_t pos);
bool sync(); bool sync();
bool timestamp(SdBaseFile* file); bool timestamp(SdBaseFile* file);
bool timestamp(uint8_t flag, uint16_t year, uint8_t month, uint8_t day, bool timestamp(uint8_t flag, uint16_t year, uint8_t month, uint8_t day,
uint8_t hour, uint8_t minute, uint8_t second); uint8_t hour, uint8_t minute, uint8_t second);
/** Type of file. You should use isFile() or isDir() instead of type()
* if possible. /**
* Type of file. Use isFile() or isDir() instead of type() if possible.
* *
* \return The file or directory type. * \return The file or directory type.
*/ */
uint8_t type() const {return type_;} uint8_t type() const { return type_; }
bool truncate(uint32_t size); bool truncate(uint32_t size);
/** \return SdVolume that contains this file. */
SdVolume* volume() const {return vol_;} /**
* \return SdVolume that contains this file.
*/
SdVolume* volume() const { return vol_; }
int16_t write(const void* buf, uint16_t nbyte); int16_t write(const void* buf, uint16_t nbyte);
//------------------------------------------------------------------------------
private: private:
// allow SdFat to set cwd_ friend class SdFat; // allow SdFat to set cwd_
friend class SdFat; static SdBaseFile* cwd_; // global pointer to cwd dir
// global pointer to cwd dir
static SdBaseFile* cwd_;
// data time callback function // data time callback function
static void (*dateTime_)(uint16_t* date, uint16_t* time); static void (*dateTime_)(uint16_t* date, uint16_t* time);
// bits defined in flags_ // bits defined in flags_
// should be 0x0F static uint8_t const F_OFLAG = (O_ACCMODE | O_APPEND | O_SYNC), // should be 0x0F
static uint8_t const F_OFLAG = (O_ACCMODE | O_APPEND | O_SYNC); F_FILE_DIR_DIRTY = 0x80; // sync of directory entry required
// sync of directory entry required
static uint8_t const F_FILE_DIR_DIRTY = 0x80;
// private data // private data
uint8_t flags_; // See above for definition of flags_ bits uint8_t flags_; // See above for definition of flags_ bits
@ -356,8 +371,11 @@ class SdBaseFile {
uint32_t firstCluster_; // first cluster of file uint32_t firstCluster_; // first cluster of file
SdVolume* vol_; // volume where file is located SdVolume* vol_; // volume where file is located
/** experimental don't use */ /**
bool openParent(SdBaseFile* dir); * EXPERIMENTAL - Don't use!
*/
//bool openParent(SdBaseFile* dir);
// private functions // private functions
bool addCluster(); bool addCluster();
bool addDirCluster(); bool addDirCluster();
@ -368,61 +386,48 @@ class SdBaseFile {
bool open(SdBaseFile* dirFile, const uint8_t dname[11], uint8_t oflag); bool open(SdBaseFile* dirFile, const uint8_t dname[11], uint8_t oflag);
bool openCachedEntry(uint8_t cacheIndex, uint8_t oflags); bool openCachedEntry(uint8_t cacheIndex, uint8_t oflags);
dir_t* readDirCache(); dir_t* readDirCache();
//------------------------------------------------------------------------------
// to be deleted // Deprecated functions
static void printDirName(const dir_t& dir, #if ALLOW_DEPRECATED_FUNCTIONS
uint8_t width, bool printSlash);
//------------------------------------------------------------------------------
// Deprecated functions - suppress cpplint warnings with NOLINT comment
#if ALLOW_DEPRECATED_FUNCTIONS && !defined(DOXYGEN)
public: public:
/** \deprecated Use:
/**
* \deprecated Use:
* bool contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); * bool contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock);
* \param[out] bgnBlock the first block address for the file. * \param[out] bgnBlock the first block address for the file.
* \param[out] endBlock the last block address for the file. * \param[out] endBlock the last block address for the file.
* \return true for success or false for failure. * \return true for success or false for failure.
*/ */
bool contiguousRange(uint32_t& bgnBlock, uint32_t& endBlock) { // NOLINT bool contiguousRange(uint32_t& bgnBlock, uint32_t& endBlock) {
return contiguousRange(&bgnBlock, &endBlock); return contiguousRange(&bgnBlock, &endBlock);
} }
/** \deprecated Use:
* bool createContiguous(SdBaseFile* dirFile, /**
* const char* path, uint32_t size) * \deprecated Use:
* \param[in] dirFile The directory where the file will be created. * bool createContiguous(SdBaseFile* dirFile, const char* path, uint32_t size)
* \param[in] path A path with a valid DOS 8.3 file name. * \param[in] dirFile The directory where the file will be created.
* \param[in] size The desired file size. * \param[in] path A path with a valid DOS 8.3 file name.
* \return true for success or false for failure. * \param[in] size The desired file size.
*/ * \return true for success or false for failure.
bool createContiguous(SdBaseFile& dirFile, // NOLINT */
const char* path, uint32_t size) { bool createContiguous(SdBaseFile& dirFile, const char* path, uint32_t size) {
return createContiguous(&dirFile, path, size); return createContiguous(&dirFile, path, size);
} }
/** \deprecated Use:
/**
* \deprecated Use:
* static void dateTimeCallback( * static void dateTimeCallback(
* void (*dateTime)(uint16_t* date, uint16_t* time)); * void (*dateTime)(uint16_t* date, uint16_t* time));
* \param[in] dateTime The user's call back function. * \param[in] dateTime The user's call back function.
*/ */
static void dateTimeCallback( static void dateTimeCallback(
void (*dateTime)(uint16_t &date, uint16_t &time)) { // NOLINT void (*dateTime)(uint16_t &date, uint16_t &time)) {
oldDateTime_ = dateTime; oldDateTime_ = dateTime;
dateTime_ = dateTime ? oldToNew : 0; dateTime_ = dateTime ? oldToNew : 0;
} }
/** \deprecated Use: bool dirEntry(dir_t* dir);
* \param[out] dir Location for return of the file's directory entry. /**
* \return true for success or false for failure. * \deprecated Use:
*/
bool dirEntry(dir_t& dir) {return dirEntry(&dir);} // NOLINT
/** \deprecated Use:
* bool mkdir(SdBaseFile* dir, const char* path);
* \param[in] dir An open SdFat instance for the directory that will contain
* the new directory.
* \param[in] path A path with a valid 8.3 DOS name for the new directory.
* \return true for success or false for failure.
*/
bool mkdir(SdBaseFile& dir, const char* path) { // NOLINT
return mkdir(&dir, path);
}
/** \deprecated Use:
* bool open(SdBaseFile* dirFile, const char* path, uint8_t oflag); * bool open(SdBaseFile* dirFile, const char* path, uint8_t oflag);
* \param[in] dirFile An open SdFat instance for the directory containing the * \param[in] dirFile An open SdFat instance for the directory containing the
* file to be opened. * file to be opened.
@ -431,20 +436,23 @@ class SdBaseFile {
* OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC.
* \return true for success or false for failure. * \return true for success or false for failure.
*/ */
bool open(SdBaseFile& dirFile, // NOLINT bool open(SdBaseFile& dirFile, const char* path, uint8_t oflag) {
const char* path, uint8_t oflag) {
return open(&dirFile, path, oflag); return open(&dirFile, path, oflag);
} }
/** \deprecated Do not use in new apps
/**
* \deprecated Do not use in new apps
* \param[in] dirFile An open SdFat instance for the directory containing the * \param[in] dirFile An open SdFat instance for the directory containing the
* file to be opened. * file to be opened.
* \param[in] path A path with a valid 8.3 DOS name for a file to be opened. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
* \return true for success or false for failure. * \return true for success or false for failure.
*/ */
bool open(SdBaseFile& dirFile, const char* path) { // NOLINT bool open(SdBaseFile& dirFile, const char* path) {
return open(dirFile, path, O_RDWR); return open(dirFile, path, O_RDWR);
} }
/** \deprecated Use:
/**
* \deprecated Use:
* bool open(SdBaseFile* dirFile, uint16_t index, uint8_t oflag); * bool open(SdBaseFile* dirFile, uint16_t index, uint8_t oflag);
* \param[in] dirFile An open SdFat instance for the directory. * \param[in] dirFile An open SdFat instance for the directory.
* \param[in] index The \a index of the directory entry for the file to be * \param[in] index The \a index of the directory entry for the file to be
@ -453,35 +461,39 @@ class SdBaseFile {
* OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC.
* \return true for success or false for failure. * \return true for success or false for failure.
*/ */
bool open(SdBaseFile& dirFile, uint16_t index, uint8_t oflag) { // NOLINT bool open(SdBaseFile& dirFile, uint16_t index, uint8_t oflag) {
return open(&dirFile, index, oflag); return open(&dirFile, index, oflag);
} }
/** \deprecated Use: bool openRoot(SdVolume* vol);
/**
* \deprecated Use: bool openRoot(SdVolume* vol);
* \param[in] vol The FAT volume containing the root directory to be opened. * \param[in] vol The FAT volume containing the root directory to be opened.
* \return true for success or false for failure. * \return true for success or false for failure.
*/ */
bool openRoot(SdVolume& vol) {return openRoot(&vol);} // NOLINT bool openRoot(SdVolume& vol) { return openRoot(&vol); }
/** \deprecated Use: int8_t readDir(dir_t* dir);
/**
* \deprecated Use: int8_t readDir(dir_t* dir);
* \param[out] dir The dir_t struct that will receive the data. * \param[out] dir The dir_t struct that will receive the data.
* \return bytes read for success zero for eof or -1 for failure. * \return bytes read for success zero for eof or -1 for failure.
*/ */
int8_t readDir(dir_t& dir, char* longFilename) {return readDir(&dir, longFilename);} // NOLINT int8_t readDir(dir_t& dir, char* longFilename) {
/** \deprecated Use: return readDir(&dir, longFilename);
}
/**
* \deprecated Use:
* static uint8_t remove(SdBaseFile* dirFile, const char* path); * static uint8_t remove(SdBaseFile* dirFile, const char* path);
* \param[in] dirFile The directory that contains the file. * \param[in] dirFile The directory that contains the file.
* \param[in] path The name of the file to be removed. * \param[in] path The name of the file to be removed.
* \return true for success or false for failure. * \return true for success or false for failure.
*/ */
static bool remove(SdBaseFile& dirFile, const char* path) { // NOLINT static bool remove(SdBaseFile& dirFile, const char* path) { return remove(&dirFile, path); }
return remove(&dirFile, path);
}
//------------------------------------------------------------------------------
// rest are private
private: private:
static void (*oldDateTime_)(uint16_t &date, uint16_t &time); // NOLINT static void (*oldDateTime_)(uint16_t &date, uint16_t &time);
static void oldToNew(uint16_t* date, uint16_t* time) { static void oldToNew(uint16_t * const date, uint16_t * const time) {
uint16_t d; uint16_t d, t;
uint16_t t;
oldDateTime_(d, t); oldDateTime_(d, t);
*date = d; *date = d;
*time = t; *time = t;
@ -489,4 +501,4 @@ class SdBaseFile {
#endif // ALLOW_DEPRECATED_FUNCTIONS #endif // ALLOW_DEPRECATED_FUNCTIONS
}; };
#endif // SDBASEFILE_H #endif // _SDBASEFILE_H_

@ -33,7 +33,6 @@
#include "../inc/MarlinConfig.h" #include "../inc/MarlinConfig.h"
//------------------------------------------------------------------------------
/** /**
* To use multiple SD cards set USE_MULTIPLE_CARDS nonzero. * To use multiple SD cards set USE_MULTIPLE_CARDS nonzero.
@ -44,8 +43,6 @@
*/ */
#define USE_MULTIPLE_CARDS 0 #define USE_MULTIPLE_CARDS 0
//------------------------------------------------------------------------------
/** /**
* Call flush for endl if ENDL_CALLS_FLUSH is nonzero * Call flush for endl if ENDL_CALLS_FLUSH is nonzero
* *
@ -65,39 +62,29 @@
*/ */
#define ENDL_CALLS_FLUSH 0 #define ENDL_CALLS_FLUSH 0
//------------------------------------------------------------------------------
/** /**
* Allow use of deprecated functions if ALLOW_DEPRECATED_FUNCTIONS is nonzero * Allow use of deprecated functions if ALLOW_DEPRECATED_FUNCTIONS is nonzero
*/ */
#define ALLOW_DEPRECATED_FUNCTIONS 1 #define ALLOW_DEPRECATED_FUNCTIONS 1
//------------------------------------------------------------------------------
/** /**
* Allow FAT12 volumes if FAT12_SUPPORT is nonzero. * Allow FAT12 volumes if FAT12_SUPPORT is nonzero.
* FAT12 has not been well tested. * FAT12 has not been well tested.
*/ */
#define FAT12_SUPPORT 0 #define FAT12_SUPPORT 0
//------------------------------------------------------------------------------
/** /**
* SPI init rate for SD initialization commands. Must be 5 (F_CPU/64) * SPI init rate for SD initialization commands. Must be 5 (F_CPU/64)
* or 6 (F_CPU/128). * or 6 (F_CPU/128).
*/ */
#define SPI_SD_INIT_RATE 5 #define SPI_SD_INIT_RATE 5
//------------------------------------------------------------------------------
/** /**
* Set the SS pin high for hardware SPI. If SS is chip select for another SPI * Set the SS pin high for hardware SPI. If SS is chip select for another SPI
* device this will disable that device during the SD init phase. * device this will disable that device during the SD init phase.
*/ */
#define SET_SPI_SS_HIGH 1 #define SET_SPI_SS_HIGH 1
//------------------------------------------------------------------------------
/** /**
* Define MEGA_SOFT_SPI nonzero to use software SPI on Mega Arduinos. * Define MEGA_SOFT_SPI nonzero to use software SPI on Mega Arduinos.
* Pins used are SS 10, MOSI 11, MISO 12, and SCK 13. * Pins used are SS 10, MOSI 11, MISO 12, and SCK 13.
@ -108,8 +95,6 @@
*/ */
#define MEGA_SOFT_SPI 0 #define MEGA_SOFT_SPI 0
//------------------------------------------------------------------------------
// Set USE_SOFTWARE_SPI nonzero to ALWAYS use Software SPI. // Set USE_SOFTWARE_SPI nonzero to ALWAYS use Software SPI.
#define USE_SOFTWARE_SPI 0 #define USE_SOFTWARE_SPI 0
@ -119,8 +104,6 @@
#define SOFT_SPI_MISO_PIN 12 // Software SPI Master In Slave Out pin #define SOFT_SPI_MISO_PIN 12 // Software SPI Master In Slave Out pin
#define SOFT_SPI_SCK_PIN 13 // Software SPI Clock pin #define SOFT_SPI_SCK_PIN 13 // Software SPI Clock pin
//------------------------------------------------------------------------------
/** /**
* The __cxa_pure_virtual function is an error handler that is invoked when * The __cxa_pure_virtual function is an error handler that is invoked when
* a pure virtual function is called. * a pure virtual function is called.

@ -20,35 +20,33 @@
* *
*/ */
/**
* \file
* \brief FAT file structures
*/
/** /**
* Arduino SdFat Library * Arduino SdFat Library
* Copyright (C) 2009 by William Greiman * Copyright (C) 2009 by William Greiman
* *
* This file is part of the Arduino Sd2Card Library * This file is part of the Arduino Sd2Card Library
*/ */
#ifndef SDFATSTRUCTS_H #ifndef SDFATSTRUCTS_H
#define SDFATSTRUCTS_H #define SDFATSTRUCTS_H
#include <stdint.h> #include <stdint.h>
#define PACKED __attribute__((__packed__)) #define PACKED __attribute__((__packed__))
/**
* \file
* \brief FAT file structures
*/
/** /**
* mostly from Microsoft document fatgen103.doc * mostly from Microsoft document fatgen103.doc
* http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx * http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx
*/ */
//------------------------------------------------------------------------------
/** Value for byte 510 of boot block or MBR */ uint8_t const BOOTSIG0 = 0x55, // Value for byte 510 of boot block or MBR
uint8_t const BOOTSIG0 = 0x55; BOOTSIG1 = 0xAA, // Value for byte 511 of boot block or MBR
/** Value for byte 511 of boot block or MBR */ EXTENDED_BOOT_SIG = 0x29; // Value for bootSignature field int FAT/FAT32 boot sector
uint8_t const BOOTSIG1 = 0xAA;
/** Value for bootSignature field int FAT/FAT32 boot sector */
uint8_t const EXTENDED_BOOT_SIG = 0x29;
//------------------------------------------------------------------------------
/** /**
* \struct partitionTable * \struct partitionTable
* \brief MBR partition table entry * \brief MBR partition table entry
@ -57,59 +55,58 @@ uint8_t const EXTENDED_BOOT_SIG = 0x29;
* The MBR partition table has four entries. * The MBR partition table has four entries.
*/ */
struct partitionTable { struct partitionTable {
/** /**
* Boot Indicator . Indicates whether the volume is the active * Boot Indicator . Indicates whether the volume is the active
* partition. Legal values include: 0x00. Do not use for booting. * partition. Legal values include: 0x00. Do not use for booting.
* 0x80 Active partition. * 0x80 Active partition.
*/ */
uint8_t boot; uint8_t boot;
/** /**
* Head part of Cylinder-head-sector address of the first block in * Head part of Cylinder-head-sector address of the first block in
* the partition. Legal values are 0-255. Only used in old PC BIOS. * the partition. Legal values are 0-255. Only used in old PC BIOS.
*/ */
uint8_t beginHead; uint8_t beginHead;
/** /**
* Sector part of Cylinder-head-sector address of the first block in * Sector part of Cylinder-head-sector address of the first block in
* the partition. Legal values are 1-63. Only used in old PC BIOS. * the partition. Legal values are 1-63. Only used in old PC BIOS.
*/ */
unsigned beginSector : 6; unsigned beginSector : 6;
/** High bits cylinder for first block in partition. */ /** High bits cylinder for first block in partition. */
unsigned beginCylinderHigh : 2; unsigned beginCylinderHigh : 2;
/** /**
* Combine beginCylinderLow with beginCylinderHigh. Legal values * Combine beginCylinderLow with beginCylinderHigh. Legal values
* are 0-1023. Only used in old PC BIOS. * are 0-1023. Only used in old PC BIOS.
*/ */
uint8_t beginCylinderLow; uint8_t beginCylinderLow;
/** /**
* Partition type. See defines that begin with PART_TYPE_ for * Partition type. See defines that begin with PART_TYPE_ for
* some Microsoft partition types. * some Microsoft partition types.
*/ */
uint8_t type; uint8_t type;
/** /**
* head part of cylinder-head-sector address of the last sector in the * head part of cylinder-head-sector address of the last sector in the
* partition. Legal values are 0-255. Only used in old PC BIOS. * partition. Legal values are 0-255. Only used in old PC BIOS.
*/ */
uint8_t endHead; uint8_t endHead;
/** /**
* Sector part of cylinder-head-sector address of the last sector in * Sector part of cylinder-head-sector address of the last sector in
* the partition. Legal values are 1-63. Only used in old PC BIOS. * the partition. Legal values are 1-63. Only used in old PC BIOS.
*/ */
unsigned endSector : 6; unsigned endSector : 6;
/** High bits of end cylinder */ /** High bits of end cylinder */
unsigned endCylinderHigh : 2; unsigned endCylinderHigh : 2;
/** /**
* Combine endCylinderLow with endCylinderHigh. Legal values * Combine endCylinderLow with endCylinderHigh. Legal values
* are 0-1023. Only used in old PC BIOS. * are 0-1023. Only used in old PC BIOS.
*/ */
uint8_t endCylinderLow; uint8_t endCylinderLow;
/** Logical block address of the first block in the partition. */
uint32_t firstSector; uint32_t firstSector; // Logical block address of the first block in the partition.
/** Length of the partition, in blocks. */ uint32_t totalSectors; // Length of the partition, in blocks.
uint32_t totalSectors;
} PACKED; } PACKED;
/** Type name for partitionTable */
typedef struct partitionTable part_t; typedef struct partitionTable part_t; // Type name for partitionTable
//------------------------------------------------------------------------------
/** /**
* \struct masterBootRecord * \struct masterBootRecord
* *
@ -118,22 +115,16 @@ typedef struct partitionTable part_t;
* The first block of a storage device that is formatted with a MBR. * The first block of a storage device that is formatted with a MBR.
*/ */
struct masterBootRecord { struct masterBootRecord {
/** Code Area for master boot program. */ uint8_t codeArea[440]; // Code Area for master boot program.
uint8_t codeArea[440]; uint32_t diskSignature; // Optional Windows NT disk signature. May contain boot code.
/** Optional Windows NT disk signature. May contain boot code. */ uint16_t usuallyZero; // Usually zero but may be more boot code.
uint32_t diskSignature; part_t part[4]; // Partition tables.
/** Usually zero but may be more boot code. */ uint8_t mbrSig0; // First MBR signature byte. Must be 0x55
uint16_t usuallyZero; uint8_t mbrSig1; // Second MBR signature byte. Must be 0xAA
/** Partition tables. */
part_t part[4];
/** First MBR signature byte. Must be 0x55 */
uint8_t mbrSig0;
/** Second MBR signature byte. Must be 0xAA */
uint8_t mbrSig1;
} PACKED; } PACKED;
/** Type name for masterBootRecord */ /** Type name for masterBootRecord */
typedef struct masterBootRecord mbr_t; typedef struct masterBootRecord mbr_t;
//------------------------------------------------------------------------------
/** /**
* \struct fat_boot * \struct fat_boot
* *
@ -141,285 +132,280 @@ typedef struct masterBootRecord mbr_t;
* *
*/ */
struct fat_boot { struct fat_boot {
/** /**
* The first three bytes of the boot sector must be valid, * The first three bytes of the boot sector must be valid,
* executable x 86-based CPU instructions. This includes a * executable x 86-based CPU instructions. This includes a
* jump instruction that skips the next nonexecutable bytes. * jump instruction that skips the next nonexecutable bytes.
*/ */
uint8_t jump[3]; uint8_t jump[3];
/** /**
* This is typically a string of characters that identifies * This is typically a string of characters that identifies
* the operating system that formatted the volume. * the operating system that formatted the volume.
*/ */
char oemId[8]; char oemId[8];
/** /**
* The size of a hardware sector. Valid decimal values for this * The size of a hardware sector. Valid decimal values for this
* field are 512, 1024, 2048, and 4096. For most disks used in * field are 512, 1024, 2048, and 4096. For most disks used in
* the United States, the value of this field is 512. * the United States, the value of this field is 512.
*/ */
uint16_t bytesPerSector; uint16_t bytesPerSector;
/** /**
* Number of sectors per allocation unit. This value must be a * Number of sectors per allocation unit. This value must be a
* power of 2 that is greater than 0. The legal values are * power of 2 that is greater than 0. The legal values are
* 1, 2, 4, 8, 16, 32, 64, and 128. 128 should be avoided. * 1, 2, 4, 8, 16, 32, 64, and 128. 128 should be avoided.
*/ */
uint8_t sectorsPerCluster; uint8_t sectorsPerCluster;
/** /**
* The number of sectors preceding the start of the first FAT, * The number of sectors preceding the start of the first FAT,
* including the boot sector. The value of this field is always 1. * including the boot sector. The value of this field is always 1.
*/ */
uint16_t reservedSectorCount; uint16_t reservedSectorCount;
/** /**
* The number of copies of the FAT on the volume. * The number of copies of the FAT on the volume.
* The value of this field is always 2. * The value of this field is always 2.
*/ */
uint8_t fatCount; uint8_t fatCount;
/** /**
* For FAT12 and FAT16 volumes, this field contains the count of * For FAT12 and FAT16 volumes, this field contains the count of
* 32-byte directory entries in the root directory. For FAT32 volumes, * 32-byte directory entries in the root directory. For FAT32 volumes,
* this field must be set to 0. For FAT12 and FAT16 volumes, this * this field must be set to 0. For FAT12 and FAT16 volumes, this
* value should always specify a count that when multiplied by 32 * value should always specify a count that when multiplied by 32
* results in a multiple of bytesPerSector. FAT16 volumes should * results in a multiple of bytesPerSector. FAT16 volumes should
* use the value 512. * use the value 512.
*/ */
uint16_t rootDirEntryCount; uint16_t rootDirEntryCount;
/** /**
* This field is the old 16-bit total count of sectors on the volume. * This field is the old 16-bit total count of sectors on the volume.
* This count includes the count of all sectors in all four regions * This count includes the count of all sectors in all four regions
* of the volume. This field can be 0; if it is 0, then totalSectors32 * of the volume. This field can be 0; if it is 0, then totalSectors32
* must be nonzero. For FAT32 volumes, this field must be 0. For * must be nonzero. For FAT32 volumes, this field must be 0. For
* FAT12 and FAT16 volumes, this field contains the sector count, and * FAT12 and FAT16 volumes, this field contains the sector count, and
* totalSectors32 is 0 if the total sector count fits * totalSectors32 is 0 if the total sector count fits
* (is less than 0x10000). * (is less than 0x10000).
*/ */
uint16_t totalSectors16; uint16_t totalSectors16;
/** /**
* This dates back to the old MS-DOS 1.x media determination and is * This dates back to the old MS-DOS 1.x media determination and is
* no longer usually used for anything. 0xF8 is the standard value * no longer usually used for anything. 0xF8 is the standard value
* for fixed (nonremovable) media. For removable media, 0xF0 is * for fixed (nonremovable) media. For removable media, 0xF0 is
* frequently used. Legal values are 0xF0 or 0xF8-0xFF. * frequently used. Legal values are 0xF0 or 0xF8-0xFF.
*/ */
uint8_t mediaType; uint8_t mediaType;
/** /**
* Count of sectors occupied by one FAT on FAT12/FAT16 volumes. * Count of sectors occupied by one FAT on FAT12/FAT16 volumes.
* On FAT32 volumes this field must be 0, and sectorsPerFat32 * On FAT32 volumes this field must be 0, and sectorsPerFat32
* contains the FAT size count. * contains the FAT size count.
*/ */
uint16_t sectorsPerFat16; uint16_t sectorsPerFat16;
/** Sectors per track for interrupt 0x13. Not used otherwise. */
uint16_t sectorsPerTrack; uint16_t sectorsPerTrack; // Sectors per track for interrupt 0x13. Not used otherwise.
/** Number of heads for interrupt 0x13. Not used otherwise. */ uint16_t headCount; // Number of heads for interrupt 0x13. Not used otherwise.
uint16_t headCount;
/** /**
* Count of hidden sectors preceding the partition that contains this * Count of hidden sectors preceding the partition that contains this
* FAT volume. This field is generally only relevant for media * FAT volume. This field is generally only relevant for media
* visible on interrupt 0x13. * visible on interrupt 0x13.
*/ */
uint32_t hidddenSectors; uint32_t hidddenSectors;
/** /**
* This field is the new 32-bit total count of sectors on the volume. * This field is the new 32-bit total count of sectors on the volume.
* This count includes the count of all sectors in all four regions * This count includes the count of all sectors in all four regions
* of the volume. This field can be 0; if it is 0, then * of the volume. This field can be 0; if it is 0, then
* totalSectors16 must be nonzero. * totalSectors16 must be nonzero.
*/ */
uint32_t totalSectors32; uint32_t totalSectors32;
/** /**
* Related to the BIOS physical drive number. Floppy drives are * Related to the BIOS physical drive number. Floppy drives are
* identified as 0x00 and physical hard disks are identified as * identified as 0x00 and physical hard disks are identified as
* 0x80, regardless of the number of physical disk drives. * 0x80, regardless of the number of physical disk drives.
* Typically, this value is set prior to issuing an INT 13h BIOS * Typically, this value is set prior to issuing an INT 13h BIOS
* call to specify the device to access. The value is only * call to specify the device to access. The value is only
* relevant if the device is a boot device. * relevant if the device is a boot device.
*/ */
uint8_t driveNumber; uint8_t driveNumber;
/** used by Windows NT - should be zero for FAT */
uint8_t reserved1; uint8_t reserved1; // used by Windows NT - should be zero for FAT
/** 0x29 if next three fields are valid */ uint8_t bootSignature; // 0x29 if next three fields are valid
uint8_t bootSignature;
/** /**
* A random serial number created when formatting a disk, * A random serial number created when formatting a disk,
* which helps to distinguish between disks. * which helps to distinguish between disks.
* Usually generated by combining date and time. * Usually generated by combining date and time.
*/ */
uint32_t volumeSerialNumber; uint32_t volumeSerialNumber;
/** /**
* A field once used to store the volume label. The volume label * A field once used to store the volume label. The volume label
* is now stored as a special file in the root directory. * is now stored as a special file in the root directory.
*/ */
char volumeLabel[11]; char volumeLabel[11];
/** /**
* A field with a value of either FAT, FAT12 or FAT16, * A field with a value of either FAT, FAT12 or FAT16,
* depending on the disk format. * depending on the disk format.
*/ */
char fileSystemType[8]; char fileSystemType[8];
/** X86 boot code */
uint8_t bootCode[448]; uint8_t bootCode[448]; // X86 boot code
/** must be 0x55 */ uint8_t bootSectorSig0; // must be 0x55
uint8_t bootSectorSig0; uint8_t bootSectorSig1; // must be 0xAA
/** must be 0xAA */
uint8_t bootSectorSig1;
} PACKED; } PACKED;
/** Type name for FAT Boot Sector */
typedef struct fat_boot fat_boot_t; typedef struct fat_boot fat_boot_t; // Type name for FAT Boot Sector
//------------------------------------------------------------------------------
/** /**
* \struct fat32_boot * \struct fat32_boot
* *
* \brief Boot sector for a FAT32 volume. * \brief Boot sector for a FAT32 volume.
*
*/ */
struct fat32_boot { struct fat32_boot {
/** /**
* The first three bytes of the boot sector must be valid, * The first three bytes of the boot sector must be valid,
* executable x 86-based CPU instructions. This includes a * executable x 86-based CPU instructions. This includes a
* jump instruction that skips the next nonexecutable bytes. * jump instruction that skips the next nonexecutable bytes.
*/ */
uint8_t jump[3]; uint8_t jump[3];
/** /**
* This is typically a string of characters that identifies * This is typically a string of characters that identifies
* the operating system that formatted the volume. * the operating system that formatted the volume.
*/ */
char oemId[8]; char oemId[8];
/** /**
* The size of a hardware sector. Valid decimal values for this * The size of a hardware sector. Valid decimal values for this
* field are 512, 1024, 2048, and 4096. For most disks used in * field are 512, 1024, 2048, and 4096. For most disks used in
* the United States, the value of this field is 512. * the United States, the value of this field is 512.
*/ */
uint16_t bytesPerSector; uint16_t bytesPerSector;
/** /**
* Number of sectors per allocation unit. This value must be a * Number of sectors per allocation unit. This value must be a
* power of 2 that is greater than 0. The legal values are * power of 2 that is greater than 0. The legal values are
* 1, 2, 4, 8, 16, 32, 64, and 128. 128 should be avoided. * 1, 2, 4, 8, 16, 32, 64, and 128. 128 should be avoided.
*/ */
uint8_t sectorsPerCluster; uint8_t sectorsPerCluster;
/** /**
* The number of sectors preceding the start of the first FAT, * The number of sectors preceding the start of the first FAT,
* including the boot sector. Must not be zero * including the boot sector. Must not be zero
*/ */
uint16_t reservedSectorCount; uint16_t reservedSectorCount;
/** /**
* The number of copies of the FAT on the volume. * The number of copies of the FAT on the volume.
* The value of this field is always 2. * The value of this field is always 2.
*/ */
uint8_t fatCount; uint8_t fatCount;
/** /**
* FAT12/FAT16 only. For FAT32 volumes, this field must be set to 0. * FAT12/FAT16 only. For FAT32 volumes, this field must be set to 0.
*/ */
uint16_t rootDirEntryCount; uint16_t rootDirEntryCount;
/** /**
* For FAT32 volumes, this field must be 0. * For FAT32 volumes, this field must be 0.
*/ */
uint16_t totalSectors16; uint16_t totalSectors16;
/** /**
* This dates back to the old MS-DOS 1.x media determination and is * This dates back to the old MS-DOS 1.x media determination and is
* no longer usually used for anything. 0xF8 is the standard value * no longer usually used for anything. 0xF8 is the standard value
* for fixed (nonremovable) media. For removable media, 0xF0 is * for fixed (nonremovable) media. For removable media, 0xF0 is
* frequently used. Legal values are 0xF0 or 0xF8-0xFF. * frequently used. Legal values are 0xF0 or 0xF8-0xFF.
*/ */
uint8_t mediaType; uint8_t mediaType;
/** /**
* On FAT32 volumes this field must be 0, and sectorsPerFat32 * On FAT32 volumes this field must be 0, and sectorsPerFat32
* contains the FAT size count. * contains the FAT size count.
*/ */
uint16_t sectorsPerFat16; uint16_t sectorsPerFat16;
/** Sectors per track for interrupt 0x13. Not used otherwise. */
uint16_t sectorsPerTrack; uint16_t sectorsPerTrack; // Sectors per track for interrupt 0x13. Not used otherwise.
/** Number of heads for interrupt 0x13. Not used otherwise. */ uint16_t headCount; // Number of heads for interrupt 0x13. Not used otherwise.
uint16_t headCount;
/** /**
* Count of hidden sectors preceding the partition that contains this * Count of hidden sectors preceding the partition that contains this
* FAT volume. This field is generally only relevant for media * FAT volume. This field is generally only relevant for media
* visible on interrupt 0x13. * visible on interrupt 0x13.
*/ */
uint32_t hidddenSectors; uint32_t hidddenSectors;
/** /**
* Contains the total number of sectors in the FAT32 volume. * Contains the total number of sectors in the FAT32 volume.
*/ */
uint32_t totalSectors32; uint32_t totalSectors32;
/** /**
* Count of sectors occupied by one FAT on FAT32 volumes. * Count of sectors occupied by one FAT on FAT32 volumes.
*/ */
uint32_t sectorsPerFat32; uint32_t sectorsPerFat32;
/** /**
* This field is only defined for FAT32 media and does not exist on * This field is only defined for FAT32 media and does not exist on
* FAT12 and FAT16 media. * FAT12 and FAT16 media.
* Bits 0-3 -- Zero-based number of active FAT. * Bits 0-3 -- Zero-based number of active FAT.
* Only valid if mirroring is disabled. * Only valid if mirroring is disabled.
* Bits 4-6 -- Reserved. * Bits 4-6 -- Reserved.
* Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. * Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs.
* -- 1 means only one FAT is active; it is the one referenced * -- 1 means only one FAT is active; it is the one referenced
* in bits 0-3. * in bits 0-3.
* Bits 8-15 -- Reserved. * Bits 8-15 -- Reserved.
*/ */
uint16_t fat32Flags; uint16_t fat32Flags;
/** /**
* FAT32 version. High byte is major revision number. * FAT32 version. High byte is major revision number.
* Low byte is minor revision number. Only 0.0 define. * Low byte is minor revision number. Only 0.0 define.
*/ */
uint16_t fat32Version; uint16_t fat32Version;
/** /**
* Cluster number of the first cluster of the root directory for FAT32. * Cluster number of the first cluster of the root directory for FAT32.
* This usually 2 but not required to be 2. * This usually 2 but not required to be 2.
*/ */
uint32_t fat32RootCluster; uint32_t fat32RootCluster;
/** /**
* Sector number of FSINFO structure in the reserved area of the * Sector number of FSINFO structure in the reserved area of the
* FAT32 volume. Usually 1. * FAT32 volume. Usually 1.
*/ */
uint16_t fat32FSInfo; uint16_t fat32FSInfo;
/** /**
* If nonzero, indicates the sector number in the reserved area * If nonzero, indicates the sector number in the reserved area
* of the volume of a copy of the boot record. Usually 6. * of the volume of a copy of the boot record. Usually 6.
* No value other than 6 is recommended. * No value other than 6 is recommended.
*/ */
uint16_t fat32BackBootBlock; uint16_t fat32BackBootBlock;
/** /**
* Reserved for future expansion. Code that formats FAT32 volumes * Reserved for future expansion. Code that formats FAT32 volumes
* should always set all of the bytes of this field to 0. * should always set all of the bytes of this field to 0.
*/ */
uint8_t fat32Reserved[12]; uint8_t fat32Reserved[12];
/** /**
* Related to the BIOS physical drive number. Floppy drives are * Related to the BIOS physical drive number. Floppy drives are
* identified as 0x00 and physical hard disks are identified as * identified as 0x00 and physical hard disks are identified as
* 0x80, regardless of the number of physical disk drives. * 0x80, regardless of the number of physical disk drives.
* Typically, this value is set prior to issuing an INT 13h BIOS * Typically, this value is set prior to issuing an INT 13h BIOS
* call to specify the device to access. The value is only * call to specify the device to access. The value is only
* relevant if the device is a boot device. * relevant if the device is a boot device.
*/ */
uint8_t driveNumber; uint8_t driveNumber;
/** used by Windows NT - should be zero for FAT */
uint8_t reserved1; uint8_t reserved1; // Used by Windows NT - should be zero for FAT
/** 0x29 if next three fields are valid */ uint8_t bootSignature; // 0x29 if next three fields are valid
uint8_t bootSignature;
/** /**
* A random serial number created when formatting a disk, * A random serial number created when formatting a disk,
* which helps to distinguish between disks. * which helps to distinguish between disks.
* Usually generated by combining date and time. * Usually generated by combining date and time.
*/ */
uint32_t volumeSerialNumber; uint32_t volumeSerialNumber;
/** /**
* A field once used to store the volume label. The volume label * A field once used to store the volume label. The volume label
* is now stored as a special file in the root directory. * is now stored as a special file in the root directory.
*/ */
char volumeLabel[11]; char volumeLabel[11];
/** /**
* A text field with a value of FAT32. * A text field with a value of FAT32.
*/ */
char fileSystemType[8]; char fileSystemType[8];
/** X86 boot code */
uint8_t bootCode[420]; uint8_t bootCode[420]; // X86 boot code
/** must be 0x55 */ uint8_t bootSectorSig0; // must be 0x55
uint8_t bootSectorSig0; uint8_t bootSectorSig1; // must be 0xAA
/** must be 0xAA */
uint8_t bootSectorSig1;
} PACKED; } PACKED;
/** Type name for FAT32 Boot Sector */
typedef struct fat32_boot fat32_boot_t; typedef struct fat32_boot fat32_boot_t; // Type name for FAT32 Boot Sector
//------------------------------------------------------------------------------
/** Lead signature for a FSINFO sector */ uint32_t const FSINFO_LEAD_SIG = 0x41615252, // 'AaRR' Lead signature for a FSINFO sector
uint32_t const FSINFO_LEAD_SIG = 0x41615252; FSINFO_STRUCT_SIG = 0x61417272; // 'aArr' Struct signature for a FSINFO sector
/** Struct signature for a FSINFO sector */
uint32_t const FSINFO_STRUCT_SIG = 0x61417272;
/** /**
* \struct fat32_fsinfo * \struct fat32_fsinfo
* *
@ -427,12 +413,9 @@ uint32_t const FSINFO_STRUCT_SIG = 0x61417272;
* *
*/ */
struct fat32_fsinfo { struct fat32_fsinfo {
/** must be 0x52, 0x52, 0x61, 0x41 */ uint32_t leadSignature; // must be 0x52, 0x52, 0x61, 0x41 'RRaA'
uint32_t leadSignature; uint8_t reserved1[480]; // must be zero
/** must be zero */ uint32_t structSignature; // must be 0x72, 0x72, 0x41, 0x61 'rrAa'
uint8_t reserved1[480];
/** must be 0x72, 0x72, 0x41, 0x61 */
uint32_t structSignature;
/** /**
* Contains the last known free cluster count on the volume. * Contains the last known free cluster count on the volume.
* If the value is 0xFFFFFFFF, then the free count is unknown * If the value is 0xFFFFFFFF, then the free count is unknown
@ -448,30 +431,22 @@ struct fat32_fsinfo {
* should start looking at cluster 2. * should start looking at cluster 2.
*/ */
uint32_t nextFree; uint32_t nextFree;
/** must be zero */
uint8_t reserved2[12]; uint8_t reserved2[12]; // must be zero
/** must be 0x00, 0x00, 0x55, 0xAA */ uint8_t tailSignature[4]; // must be 0x00, 0x00, 0x55, 0xAA
uint8_t tailSignature[4];
} PACKED; } PACKED;
/** Type name for FAT32 FSINFO Sector */
typedef struct fat32_fsinfo fat32_fsinfo_t; typedef struct fat32_fsinfo fat32_fsinfo_t; // Type name for FAT32 FSINFO Sector
//------------------------------------------------------------------------------
// End Of Chain values for FAT entries // End Of Chain values for FAT entries
/** FAT12 end of chain value used by Microsoft. */ uint16_t const FAT12EOC = 0xFFF, // FAT12 end of chain value used by Microsoft.
uint16_t const FAT12EOC = 0xFFF; FAT12EOC_MIN = 0xFF8, // Minimum value for FAT12 EOC. Use to test for EOC.
/** Minimum value for FAT12 EOC. Use to test for EOC. */ FAT16EOC = 0xFFFF, // FAT16 end of chain value used by Microsoft.
uint16_t const FAT12EOC_MIN = 0xFF8; FAT16EOC_MIN = 0xFFF8; // Minimum value for FAT16 EOC. Use to test for EOC.
/** FAT16 end of chain value used by Microsoft. */ uint32_t const FAT32EOC = 0x0FFFFFFF, // FAT32 end of chain value used by Microsoft.
uint16_t const FAT16EOC = 0xFFFF; FAT32EOC_MIN = 0x0FFFFFF8, // Minimum value for FAT32 EOC. Use to test for EOC.
/** Minimum value for FAT16 EOC. Use to test for EOC. */ FAT32MASK = 0x0FFFFFFF; // Mask a for FAT32 entry. Entries are 28 bits.
uint16_t const FAT16EOC_MIN = 0xFFF8;
/** FAT32 end of chain value used by Microsoft. */
uint32_t const FAT32EOC = 0x0FFFFFFF;
/** Minimum value for FAT32 EOC. Use to test for EOC. */
uint32_t const FAT32EOC_MIN = 0x0FFFFFF8;
/** Mask a for FAT32 entry. Entries are 28 bits. */
uint32_t const FAT32MASK = 0x0FFFFFFF;
//------------------------------------------------------------------------------
/** /**
* \struct directoryEntry * \struct directoryEntry
* \brief FAT short directory entry * \brief FAT short directory entry
@ -503,54 +478,54 @@ uint32_t const FAT32MASK = 0x0FFFFFFF;
* The valid time range is from Midnight 00:00:00 to 23:59:58. * The valid time range is from Midnight 00:00:00 to 23:59:58.
*/ */
struct directoryEntry { struct directoryEntry {
/** Short 8.3 name. /**
* * Short 8.3 name.
* The first eight bytes contain the file name with blank fill. *
* The last three bytes contain the file extension with blank fill. * The first eight bytes contain the file name with blank fill.
*/ * The last three bytes contain the file extension with blank fill.
*/
uint8_t name[11]; uint8_t name[11];
/** Entry attributes. /**
* * Entry attributes.
* The upper two bits of the attribute byte are reserved and should *
* always be set to 0 when a file is created and never modified or * The upper two bits of the attribute byte are reserved and should
* looked at after that. See defines that begin with DIR_ATT_. * always be set to 0 when a file is created and never modified or
*/ * looked at after that. See defines that begin with DIR_ATT_.
*/
uint8_t attributes; uint8_t attributes;
/** /**
* Reserved for use by Windows NT. Set value to 0 when a file is * Reserved for use by Windows NT. Set value to 0 when a file is
* created and never modify or look at it after that. * created and never modify or look at it after that.
*/ */
uint8_t reservedNT; uint8_t reservedNT;
/** /**
* The granularity of the seconds part of creationTime is 2 seconds * The granularity of the seconds part of creationTime is 2 seconds
* so this field is a count of tenths of a second and it's valid * so this field is a count of tenths of a second and it's valid
* value range is 0-199 inclusive. (WHG note - seems to be hundredths) * value range is 0-199 inclusive. (WHG note - seems to be hundredths)
*/ */
uint8_t creationTimeTenths; uint8_t creationTimeTenths;
/** Time file was created. */
uint16_t creationTime; uint16_t creationTime; // Time file was created.
/** Date file was created. */ uint16_t creationDate; // Date file was created.
uint16_t creationDate;
/** /**
* Last access date. Note that there is no last access time, only * Last access date. Note that there is no last access time, only
* a date. This is the date of last read or write. In the case of * a date. This is the date of last read or write. In the case of
* a write, this should be set to the same date as lastWriteDate. * a write, this should be set to the same date as lastWriteDate.
*/ */
uint16_t lastAccessDate; uint16_t lastAccessDate;
/** /**
* High word of this entry's first cluster number (always 0 for a * High word of this entry's first cluster number (always 0 for a
* FAT12 or FAT16 volume). * FAT12 or FAT16 volume).
*/ */
uint16_t firstClusterHigh; uint16_t firstClusterHigh;
/** Time of last write. File creation is considered a write. */
uint16_t lastWriteTime; uint16_t lastWriteTime; // Time of last write. File creation is considered a write.
/** Date of last write. File creation is considered a write. */ uint16_t lastWriteDate; // Date of last write. File creation is considered a write.
uint16_t lastWriteDate; uint16_t firstClusterLow; // Low word of this entry's first cluster number.
/** Low word of this entry's first cluster number. */ uint32_t fileSize; // 32-bit unsigned holding this file's size in bytes.
uint16_t firstClusterLow;
/** 32-bit unsigned holding this file's size in bytes. */
uint32_t fileSize;
} PACKED; } PACKED;
/** /**
* \struct directoryVFATEntry * \struct directoryVFATEntry
* \brief VFAT long filename directory entry * \brief VFAT long filename directory entry
@ -568,54 +543,36 @@ struct directoryVFATEntry {
* bit 0-4: the position of this long filename block (first block is 1) * bit 0-4: the position of this long filename block (first block is 1)
*/ */
uint8_t sequenceNumber; uint8_t sequenceNumber;
/** First set of UTF-16 characters */
uint16_t name1[5];//UTF-16 uint16_t name1[5]; // First set of UTF-16 characters
/** attributes (at the same location as in directoryEntry), always 0x0F */ uint8_t attributes; // attributes (at the same location as in directoryEntry), always 0x0F
uint8_t attributes; uint8_t reservedNT; // Reserved for use by Windows NT. Always 0.
/** Reserved for use by Windows NT. Always 0. */ uint8_t checksum; // Checksum of the short 8.3 filename, can be used to checked if the file system as modified by a not-long-filename aware implementation.
uint8_t reservedNT; uint16_t name2[6]; // Second set of UTF-16 characters
/** Checksum of the short 8.3 filename, can be used to checked if the file system as modified by a not-long-filename aware implementation. */ uint16_t firstClusterLow; // firstClusterLow is always zero for longFilenames
uint8_t checksum; uint16_t name3[2]; // Third set of UTF-16 characters
/** Second set of UTF-16 characters */
uint16_t name2[6];//UTF-16
/** firstClusterLow is always zero for longFilenames */
uint16_t firstClusterLow;
/** Third set of UTF-16 characters */
uint16_t name3[2];//UTF-16
} PACKED; } PACKED;
//------------------------------------------------------------------------------
// Definitions for directory entries // Definitions for directory entries
// //
/** Type name for directoryEntry */ typedef struct directoryEntry dir_t; // Type name for directoryEntry
typedef struct directoryEntry dir_t; typedef struct directoryVFATEntry vfat_t; // Type name for directoryVFATEntry
/** Type name for directoryVFATEntry */
typedef struct directoryVFATEntry vfat_t; uint8_t const DIR_NAME_0xE5 = 0x05, // escape for name[0] = 0xE5
/** escape for name[0] = 0xE5 */ DIR_NAME_DELETED = 0xE5, // name[0] value for entry that is free after being "deleted"
uint8_t const DIR_NAME_0xE5 = 0x05; DIR_NAME_FREE = 0x00, // name[0] value for entry that is free and no allocated entries follow
/** name[0] value for entry that is free after being "deleted" */ DIR_ATT_READ_ONLY = 0x01, // file is read-only
uint8_t const DIR_NAME_DELETED = 0xE5; DIR_ATT_HIDDEN = 0x02, // File should hidden in directory listings
/** name[0] value for entry that is free and no allocated entries follow */ DIR_ATT_SYSTEM = 0x04, // Entry is for a system file
uint8_t const DIR_NAME_FREE = 0x00; DIR_ATT_VOLUME_ID = 0x08, // Directory entry contains the volume label
/** file is read-only */ DIR_ATT_DIRECTORY = 0x10, // Entry is for a directory
uint8_t const DIR_ATT_READ_ONLY = 0x01; DIR_ATT_ARCHIVE = 0x20, // Old DOS archive bit for backup support
/** File should hidden in directory listings */ DIR_ATT_LONG_NAME = 0x0F, // Test value for long name entry. Test is (d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME.
uint8_t const DIR_ATT_HIDDEN = 0x02; DIR_ATT_LONG_NAME_MASK = 0x3F, // Test mask for long name entry
/** Entry is for a system file */ DIR_ATT_DEFINED_BITS = 0x3F; // defined attribute bits
uint8_t const DIR_ATT_SYSTEM = 0x04;
/** Directory entry contains the volume label */ /**
uint8_t const DIR_ATT_VOLUME_ID = 0x08; * Directory entry is part of a long name
/** Entry is for a directory */
uint8_t const DIR_ATT_DIRECTORY = 0x10;
/** Old DOS archive bit for backup support */
uint8_t const DIR_ATT_ARCHIVE = 0x20;
/** Test value for long name entry. Test is
(d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME. */
uint8_t const DIR_ATT_LONG_NAME = 0x0F;
/** Test mask for long name entry */
uint8_t const DIR_ATT_LONG_NAME_MASK = 0x3F;
/** defined attribute bits */
uint8_t const DIR_ATT_DEFINED_BITS = 0x3F;
/** Directory entry is part of a long name
* \param[in] dir Pointer to a directory entry. * \param[in] dir Pointer to a directory entry.
* *
* \return true if the entry is for part of a long name else false. * \return true if the entry is for part of a long name else false.
@ -623,9 +580,12 @@ uint8_t const DIR_ATT_DEFINED_BITS = 0x3F;
static inline uint8_t DIR_IS_LONG_NAME(const dir_t* dir) { static inline uint8_t DIR_IS_LONG_NAME(const dir_t* dir) {
return (dir->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME; return (dir->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME;
} }
/** Mask for file/subdirectory tests */ /** Mask for file/subdirectory tests */
uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY); uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY);
/** Directory entry is for a file
/**
* Directory entry is for a file
* \param[in] dir Pointer to a directory entry. * \param[in] dir Pointer to a directory entry.
* *
* \return true if the entry is for a normal file else false. * \return true if the entry is for a normal file else false.
@ -633,7 +593,9 @@ uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY);
static inline uint8_t DIR_IS_FILE(const dir_t* dir) { static inline uint8_t DIR_IS_FILE(const dir_t* dir) {
return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0; return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0;
} }
/** Directory entry is for a subdirectory
/**
* Directory entry is for a subdirectory
* \param[in] dir Pointer to a directory entry. * \param[in] dir Pointer to a directory entry.
* *
* \return true if the entry is for a subdirectory else false. * \return true if the entry is for a subdirectory else false.
@ -641,7 +603,9 @@ static inline uint8_t DIR_IS_FILE(const dir_t* dir) {
static inline uint8_t DIR_IS_SUBDIR(const dir_t* dir) { static inline uint8_t DIR_IS_SUBDIR(const dir_t* dir) {
return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY; return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY;
} }
/** Directory entry is for a file or subdirectory
/**
* Directory entry is for a file or subdirectory
* \param[in] dir Pointer to a directory entry. * \param[in] dir Pointer to a directory entry.
* *
* \return true if the entry is for a normal file or subdirectory else false. * \return true if the entry is for a normal file or subdirectory else false.

@ -33,8 +33,8 @@
#include "SdFatUtil.h" #include "SdFatUtil.h"
//------------------------------------------------------------------------------ /**
/** Amount of free RAM * Amount of free RAM
* \return The number of free bytes. * \return The number of free bytes.
*/ */
#ifdef __arm__ #ifdef __arm__
@ -46,7 +46,8 @@ int SdFatUtil::FreeRam() {
#else // __arm__ #else // __arm__
extern char* __brkval; extern char* __brkval;
extern char __bss_end; extern char __bss_end;
/** Amount of free RAM /**
* Amount of free RAM
* \return The number of free bytes. * \return The number of free bytes.
*/ */
int SdFatUtil::FreeRam() { int SdFatUtil::FreeRam() {
@ -55,8 +56,8 @@ int SdFatUtil::FreeRam() {
} }
#endif // __arm #endif // __arm
//------------------------------------------------------------------------------ /**
/** %Print a string in flash memory. * %Print a string in flash memory.
* *
* \param[in] pr Print object for output. * \param[in] pr Print object for output.
* \param[in] str Pointer to string stored in flash memory. * \param[in] str Pointer to string stored in flash memory.
@ -64,31 +65,27 @@ int SdFatUtil::FreeRam() {
void SdFatUtil::print_P(PGM_P str) { void SdFatUtil::print_P(PGM_P str) {
for (uint8_t c; (c = pgm_read_byte(str)); str++) MYSERIAL.write(c); for (uint8_t c; (c = pgm_read_byte(str)); str++) MYSERIAL.write(c);
} }
//------------------------------------------------------------------------------
/** %Print a string in flash memory followed by a CR/LF. /**
* %Print a string in flash memory followed by a CR/LF.
* *
* \param[in] pr Print object for output. * \param[in] pr Print object for output.
* \param[in] str Pointer to string stored in flash memory. * \param[in] str Pointer to string stored in flash memory.
*/ */
void SdFatUtil::println_P(PGM_P str) { void SdFatUtil::println_P(PGM_P str) { print_P(str); MYSERIAL.println(); }
print_P(str);
MYSERIAL.println(); /**
} * %Print a string in flash memory to Serial.
//------------------------------------------------------------------------------
/** %Print a string in flash memory to Serial.
* *
* \param[in] str Pointer to string stored in flash memory. * \param[in] str Pointer to string stored in flash memory.
*/ */
void SdFatUtil::SerialPrint_P(PGM_P str) { void SdFatUtil::SerialPrint_P(PGM_P str) { print_P(str); }
print_P(str);
} /**
//------------------------------------------------------------------------------ * %Print a string in flash memory to Serial followed by a CR/LF.
/** %Print a string in flash memory to Serial followed by a CR/LF.
* *
* \param[in] str Pointer to string stored in flash memory. * \param[in] str Pointer to string stored in flash memory.
*/ */
void SdFatUtil::SerialPrintln_P(PGM_P str) { void SdFatUtil::SerialPrintln_P(PGM_P str) { println_P(str); }
println_P(str);
}
#endif // SDSUPPORT #endif // SDSUPPORT

@ -26,8 +26,8 @@
* *
* This file is part of the Arduino Sd2Card Library * This file is part of the Arduino Sd2Card Library
*/ */
#ifndef SDFATUTIL_H #ifndef _SDFATUTIL_H_
#define SDFATUTIL_H #define _SDFATUTIL_H_
#include <string.h> #include <string.h>
@ -50,4 +50,4 @@ namespace SdFatUtil {
using namespace SdFatUtil; // NOLINT using namespace SdFatUtil; // NOLINT
#endif // SDFATUTIL_H #endif // _SDFATUTIL_H_

@ -33,17 +33,18 @@
#include "SdFile.h" #include "SdFile.h"
/** Create a file object and open it in the current working directory. /**
* Create a file object and open it in the current working directory.
* *
* \param[in] path A path with a valid 8.3 DOS name for a file to be opened. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
* *
* \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
* OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t). * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
*/ */
SdFile::SdFile(const char* path, uint8_t oflag) : SdBaseFile(path, oflag) { SdFile::SdFile(const char* path, uint8_t oflag) : SdBaseFile(path, oflag) { }
}
//------------------------------------------------------------------------------ /**
/** Write data to an open file. * Write data to an open file.
* *
* \note Data is moved to the cache but may not be written to the * \note Data is moved to the cache but may not be written to the
* storage device until sync() is called. * storage device until sync() is called.
@ -58,41 +59,37 @@ SdFile::SdFile(const char* path, uint8_t oflag) : SdBaseFile(path, oflag) {
* for a read-only file, device is full, a corrupt file system or an I/O error. * for a read-only file, device is full, a corrupt file system or an I/O error.
* *
*/ */
int16_t SdFile::write(const void* buf, uint16_t nbyte) { int16_t SdFile::write(const void* buf, uint16_t nbyte) { return SdBaseFile::write(buf, nbyte); }
return SdBaseFile::write(buf, nbyte);
} /**
//------------------------------------------------------------------------------ * Write a byte to a file. Required by the Arduino Print class.
/** Write a byte to a file. Required by the Arduino Print class.
* \param[in] b the byte to be written. * \param[in] b the byte to be written.
* Use writeError to check for errors. * Use writeError to check for errors.
*/ */
#if ARDUINO >= 100 #if ARDUINO >= 100
size_t SdFile::write(uint8_t b) { size_t SdFile::write(uint8_t b) { return SdBaseFile::write(&b, 1); }
return SdBaseFile::write(&b, 1);
}
#else #else
void SdFile::write(uint8_t b) { void SdFile::write(uint8_t b) { SdBaseFile::write(&b, 1); }
SdBaseFile::write(&b, 1);
}
#endif #endif
//------------------------------------------------------------------------------
/** Write a string to a file. Used by the Arduino Print class. /**
* Write a string to a file. Used by the Arduino Print class.
* \param[in] str Pointer to the string. * \param[in] str Pointer to the string.
* Use writeError to check for errors. * Use writeError to check for errors.
*/ */
void SdFile::write(const char* str) { void SdFile::write(const char* str) { SdBaseFile::write(str, strlen(str)); }
SdBaseFile::write(str, strlen(str));
} /**
//------------------------------------------------------------------------------ * Write a PROGMEM string to a file.
/** Write a PROGMEM string to a file.
* \param[in] str Pointer to the PROGMEM string. * \param[in] str Pointer to the PROGMEM string.
* Use writeError to check for errors. * Use writeError to check for errors.
*/ */
void SdFile::write_P(PGM_P str) { void SdFile::write_P(PGM_P str) {
for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c); for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c);
} }
//------------------------------------------------------------------------------
/** Write a PROGMEM string followed by CR/LF to a file. /**
* Write a PROGMEM string followed by CR/LF to a file.
* \param[in] str Pointer to the PROGMEM string. * \param[in] str Pointer to the PROGMEM string.
* Use writeError to check for errors. * Use writeError to check for errors.
*/ */
@ -101,5 +98,4 @@ void SdFile::writeln_P(PGM_P str) {
write_P(PSTR("\r\n")); write_P(PSTR("\r\n"));
} }
#endif // SDSUPPORT
#endif

@ -20,27 +20,25 @@
* *
*/ */
/**
* \file
* \brief SdFile class
*/
/** /**
* Arduino SdFat Library * Arduino SdFat Library
* Copyright (C) 2009 by William Greiman * Copyright (C) 2009 by William Greiman
* *
* This file is part of the Arduino Sd2Card Library * This file is part of the Arduino Sd2Card Library
*/ */
#ifndef _SDFILE_H_
/** #define _SDFILE_H_
* \file
* \brief SdFile class
*/
#ifndef SDFILE_H
#define SDFILE_H
#include "SdBaseFile.h" #include "SdBaseFile.h"
#include <stdint.h> #include <stdint.h>
#include <string.h> #include <string.h>
//------------------------------------------------------------------------------
/** /**
* \class SdFile * \class SdFile
* \brief SdBaseFile with Print. * \brief SdBaseFile with Print.
@ -61,4 +59,4 @@ class SdFile : public SdBaseFile/*, public Print*/ {
void writeln_P(PGM_P str); void writeln_P(PGM_P str);
}; };
#endif // SDFILE_H #endif // _SDFILE_H_

@ -26,8 +26,8 @@
* *
* This file is part of the Arduino Sd2Card Library * This file is part of the Arduino Sd2Card Library
*/ */
#ifndef SDINFO_H #ifndef _SDINFO_H_
#define SDINFO_H #define _SDINFO_H_
#include <stdint.h> #include <stdint.h>
@ -41,46 +41,26 @@
// May 18, 2010 // May 18, 2010
// //
// http://www.sdcard.org/developers/tech/sdcard/pls/simplified_specs // http://www.sdcard.org/developers/tech/sdcard/pls/simplified_specs
//------------------------------------------------------------------------------
// SD card commands // SD card commands
/** GO_IDLE_STATE - init card in spi mode if CS low */ uint8_t const CMD0 = 0x00, // GO_IDLE_STATE - init card in spi mode if CS low
uint8_t const CMD0 = 0x00; CMD8 = 0x08, // SEND_IF_COND - verify SD Memory Card interface operating condition
/** SEND_IF_COND - verify SD Memory Card interface operating condition.*/ CMD9 = 0x09, // SEND_CSD - read the Card Specific Data (CSD register)
uint8_t const CMD8 = 0x08; CMD10 = 0x0A, // SEND_CID - read the card identification information (CID register)
/** SEND_CSD - read the Card Specific Data (CSD register) */ CMD12 = 0x0C, // STOP_TRANSMISSION - end multiple block read sequence
uint8_t const CMD9 = 0x09; CMD13 = 0x0D, // SEND_STATUS - read the card status register
/** SEND_CID - read the card identification information (CID register) */ CMD17 = 0x11, // READ_SINGLE_BLOCK - read a single data block from the card
uint8_t const CMD10 = 0x0A; CMD18 = 0x12, // READ_MULTIPLE_BLOCK - read a multiple data blocks from the card
/** STOP_TRANSMISSION - end multiple block read sequence */ CMD24 = 0x18, // WRITE_BLOCK - write a single data block to the card
uint8_t const CMD12 = 0x0C; CMD25 = 0x19, // WRITE_MULTIPLE_BLOCK - write blocks of data until a STOP_TRANSMISSION
/** SEND_STATUS - read the card status register */ CMD32 = 0x20, // ERASE_WR_BLK_START - sets the address of the first block to be erased
uint8_t const CMD13 = 0x0D; CMD33 = 0x21, // ERASE_WR_BLK_END - sets the address of the last block of the continuous range to be erased*/
/** READ_SINGLE_BLOCK - read a single data block from the card */ CMD38 = 0x26, // ERASE - erase all previously selected blocks */
uint8_t const CMD17 = 0x11; CMD55 = 0x37, // APP_CMD - escape for application specific command */
/** READ_MULTIPLE_BLOCK - read a multiple data blocks from the card */ CMD58 = 0x3A, // READ_OCR - read the OCR register of a card */
uint8_t const CMD18 = 0x12; ACMD23 = 0x17, // SET_WR_BLK_ERASE_COUNT - Set the number of write blocks to be pre-erased before writing */
/** WRITE_BLOCK - write a single data block to the card */ ACMD41 = 0x29; // SD_SEND_OP_COMD - Sends host capacity support information and activates the card's initialization process */
uint8_t const CMD24 = 0x18;
/** WRITE_MULTIPLE_BLOCK - write blocks of data until a STOP_TRANSMISSION */
uint8_t const CMD25 = 0x19;
/** ERASE_WR_BLK_START - sets the address of the first block to be erased */
uint8_t const CMD32 = 0x20;
/** ERASE_WR_BLK_END - sets the address of the last block of the continuous
range to be erased*/
uint8_t const CMD33 = 0x21;
/** ERASE - erase all previously selected blocks */
uint8_t const CMD38 = 0x26;
/** APP_CMD - escape for application specific command */
uint8_t const CMD55 = 0x37;
/** READ_OCR - read the OCR register of a card */
uint8_t const CMD58 = 0x3A;
/** SET_WR_BLK_ERASE_COUNT - Set the number of write blocks to be
pre-erased before writing */
uint8_t const ACMD23 = 0x17;
/** SD_SEND_OP_COMD - Sends host capacity support information and
activates the card's initialization process */
uint8_t const ACMD41 = 0x29;
//------------------------------------------------------------------------------
/** status for card in the ready state */ /** status for card in the ready state */
uint8_t const R1_READY_STATE = 0x00; uint8_t const R1_READY_STATE = 0x00;
/** status for card in the idle state */ /** status for card in the idle state */
@ -97,7 +77,7 @@ uint8_t const WRITE_MULTIPLE_TOKEN = 0xFC;
uint8_t const DATA_RES_MASK = 0x1F; uint8_t const DATA_RES_MASK = 0x1F;
/** write data accepted token */ /** write data accepted token */
uint8_t const DATA_RES_ACCEPTED = 0x05; uint8_t const DATA_RES_ACCEPTED = 0x05;
//------------------------------------------------------------------------------
/** Card IDentification (CID) register */ /** Card IDentification (CID) register */
typedef struct CID { typedef struct CID {
// byte 0 // byte 0
@ -133,7 +113,7 @@ typedef struct CID {
/** CRC7 checksum */ /** CRC7 checksum */
unsigned char crc : 7; unsigned char crc : 7;
} cid_t; } cid_t;
//------------------------------------------------------------------------------
/** CSD for version 1.00 cards */ /** CSD for version 1.00 cards */
typedef struct CSDV1 { typedef struct CSDV1 {
// byte 0 // byte 0
@ -195,7 +175,7 @@ typedef struct CSDV1 {
unsigned char always1 : 1; unsigned char always1 : 1;
unsigned char crc : 7; unsigned char crc : 7;
} csd1_t; } csd1_t;
//------------------------------------------------------------------------------
/** CSD for version 2.00 cards */ /** CSD for version 2.00 cards */
typedef struct CSDV2 { typedef struct CSDV2 {
// byte 0 // byte 0
@ -277,11 +257,11 @@ typedef struct CSDV2 {
/** checksum */ /** checksum */
unsigned char crc : 7; unsigned char crc : 7;
} csd2_t; } csd2_t;
//------------------------------------------------------------------------------
/** union of old and new style CSD register */ /** union of old and new style CSD register */
union csd_t { union csd_t {
csd1_t v1; csd1_t v1;
csd2_t v2; csd2_t v2;
}; };
#endif // SDINFO_H #endif // _SDINFO_H_

@ -35,7 +35,6 @@
#include "../Marlin.h" #include "../Marlin.h"
//------------------------------------------------------------------------------
#if !USE_MULTIPLE_CARDS #if !USE_MULTIPLE_CARDS
// raw block cache // raw block cache
uint32_t SdVolume::cacheBlockNumber_; // current block number uint32_t SdVolume::cacheBlockNumber_; // current block number
@ -44,7 +43,7 @@
bool SdVolume::cacheDirty_; // cacheFlush() will write block if true bool SdVolume::cacheDirty_; // cacheFlush() will write block if true
uint32_t SdVolume::cacheMirrorBlock_; // mirror block for second FAT uint32_t SdVolume::cacheMirrorBlock_; // mirror block for second FAT
#endif // USE_MULTIPLE_CARDS #endif // USE_MULTIPLE_CARDS
//------------------------------------------------------------------------------
// find a contiguous group of clusters // find a contiguous group of clusters
bool SdVolume::allocContiguous(uint32_t count, uint32_t* curCluster) { bool SdVolume::allocContiguous(uint32_t count, uint32_t* curCluster) {
// start of group // start of group
@ -78,14 +77,14 @@ bool SdVolume::allocContiguous(uint32_t count, uint32_t* curCluster) {
// search the FAT for free clusters // search the FAT for free clusters
for (uint32_t n = 0;; n++, endCluster++) { for (uint32_t n = 0;; n++, endCluster++) {
// can't find space checked all clusters // can't find space checked all clusters
if (n >= clusterCount_) goto FAIL; if (n >= clusterCount_) return false;
// past end - start from beginning of FAT // past end - start from beginning of FAT
if (endCluster > fatEnd) { if (endCluster > fatEnd) {
bgnCluster = endCluster = 2; bgnCluster = endCluster = 2;
} }
uint32_t f; uint32_t f;
if (!fatGet(endCluster, &f)) goto FAIL; if (!fatGet(endCluster, &f)) return false;
if (f != 0) { if (f != 0) {
// cluster in use try next cluster as bgnCluster // cluster in use try next cluster as bgnCluster
@ -97,16 +96,16 @@ bool SdVolume::allocContiguous(uint32_t count, uint32_t* curCluster) {
} }
} }
// mark end of chain // mark end of chain
if (!fatPutEOC(endCluster)) goto FAIL; if (!fatPutEOC(endCluster)) return false;
// link clusters // link clusters
while (endCluster > bgnCluster) { while (endCluster > bgnCluster) {
if (!fatPut(endCluster - 1, endCluster)) goto FAIL; if (!fatPut(endCluster - 1, endCluster)) return false;
endCluster--; endCluster--;
} }
if (*curCluster != 0) { if (*curCluster != 0) {
// connect chains // connect chains
if (!fatPut(*curCluster, bgnCluster)) goto FAIL; if (!fatPut(*curCluster, bgnCluster)) return false;
} }
// return first cluster number to caller // return first cluster number to caller
*curCluster = bgnCluster; *curCluster = bgnCluster;
@ -115,111 +114,94 @@ bool SdVolume::allocContiguous(uint32_t count, uint32_t* curCluster) {
if (setStart) allocSearchStart_ = bgnCluster + 1; if (setStart) allocSearchStart_ = bgnCluster + 1;
return true; return true;
FAIL:
return false;
} }
//------------------------------------------------------------------------------
bool SdVolume::cacheFlush() { bool SdVolume::cacheFlush() {
if (cacheDirty_) { if (cacheDirty_) {
if (!sdCard_->writeBlock(cacheBlockNumber_, cacheBuffer_.data)) { if (!sdCard_->writeBlock(cacheBlockNumber_, cacheBuffer_.data))
goto FAIL; return false;
}
// mirror FAT tables // mirror FAT tables
if (cacheMirrorBlock_) { if (cacheMirrorBlock_) {
if (!sdCard_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data)) { if (!sdCard_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data))
goto FAIL; return false;
}
cacheMirrorBlock_ = 0; cacheMirrorBlock_ = 0;
} }
cacheDirty_ = 0; cacheDirty_ = 0;
} }
return true; return true;
FAIL:
return false;
} }
//------------------------------------------------------------------------------
bool SdVolume::cacheRawBlock(uint32_t blockNumber, bool dirty) { bool SdVolume::cacheRawBlock(uint32_t blockNumber, bool dirty) {
if (cacheBlockNumber_ != blockNumber) { if (cacheBlockNumber_ != blockNumber) {
if (!cacheFlush()) goto FAIL; if (!cacheFlush()) return false;
if (!sdCard_->readBlock(blockNumber, cacheBuffer_.data)) goto FAIL; if (!sdCard_->readBlock(blockNumber, cacheBuffer_.data)) return false;
cacheBlockNumber_ = blockNumber; cacheBlockNumber_ = blockNumber;
} }
if (dirty) cacheDirty_ = true; if (dirty) cacheDirty_ = true;
return true; return true;
FAIL:
return false;
} }
//------------------------------------------------------------------------------
// return the size in bytes of a cluster chain // return the size in bytes of a cluster chain
bool SdVolume::chainSize(uint32_t cluster, uint32_t* size) { bool SdVolume::chainSize(uint32_t cluster, uint32_t* size) {
uint32_t s = 0; uint32_t s = 0;
do { do {
if (!fatGet(cluster, &cluster)) goto FAIL; if (!fatGet(cluster, &cluster)) return false;
s += 512UL << clusterSizeShift_; s += 512UL << clusterSizeShift_;
} while (!isEOC(cluster)); } while (!isEOC(cluster));
*size = s; *size = s;
return true; return true;
FAIL:
return false;
} }
//------------------------------------------------------------------------------
// Fetch a FAT entry // Fetch a FAT entry
bool SdVolume::fatGet(uint32_t cluster, uint32_t* value) { bool SdVolume::fatGet(uint32_t cluster, uint32_t* value) {
uint32_t lba; uint32_t lba;
if (cluster > (clusterCount_ + 1)) goto FAIL; if (cluster > (clusterCount_ + 1)) return false;
if (FAT12_SUPPORT && fatType_ == 12) { if (FAT12_SUPPORT && fatType_ == 12) {
uint16_t index = cluster; uint16_t index = cluster;
index += index >> 1; index += index >> 1;
lba = fatStartBlock_ + (index >> 9); lba = fatStartBlock_ + (index >> 9);
if (!cacheRawBlock(lba, CACHE_FOR_READ)) goto FAIL; if (!cacheRawBlock(lba, CACHE_FOR_READ)) return false;
index &= 0x1FF; index &= 0x1FF;
uint16_t tmp = cacheBuffer_.data[index]; uint16_t tmp = cacheBuffer_.data[index];
index++; index++;
if (index == 512) { if (index == 512) {
if (!cacheRawBlock(lba + 1, CACHE_FOR_READ)) goto FAIL; if (!cacheRawBlock(lba + 1, CACHE_FOR_READ)) return false;
index = 0; index = 0;
} }
tmp |= cacheBuffer_.data[index] << 8; tmp |= cacheBuffer_.data[index] << 8;
*value = cluster & 1 ? tmp >> 4 : tmp & 0xFFF; *value = cluster & 1 ? tmp >> 4 : tmp & 0xFFF;
return true; return true;
} }
if (fatType_ == 16) {
if (fatType_ == 16)
lba = fatStartBlock_ + (cluster >> 8); lba = fatStartBlock_ + (cluster >> 8);
} else if (fatType_ == 32)
else if (fatType_ == 32) {
lba = fatStartBlock_ + (cluster >> 7); lba = fatStartBlock_ + (cluster >> 7);
} else
else { return false;
goto FAIL;
} if (lba != cacheBlockNumber_ && !cacheRawBlock(lba, CACHE_FOR_READ))
if (lba != cacheBlockNumber_) { return false;
if (!cacheRawBlock(lba, CACHE_FOR_READ)) goto FAIL;
} *value = (fatType_ == 16) ? cacheBuffer_.fat16[cluster & 0xFF] : (cacheBuffer_.fat32[cluster & 0x7F] & FAT32MASK);
if (fatType_ == 16) {
*value = cacheBuffer_.fat16[cluster & 0xFF];
}
else {
*value = cacheBuffer_.fat32[cluster & 0x7F] & FAT32MASK;
}
return true; return true;
FAIL:
return false;
} }
//------------------------------------------------------------------------------
// Store a FAT entry // Store a FAT entry
bool SdVolume::fatPut(uint32_t cluster, uint32_t value) { bool SdVolume::fatPut(uint32_t cluster, uint32_t value) {
uint32_t lba; uint32_t lba;
// error if reserved cluster // error if reserved cluster
if (cluster < 2) goto FAIL; if (cluster < 2) return false;
// error if not in FAT // error if not in FAT
if (cluster > (clusterCount_ + 1)) goto FAIL; if (cluster > (clusterCount_ + 1)) return false;
if (FAT12_SUPPORT && fatType_ == 12) { if (FAT12_SUPPORT && fatType_ == 12) {
uint16_t index = cluster; uint16_t index = cluster;
index += index >> 1; index += index >> 1;
lba = fatStartBlock_ + (index >> 9); lba = fatStartBlock_ + (index >> 9);
if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) goto FAIL; if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) return false;
// mirror second FAT // mirror second FAT
if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_;
index &= 0x1FF; index &= 0x1FF;
@ -232,7 +214,7 @@ bool SdVolume::fatPut(uint32_t cluster, uint32_t value) {
if (index == 512) { if (index == 512) {
lba++; lba++;
index = 0; index = 0;
if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) goto FAIL; if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) return false;
// mirror second FAT // mirror second FAT
if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_;
} }
@ -243,51 +225,45 @@ bool SdVolume::fatPut(uint32_t cluster, uint32_t value) {
cacheBuffer_.data[index] = tmp; cacheBuffer_.data[index] = tmp;
return true; return true;
} }
if (fatType_ == 16) {
if (fatType_ == 16)
lba = fatStartBlock_ + (cluster >> 8); lba = fatStartBlock_ + (cluster >> 8);
} else if (fatType_ == 32)
else if (fatType_ == 32) {
lba = fatStartBlock_ + (cluster >> 7); lba = fatStartBlock_ + (cluster >> 7);
} else
else { return false;
goto FAIL;
} if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) return false;
if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) goto FAIL;
// store entry // store entry
if (fatType_ == 16) { if (fatType_ == 16)
cacheBuffer_.fat16[cluster & 0xFF] = value; cacheBuffer_.fat16[cluster & 0xFF] = value;
} else
else {
cacheBuffer_.fat32[cluster & 0x7F] = value; cacheBuffer_.fat32[cluster & 0x7F] = value;
}
// mirror second FAT // mirror second FAT
if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_;
return true; return true;
FAIL:
return false;
} }
//------------------------------------------------------------------------------
// free a cluster chain // free a cluster chain
bool SdVolume::freeChain(uint32_t cluster) { bool SdVolume::freeChain(uint32_t cluster) {
uint32_t next;
// clear free cluster location // clear free cluster location
allocSearchStart_ = 2; allocSearchStart_ = 2;
do { do {
if (!fatGet(cluster, &next)) goto FAIL; uint32_t next;
if (!fatGet(cluster, &next)) return false;
// free cluster // free cluster
if (!fatPut(cluster, 0)) goto FAIL; if (!fatPut(cluster, 0)) return false;
cluster = next; cluster = next;
} while (!isEOC(cluster)); } while (!isEOC(cluster));
return true; return true;
FAIL:
return false;
} }
//------------------------------------------------------------------------------
/** Volume free space in clusters. /** Volume free space in clusters.
* *
* \return Count of free clusters for success or -1 if an error occurs. * \return Count of free clusters for success or -1 if an error occurs.
@ -297,34 +273,28 @@ int32_t SdVolume::freeClusterCount() {
uint16_t n; uint16_t n;
uint32_t todo = clusterCount_ + 2; uint32_t todo = clusterCount_ + 2;
if (fatType_ == 16) { if (fatType_ == 16)
n = 256; n = 256;
} else if (fatType_ == 32)
else if (fatType_ == 32) {
n = 128; n = 128;
} else // put FAT12 here
else {
// put FAT12 here
return -1; return -1;
}
for (uint32_t lba = fatStartBlock_; todo; todo -= n, lba++) { for (uint32_t lba = fatStartBlock_; todo; todo -= n, lba++) {
if (!cacheRawBlock(lba, CACHE_FOR_READ)) return -1; if (!cacheRawBlock(lba, CACHE_FOR_READ)) return -1;
NOMORE(n, todo); NOMORE(n, todo);
if (fatType_ == 16) { if (fatType_ == 16) {
for (uint16_t i = 0; i < n; i++) { for (uint16_t i = 0; i < n; i++)
if (cacheBuffer_.fat16[i] == 0) free++; if (cacheBuffer_.fat16[i] == 0) free++;
}
} }
else { else {
for (uint16_t i = 0; i < n; i++) { for (uint16_t i = 0; i < n; i++)
if (cacheBuffer_.fat32[i] == 0) free++; if (cacheBuffer_.fat32[i] == 0) free++;
}
} }
} }
return free; return free;
} }
//------------------------------------------------------------------------------
/** Initialize a FAT volume. /** Initialize a FAT volume.
* *
* \param[in] dev The SD card where the volume is located. * \param[in] dev The SD card where the volume is located.
@ -334,14 +304,12 @@ int32_t SdVolume::freeClusterCount() {
* a MBR, Master Boot Record, or zero if the device is formatted as * a MBR, Master Boot Record, or zero if the device is formatted as
* a super floppy with the FAT boot sector in block zero. * a super floppy with the FAT boot sector in block zero.
* *
* \return The value one, true, is returned for success and * \return true for success, false for failure.
* the value zero, false, is returned for failure. Reasons for * Reasons for failure include not finding a valid partition, not finding a valid
* failure include not finding a valid partition, not finding a valid
* FAT file system in the specified partition or an I/O error. * FAT file system in the specified partition or an I/O error.
*/ */
bool SdVolume::init(Sd2Card* dev, uint8_t part) { bool SdVolume::init(Sd2Card* dev, uint8_t part) {
uint32_t totalBlocks; uint32_t totalBlocks, volumeStartBlock = 0;
uint32_t volumeStartBlock = 0;
fat32_boot_t* fbs; fat32_boot_t* fbs;
sdCard_ = dev; sdCard_ = dev;
@ -354,25 +322,21 @@ bool SdVolume::init(Sd2Card* dev, uint8_t part) {
// if part == 0 assume super floppy with FAT boot sector in block zero // if part == 0 assume super floppy with FAT boot sector in block zero
// if part > 0 assume mbr volume with partition table // if part > 0 assume mbr volume with partition table
if (part) { if (part) {
if (part > 4)goto FAIL; if (part > 4) return false;
if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) goto FAIL; if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) return false;
part_t* p = &cacheBuffer_.mbr.part[part - 1]; part_t* p = &cacheBuffer_.mbr.part[part - 1];
if ((p->boot & 0x7F) != 0 || if ((p->boot & 0x7F) != 0 || p->totalSectors < 100 || p->firstSector == 0)
p->totalSectors < 100 || return false; // not a valid partition
p->firstSector == 0) {
// not a valid partition
goto FAIL;
}
volumeStartBlock = p->firstSector; volumeStartBlock = p->firstSector;
} }
if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) goto FAIL; if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) return false;
fbs = &cacheBuffer_.fbs32; fbs = &cacheBuffer_.fbs32;
if (fbs->bytesPerSector != 512 || if (fbs->bytesPerSector != 512 ||
fbs->fatCount == 0 || fbs->fatCount == 0 ||
fbs->reservedSectorCount == 0 || fbs->reservedSectorCount == 0 ||
fbs->sectorsPerCluster == 0) { fbs->sectorsPerCluster == 0) {
// not valid FAT volume // not valid FAT volume
goto FAIL; return false;
} }
fatCount_ = fbs->fatCount; fatCount_ = fbs->fatCount;
blocksPerCluster_ = fbs->sectorsPerCluster; blocksPerCluster_ = fbs->sectorsPerCluster;
@ -380,7 +344,7 @@ bool SdVolume::init(Sd2Card* dev, uint8_t part) {
clusterSizeShift_ = 0; clusterSizeShift_ = 0;
while (blocksPerCluster_ != _BV(clusterSizeShift_)) { while (blocksPerCluster_ != _BV(clusterSizeShift_)) {
// error if not power of 2 // error if not power of 2
if (clusterSizeShift_++ > 7) goto FAIL; if (clusterSizeShift_++ > 7) return false;
} }
blocksPerFat_ = fbs->sectorsPerFat16 ? blocksPerFat_ = fbs->sectorsPerFat16 ?
fbs->sectorsPerFat16 : fbs->sectorsPerFat32; fbs->sectorsPerFat16 : fbs->sectorsPerFat32;
@ -409,18 +373,15 @@ bool SdVolume::init(Sd2Card* dev, uint8_t part) {
// FAT type is determined by cluster count // FAT type is determined by cluster count
if (clusterCount_ < 4085) { if (clusterCount_ < 4085) {
fatType_ = 12; fatType_ = 12;
if (!FAT12_SUPPORT) goto FAIL; if (!FAT12_SUPPORT) return false;
} }
else if (clusterCount_ < 65525) { else if (clusterCount_ < 65525)
fatType_ = 16; fatType_ = 16;
}
else { else {
rootDirStart_ = fbs->fat32RootCluster; rootDirStart_ = fbs->fat32RootCluster;
fatType_ = 32; fatType_ = 32;
} }
return true; return true;
FAIL:
return false;
} }
#endif // SDSUPPORT #endif // SDSUPPORT

@ -20,19 +20,20 @@
* *
*/ */
/**
* \file
* \brief SdVolume class
*/
/** /**
* Arduino SdFat Library * Arduino SdFat Library
* Copyright (C) 2009 by William Greiman * Copyright (C) 2009 by William Greiman
* *
* This file is part of the Arduino Sd2Card Library * This file is part of the Arduino Sd2Card Library
*/ */
#ifndef SDVOLUME_H #ifndef _SDVOLUME_H_
#define SDVOLUME_H #define _SDVOLUME_H_
/**
* \file
* \brief SdVolume class
*/
#include "SdFatConfig.h" #include "SdFatConfig.h"
#include "Sd2Card.h" #include "Sd2Card.h"
#include "SdFatStructs.h" #include "SdFatStructs.h"
@ -45,33 +46,26 @@
* \brief Cache for an SD data block * \brief Cache for an SD data block
*/ */
union cache_t { union cache_t {
/** Used to access cached file data blocks. */ uint8_t data[512]; // Used to access cached file data blocks.
uint8_t data[512]; uint16_t fat16[256]; // Used to access cached FAT16 entries.
/** Used to access cached FAT16 entries. */ uint32_t fat32[128]; // Used to access cached FAT32 entries.
uint16_t fat16[256]; dir_t dir[16]; // Used to access cached directory entries.
/** Used to access cached FAT32 entries. */ mbr_t mbr; // Used to access a cached Master Boot Record.
uint32_t fat32[128]; fat_boot_t fbs; // Used to access to a cached FAT boot sector.
/** Used to access cached directory entries. */ fat32_boot_t fbs32; // Used to access to a cached FAT32 boot sector.
dir_t dir[16]; fat32_fsinfo_t fsinfo; // Used to access to a cached FAT32 FSINFO sector.
/** Used to access a cached Master Boot Record. */
mbr_t mbr;
/** Used to access to a cached FAT boot sector. */
fat_boot_t fbs;
/** Used to access to a cached FAT32 boot sector. */
fat32_boot_t fbs32;
/** Used to access to a cached FAT32 FSINFO sector. */
fat32_fsinfo_t fsinfo;
}; };
//------------------------------------------------------------------------------
/** /**
* \class SdVolume * \class SdVolume
* \brief Access FAT16 and FAT32 volumes on SD and SDHC cards. * \brief Access FAT16 and FAT32 volumes on SD and SDHC cards.
*/ */
class SdVolume { class SdVolume {
public: public:
/** Create an instance of SdVolume */ // Create an instance of SdVolume
SdVolume() : fatType_(0) {} SdVolume() : fatType_(0) {}
/** Clear the cache and returns a pointer to the cache. Used by the WaveRP /**
* Clear the cache and returns a pointer to the cache. Used by the WaveRP
* recorder to do raw write to the SD card. Not for normal apps. * recorder to do raw write to the SD card. Not for normal apps.
* \return A pointer to the cache buffer or zero if an error occurs. * \return A pointer to the cache buffer or zero if an error occurs.
*/ */
@ -80,54 +74,53 @@ class SdVolume {
cacheBlockNumber_ = 0xFFFFFFFF; cacheBlockNumber_ = 0xFFFFFFFF;
return &cacheBuffer_; return &cacheBuffer_;
} }
/** Initialize a FAT volume. Try partition one first then try super
/**
* Initialize a FAT volume. Try partition one first then try super
* floppy format. * floppy format.
* *
* \param[in] dev The Sd2Card where the volume is located. * \param[in] dev The Sd2Card where the volume is located.
* *
* \return The value one, true, is returned for success and * \return true for success, false for failure.
* the value zero, false, is returned for failure. Reasons for * Reasons for failure include not finding a valid partition, not finding
* failure include not finding a valid partition, not finding a valid * a valid FAT file system or an I/O error.
* FAT file system or an I/O error.
*/ */
bool init(Sd2Card* dev) { return init(dev, 1) ? true : init(dev, 0);} bool init(Sd2Card* dev) { return init(dev, 1) ? true : init(dev, 0); }
bool init(Sd2Card* dev, uint8_t part); bool init(Sd2Card* dev, uint8_t part);
// inline functions that return volume info // inline functions that return volume info
/** \return The volume's cluster size in blocks. */ uint8_t blocksPerCluster() const { return blocksPerCluster_; } //> \return The volume's cluster size in blocks.
uint8_t blocksPerCluster() const {return blocksPerCluster_;} uint32_t blocksPerFat() const { return blocksPerFat_; } //> \return The number of blocks in one FAT.
/** \return The number of blocks in one FAT. */ uint32_t clusterCount() const { return clusterCount_; } //> \return The total number of clusters in the volume.
uint32_t blocksPerFat() const {return blocksPerFat_;} uint8_t clusterSizeShift() const { return clusterSizeShift_; } //> \return The shift count required to multiply by blocksPerCluster.
/** \return The total number of clusters in the volume. */ uint32_t dataStartBlock() const { return dataStartBlock_; } //> \return The logical block number for the start of file data.
uint32_t clusterCount() const {return clusterCount_;} uint8_t fatCount() const { return fatCount_; } //> \return The number of FAT structures on the volume.
/** \return The shift count required to multiply by blocksPerCluster. */ uint32_t fatStartBlock() const { return fatStartBlock_; } //> \return The logical block number for the start of the first FAT.
uint8_t clusterSizeShift() const {return clusterSizeShift_;} uint8_t fatType() const { return fatType_; } //> \return The FAT type of the volume. Values are 12, 16 or 32.
/** \return The logical block number for the start of file data. */
uint32_t dataStartBlock() const {return dataStartBlock_;}
/** \return The number of FAT structures on the volume. */
uint8_t fatCount() const {return fatCount_;}
/** \return The logical block number for the start of the first FAT. */
uint32_t fatStartBlock() const {return fatStartBlock_;}
/** \return The FAT type of the volume. Values are 12, 16 or 32. */
uint8_t fatType() const {return fatType_;}
int32_t freeClusterCount(); int32_t freeClusterCount();
/** \return The number of entries in the root directory for FAT16 volumes. */ uint32_t rootDirEntryCount() const { return rootDirEntryCount_; } /** \return The number of entries in the root directory for FAT16 volumes. */
uint32_t rootDirEntryCount() const {return rootDirEntryCount_;}
/** \return The logical block number for the start of the root directory /**
on FAT16 volumes or the first cluster number on FAT32 volumes. */ * \return The logical block number for the start of the root directory
uint32_t rootDirStart() const {return rootDirStart_;} * on FAT16 volumes or the first cluster number on FAT32 volumes.
/** Sd2Card object for this volume */
uint32_t rootDirStart() const { return rootDirStart_; }
/**
* Sd2Card object for this volume
* \return pointer to Sd2Card object. * \return pointer to Sd2Card object.
*/ */
Sd2Card* sdCard() {return sdCard_;} Sd2Card* sdCard() { return sdCard_; }
/** Debug access to FAT table
/**
* Debug access to FAT table
* *
* \param[in] n cluster number. * \param[in] n cluster number.
* \param[out] v value of entry * \param[out] v value of entry
* \return true for success or false for failure * \return true for success or false for failure
*/ */
bool dbgFat(uint32_t n, uint32_t* v) {return fatGet(n, v);} bool dbgFat(uint32_t n, uint32_t* v) { return fatGet(n, v); }
//------------------------------------------------------------------------------
private: private:
// Allow SdBaseFile access to SdVolume private data. // Allow SdBaseFile access to SdVolume private data.
friend class SdBaseFile; friend class SdBaseFile;
@ -143,13 +136,14 @@ class SdVolume {
Sd2Card* sdCard_; // Sd2Card object for cache Sd2Card* sdCard_; // Sd2Card object for cache
bool cacheDirty_; // cacheFlush() will write block if true bool cacheDirty_; // cacheFlush() will write block if true
uint32_t cacheMirrorBlock_; // block number for mirror FAT uint32_t cacheMirrorBlock_; // block number for mirror FAT
#else // USE_MULTIPLE_CARDS #else
static cache_t cacheBuffer_; // 512 byte cache for device blocks static cache_t cacheBuffer_; // 512 byte cache for device blocks
static uint32_t cacheBlockNumber_; // Logical number of block in the cache static uint32_t cacheBlockNumber_; // Logical number of block in the cache
static Sd2Card* sdCard_; // Sd2Card object for cache static Sd2Card* sdCard_; // Sd2Card object for cache
static bool cacheDirty_; // cacheFlush() will write block if true static bool cacheDirty_; // cacheFlush() will write block if true
static uint32_t cacheMirrorBlock_; // block number for mirror FAT static uint32_t cacheMirrorBlock_; // block number for mirror FAT
#endif // USE_MULTIPLE_CARDS #endif
uint32_t allocSearchStart_; // start cluster for alloc search uint32_t allocSearchStart_; // start cluster for alloc search
uint8_t blocksPerCluster_; // cluster size in blocks uint8_t blocksPerCluster_; // cluster size in blocks
uint32_t blocksPerFat_; // FAT size in blocks uint32_t blocksPerFat_; // FAT size in blocks
@ -161,68 +155,59 @@ class SdVolume {
uint8_t fatType_; // volume type (12, 16, OR 32) uint8_t fatType_; // volume type (12, 16, OR 32)
uint16_t rootDirEntryCount_; // number of entries in FAT16 root dir uint16_t rootDirEntryCount_; // number of entries in FAT16 root dir
uint32_t rootDirStart_; // root start block for FAT16, cluster for FAT32 uint32_t rootDirStart_; // root start block for FAT16, cluster for FAT32
//----------------------------------------------------------------------------
bool allocContiguous(uint32_t count, uint32_t* curCluster); bool allocContiguous(uint32_t count, uint32_t* curCluster);
uint8_t blockOfCluster(uint32_t position) const { uint8_t blockOfCluster(uint32_t position) const { return (position >> 9) & (blocksPerCluster_ - 1); }
return (position >> 9) & (blocksPerCluster_ - 1); uint32_t clusterStartBlock(uint32_t cluster) const { return dataStartBlock_ + ((cluster - 2) << clusterSizeShift_); }
} uint32_t blockNumber(uint32_t cluster, uint32_t position) const { return clusterStartBlock(cluster) + blockOfCluster(position); }
uint32_t clusterStartBlock(uint32_t cluster) const {
return dataStartBlock_ + ((cluster - 2) << clusterSizeShift_); cache_t* cache() { return &cacheBuffer_; }
} uint32_t cacheBlockNumber() const { return cacheBlockNumber_; }
uint32_t blockNumber(uint32_t cluster, uint32_t position) const {
return clusterStartBlock(cluster) + blockOfCluster(position);
}
cache_t* cache() {return &cacheBuffer_;}
uint32_t cacheBlockNumber() {return cacheBlockNumber_;}
#if USE_MULTIPLE_CARDS #if USE_MULTIPLE_CARDS
bool cacheFlush(); bool cacheFlush();
bool cacheRawBlock(uint32_t blockNumber, bool dirty); bool cacheRawBlock(uint32_t blockNumber, bool dirty);
#else // USE_MULTIPLE_CARDS #else
static bool cacheFlush(); static bool cacheFlush();
static bool cacheRawBlock(uint32_t blockNumber, bool dirty); static bool cacheRawBlock(uint32_t blockNumber, bool dirty);
#endif // USE_MULTIPLE_CARDS #endif
// used by SdBaseFile write to assign cache to SD location // used by SdBaseFile write to assign cache to SD location
void cacheSetBlockNumber(uint32_t blockNumber, bool dirty) { void cacheSetBlockNumber(uint32_t blockNumber, bool dirty) {
cacheDirty_ = dirty; cacheDirty_ = dirty;
cacheBlockNumber_ = blockNumber; cacheBlockNumber_ = blockNumber;
} }
void cacheSetDirty() {cacheDirty_ |= CACHE_FOR_WRITE;} void cacheSetDirty() { cacheDirty_ |= CACHE_FOR_WRITE; }
bool chainSize(uint32_t beginCluster, uint32_t* size); bool chainSize(uint32_t beginCluster, uint32_t* size);
bool fatGet(uint32_t cluster, uint32_t* value); bool fatGet(uint32_t cluster, uint32_t* value);
bool fatPut(uint32_t cluster, uint32_t value); bool fatPut(uint32_t cluster, uint32_t value);
bool fatPutEOC(uint32_t cluster) { bool fatPutEOC(uint32_t cluster) { return fatPut(cluster, 0x0FFFFFFF); }
return fatPut(cluster, 0x0FFFFFFF);
}
bool freeChain(uint32_t cluster); bool freeChain(uint32_t cluster);
bool isEOC(uint32_t cluster) const { bool isEOC(uint32_t cluster) const {
if (FAT12_SUPPORT && fatType_ == 12) return cluster >= FAT12EOC_MIN; if (FAT12_SUPPORT && fatType_ == 12) return cluster >= FAT12EOC_MIN;
if (fatType_ == 16) return cluster >= FAT16EOC_MIN; if (fatType_ == 16) return cluster >= FAT16EOC_MIN;
return cluster >= FAT32EOC_MIN; return cluster >= FAT32EOC_MIN;
} }
bool readBlock(uint32_t block, uint8_t* dst) { bool readBlock(uint32_t block, uint8_t* dst) { return sdCard_->readBlock(block, dst); }
return sdCard_->readBlock(block, dst); bool writeBlock(uint32_t block, const uint8_t* dst) { return sdCard_->writeBlock(block, dst); }
}
bool writeBlock(uint32_t block, const uint8_t* dst) { // Deprecated functions
return sdCard_->writeBlock(block, dst); #if ALLOW_DEPRECATED_FUNCTIONS
}
//------------------------------------------------------------------------------
// Deprecated functions - suppress cpplint warnings with NOLINT comment
#if ALLOW_DEPRECATED_FUNCTIONS && !defined(DOXYGEN)
public: public:
/** \deprecated Use: bool SdVolume::init(Sd2Card* dev); /**
* \deprecated Use: bool SdVolume::init(Sd2Card* dev);
* \param[in] dev The SD card where the volume is located. * \param[in] dev The SD card where the volume is located.
* \return true for success or false for failure. * \return true for success or false for failure.
*/ */
bool init(Sd2Card& dev) {return init(&dev);} // NOLINT bool init(Sd2Card& dev) { return init(&dev); }
/** \deprecated Use: bool SdVolume::init(Sd2Card* dev, uint8_t vol); /**
* \deprecated Use: bool SdVolume::init(Sd2Card* dev, uint8_t vol);
* \param[in] dev The SD card where the volume is located. * \param[in] dev The SD card where the volume is located.
* \param[in] part The partition to be used. * \param[in] part The partition to be used.
* \return true for success or false for failure. * \return true for success or false for failure.
*/ */
bool init(Sd2Card& dev, uint8_t part) { // NOLINT bool init(Sd2Card& dev, uint8_t part) { return init(&dev, part); }
return init(&dev, part);
}
#endif // ALLOW_DEPRECATED_FUNCTIONS #endif // ALLOW_DEPRECATED_FUNCTIONS
}; };
#endif // SDVOLUME_H #endif // _SDVOLUME_H_

@ -49,8 +49,9 @@ CardReader::CardReader() {
sdprinting = cardOK = saving = logging = false; sdprinting = cardOK = saving = logging = false;
filesize = 0; filesize = 0;
sdpos = 0; sdpos = 0;
workDirDepth = 0;
file_subcall_ctr = 0; file_subcall_ctr = 0;
workDirDepth = 0;
ZERO(workDirParents); ZERO(workDirParents);
autostart_stilltocheck = true; //the SD start is delayed, because otherwise the serial cannot answer fast enough to make contact with the host software. autostart_stilltocheck = true; //the SD start is delayed, because otherwise the serial cannot answer fast enough to make contact with the host software.
@ -263,16 +264,7 @@ void CardReader::initsd() {
SERIAL_ECHO_START(); SERIAL_ECHO_START();
SERIAL_ECHOLNPGM(MSG_SD_CARD_OK); SERIAL_ECHOLNPGM(MSG_SD_CARD_OK);
} }
workDir = root; setroot();
curDir = &root;
#if ENABLED(SDCARD_SORT_ALPHA)
presort();
#endif
/**
if (!workDir.openRoot(&volume)) {
SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
}
*/
} }
void CardReader::setroot() { void CardReader::setroot() {
@ -356,9 +348,8 @@ void CardReader::openFile(char* name, bool read, bool push_current/*=false*/) {
filespos[file_subcall_ctr] = sdpos; filespos[file_subcall_ctr] = sdpos;
file_subcall_ctr++; file_subcall_ctr++;
} }
else { else
doing = 1; doing = 1;
}
} }
else { // Opening fresh file else { // Opening fresh file
doing = 2; doing = 2;
@ -368,7 +359,7 @@ void CardReader::openFile(char* name, bool read, bool push_current/*=false*/) {
if (doing) { if (doing) {
SERIAL_ECHO_START(); SERIAL_ECHO_START();
SERIAL_ECHOPGM("Now "); SERIAL_ECHOPGM("Now ");
SERIAL_ECHO(doing == 1 ? "doing" : "fresh"); serialprintPGM(doing == 1 ? PSTR("doing") : PSTR("fresh"));
SERIAL_ECHOLNPAIR(" file: ", name); SERIAL_ECHOLNPAIR(" file: ", name);
} }
@ -388,8 +379,7 @@ void CardReader::openFile(char* name, bool read, bool push_current/*=false*/) {
if (dirname_end != NULL && dirname_end > dirname_start) { if (dirname_end != NULL && dirname_end > dirname_start) {
char subdirname[FILENAME_LENGTH]; char subdirname[FILENAME_LENGTH];
strncpy(subdirname, dirname_start, dirname_end - dirname_start); strncpy(subdirname, dirname_start, dirname_end - dirname_start);
subdirname[dirname_end - dirname_start] = 0; subdirname[dirname_end - dirname_start] = '\0';
SERIAL_ECHOLN(subdirname);
if (!myDir.open(curDir, subdirname, O_READ)) { if (!myDir.open(curDir, subdirname, O_READ)) {
SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
SERIAL_PROTOCOL(subdirname); SERIAL_PROTOCOL(subdirname);
@ -411,17 +401,15 @@ void CardReader::openFile(char* name, bool read, bool push_current/*=false*/) {
} }
} }
} }
else { //relative path else
curDir = &workDir; curDir = &workDir; // Relative paths start in current directory
}
if (read) { if (read) {
if (file.open(curDir, fname, O_READ)) { if (file.open(curDir, fname, O_READ)) {
filesize = file.fileSize(); filesize = file.fileSize();
sdpos = 0;
SERIAL_PROTOCOLPAIR(MSG_SD_FILE_OPENED, fname); SERIAL_PROTOCOLPAIR(MSG_SD_FILE_OPENED, fname);
SERIAL_PROTOCOLLNPAIR(MSG_SD_SIZE, filesize); SERIAL_PROTOCOLLNPAIR(MSG_SD_SIZE, filesize);
sdpos = 0;
SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED); SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED);
getfilename(0, fname); getfilename(0, fname);
lcd_setstatus(longFilename[0] ? longFilename : fname); lcd_setstatus(longFilename[0] ? longFilename : fname);
@ -446,14 +434,14 @@ void CardReader::openFile(char* name, bool read, bool push_current/*=false*/) {
} }
} }
void CardReader::removeFile(char* name) { void CardReader::removeFile(const char * const name) {
if (!cardOK) return; if (!cardOK) return;
stopSDPrint(); stopSDPrint();
SdFile myDir; SdFile myDir;
curDir = &root; curDir = &root;
char *fname = name; const char *fname = name;
char *dirname_start, *dirname_end; char *dirname_start, *dirname_end;
if (name[0] == '/') { if (name[0] == '/') {
@ -468,29 +456,23 @@ void CardReader::removeFile(char* name) {
subdirname[dirname_end - dirname_start] = 0; subdirname[dirname_end - dirname_start] = 0;
SERIAL_ECHOLN(subdirname); SERIAL_ECHOLN(subdirname);
if (!myDir.open(curDir, subdirname, O_READ)) { if (!myDir.open(curDir, subdirname, O_READ)) {
SERIAL_PROTOCOLPAIR("open failed, File: ", subdirname); SERIAL_PROTOCOLPAIR(MSG_SD_OPEN_FILE_FAIL, subdirname);
SERIAL_PROTOCOLCHAR('.'); SERIAL_PROTOCOLCHAR('.');
SERIAL_EOL(); SERIAL_EOL();
return; return;
} }
else {
//SERIAL_ECHOLNPGM("dive ok");
}
curDir = &myDir; curDir = &myDir;
dirname_start = dirname_end + 1; dirname_start = dirname_end + 1;
} }
else { // the remainder after all /fsa/fdsa/ is the filename else {
fname = dirname_start; fname = dirname_start;
//SERIAL_ECHOLNPGM("remainder");
//SERIAL_ECHOLN(fname);
break; break;
} }
} }
} }
else { // relative path else // Relative paths are rooted in the current directory
curDir = &workDir; curDir = &workDir;
}
if (file.remove(curDir, fname)) { if (file.remove(curDir, fname)) {
SERIAL_PROTOCOLPGM("File deleted:"); SERIAL_PROTOCOLPGM("File deleted:");
@ -514,14 +496,13 @@ void CardReader::getStatus() {
SERIAL_PROTOCOLCHAR('/'); SERIAL_PROTOCOLCHAR('/');
SERIAL_PROTOCOLLN(filesize); SERIAL_PROTOCOLLN(filesize);
} }
else { else
SERIAL_PROTOCOLLNPGM(MSG_SD_NOT_PRINTING); SERIAL_PROTOCOLLNPGM(MSG_SD_NOT_PRINTING);
}
} }
void CardReader::write_command(char *buf) { void CardReader::write_command(char *buf) {
char* begin = buf; char* begin = buf;
char* npos = 0; char* npos = NULL;
char* end = buf + strlen(buf) - 1; char* end = buf + strlen(buf) - 1;
file.writeError = false; file.writeError = false;

@ -20,8 +20,8 @@
* *
*/ */
#ifndef CARDREADER_H #ifndef _CARDREADER_H_
#define CARDREADER_H #define _CARDREADER_H_
#define MAX_DIR_DEPTH 10 // Maximum folder depth #define MAX_DIR_DEPTH 10 // Maximum folder depth
@ -35,13 +35,15 @@ public:
void initsd(); void initsd();
void write_command(char *buf); void write_command(char *buf);
//files auto[0-9].g on the sd card are performed in a row // Files auto[0-9].g on the sd card are performed in sequence.
//this is to delay autostart and hence the initialisaiton of the sd card to some seconds after the normal init, so the device is available quick after a reset // This is to delay autostart and hence the initialisation of
// the sd card to some seconds after the normal init, so the
// device is available soon after a reset.
void checkautostart(bool x); void checkautostart(bool x);
void openFile(char* name, bool read, bool push_current=false); void openFile(char* name, bool read, bool push_current=false);
void openLogFile(char* name); void openLogFile(char* name);
void removeFile(char* name); void removeFile(const char * const name);
void closefile(bool store_location=false); void closefile(bool store_location=false);
void release(); void release();
void openAndPrintFile(const char *name); void openAndPrintFile(const char *name);
@ -151,8 +153,7 @@ private:
uint8_t file_subcall_ctr; uint8_t file_subcall_ctr;
uint32_t filespos[SD_PROCEDURE_DEPTH]; uint32_t filespos[SD_PROCEDURE_DEPTH];
char proc_filenames[SD_PROCEDURE_DEPTH][MAXPATHNAMELENGTH]; char proc_filenames[SD_PROCEDURE_DEPTH][MAXPATHNAMELENGTH];
uint32_t filesize; uint32_t filesize, sdpos;
uint32_t sdpos;
millis_t next_autostart_ms; millis_t next_autostart_ms;
bool autostart_stilltocheck; //the sd start is delayed, because otherwise the serial cannot answer fast enought to make contact with the hostsoftware. bool autostart_stilltocheck; //the sd start is delayed, because otherwise the serial cannot answer fast enought to make contact with the hostsoftware.
@ -188,4 +189,4 @@ private:
extern CardReader card; extern CardReader card;
#endif // CARDREADER_H #endif // _CARDREADER_H_

Loading…
Cancel
Save