Commit fc2d65a2 authored by MagoKimbra's avatar MagoKimbra

Update SD

parent f076bcb0
......@@ -1026,6 +1026,7 @@
//#define SDSLOW // Use slower SD transfer mode (not normally needed - uncomment if you're getting volume init error)
//#define SDEXTRASLOW // Use even slower SD transfer mode (not normally needed - uncomment if you're getting volume init error)
//#define SD_CHECK_AND_RETRY // Use CRC checks and retries on the SD communication
//#define SD_EXTENDED_DIR // Show extended directory including file length. Don't use this with Pronterface
// Decomment this if you are external SD without DETECT_PIN
//#define SD_DISABLED_DETECT
......@@ -1044,9 +1045,6 @@
// using:
//#define MENU_ADDAUTOSTART
// This allows hosts to request long names for files and folders with M33
//#define LONG_FILENAME_HOST_SUPPORT
// This enable the firmware to write some configuration that require frequent update, on the SD card
//#define SD_SETTINGS // Uncomment to enable
#define SD_CFG_SECONDS 300 // seconds between update
......
......@@ -930,8 +930,7 @@ void ConfigSD_ResetDefault() {
void ConfigSD_StoreSettings() {
if(!IS_SD_INSERTED || card.isFileOpen() || card.sdprinting) return;
set_sd_dot();
card.setroot(true);
card.openFile((char *)CFG_SD_FILE, false, true, false);
card.startWrite((char *)CFG_SD_FILE);
char buff[CFG_SD_MAX_VALUE_LEN];
#if HAS(POWER_CONSUMPTION_SENSOR)
ltoa(power_consumption_hour, buff, 10);
......@@ -941,9 +940,7 @@ void ConfigSD_ResetDefault() {
card.unparseKeyLine(cfgSD_KEY[SD_CFG_TME], buff);
ltoa(printer_usage_filament, buff, 10);
card.unparseKeyLine(cfgSD_KEY[SD_CFG_FIL], buff);
card.closeFile(false);
card.setlast();
config_last_update = millis();
unset_sd_dot();
}
......@@ -954,8 +951,7 @@ void ConfigSD_ResetDefault() {
char key[CFG_SD_MAX_KEY_LEN], value[CFG_SD_MAX_VALUE_LEN];
int k_idx;
int k_len, v_len;
card.setroot(true);
card.openFile((char *)CFG_SD_FILE, true, true, false);
card.selectFile((char *)CFG_SD_FILE);
while(true) {
k_len = CFG_SD_MAX_KEY_LEN;
v_len = CFG_SD_MAX_VALUE_LEN;
......@@ -984,7 +980,6 @@ void ConfigSD_ResetDefault() {
}
}
card.closeFile(false);
card.setlast();
config_readed = true;
unset_sd_dot();
}
......
......@@ -40,6 +40,8 @@
#define MKSERIAL Serial
#endif
#define PACK
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
......
......@@ -683,15 +683,11 @@ void loop() {
char* command = command_queue[cmd_queue_index_r];
if (strstr_P(command, PSTR("M29"))) {
// M29 closes the file
card.closeFile();
ECHO_EM(SERIAL_FILE_SAVED);
card.finishWrite();
}
else {
// Write the string from the read buffer to SD
card.write_command(command);
if (card.logging)
process_next_command(); // The card is saving because it's logging
else
ECHO_L(OK);
}
}
......@@ -826,14 +822,16 @@ void get_command() {
commands_in_queue += 1;
serial_count = 0; //clear buffer
} else if (serial_char == '\\') { // Handle escapes
}
else if (serial_char == '\\') { // Handle escapes
if (MKSERIAL.available() > 0 && commands_in_queue < BUFSIZE) {
// if we have one more character, copy it over
serial_char = MKSERIAL.read();
command_queue[cmd_queue_index_w][serial_count++] = serial_char;
}
// otherwise do nothing
} else { // its not a newline, carriage return or escape char
}
else { // its not a newline, carriage return or escape char
if (serial_char == ';') comment_mode = true;
if (!comment_mode) command_queue[cmd_queue_index_w][serial_count++] = serial_char;
}
......@@ -4282,28 +4280,28 @@ inline void gcode_M17() {
* M21: Init SD Card
*/
inline void gcode_M21() {
card.initsd();
card.mount();
}
/**
* M22: Release SD Card
*/
inline void gcode_M22() {
card.release();
card.unmount();
}
/**
* M23: Select a file
*/
inline void gcode_M23() {
card.openFile(current_command_args, true);
card.selectFile(current_command_args);
}
/**
* M24: Start SD Print
*/
inline void gcode_M24() {
card.startFileprint();
card.startPrint();
print_job_start_ms = millis();
#if HAS(POWER_CONSUMPTION_SENSOR)
startpower = power_consumption_hour;
......@@ -4314,7 +4312,7 @@ inline void gcode_M17() {
* M25: Pause SD Print
*/
inline void gcode_M25() {
card.pauseSDPrint();
card.pausePrint();
}
/**
......@@ -4329,14 +4327,14 @@ inline void gcode_M17() {
* M27: Get SD Card status
*/
inline void gcode_M27() {
card.getStatus();
card.printStatus();
}
/**
* M28: Start SD Write
*/
inline void gcode_M28() {
card.openFile(current_command_args, false);
card.startWrite(current_command_args, false);
}
/**
......@@ -4352,8 +4350,8 @@ inline void gcode_M17() {
*/
inline void gcode_M30() {
if (card.cardOK) {
card.closeFile();
card.removeFile(current_command_args);
card.fat.chdir();
card.deleteFile(current_command_args);
}
}
#endif
......@@ -4372,62 +4370,16 @@ inline void gcode_M31() {
autotempShutdown();
}
#if ENABLED(SDSUPPORT)
/**
* M32: Select file and start SD Print
/**
* M32: Make Directory
*/
inline void gcode_M32() {
if (card.sdprinting) st_synchronize();
char* namestartpos = strchr(current_command_args, '!'); // Find ! to indicate filename string start.
if (!namestartpos)
namestartpos = current_command_args; // Default name position, 4 letters after the M
else
namestartpos++; // to skip the '!'
bool call_procedure = code_seen('P') && (seen_pointer < namestartpos);
inline void gcode_M32() {
if (card.cardOK) {
card.openFile(namestartpos, true, !call_procedure);
if (code_seen('S') && seen_pointer < namestartpos) // "S" (must occur _before_ the filename!)
card.setIndex(code_value_short());
card.startFileprint();
if (!call_procedure)
print_job_start_ms = millis(); // procedure calls count as normal print time.
card.fat.chdir();
card.makeDirectory(current_command_args);
card.mount();
}
}
#if ENABLED(LONG_FILENAME_HOST_SUPPORT)
/**
* M33: Get the long full path of a file or folder
*
* Parameters:
* <dospath> Case-insensitive DOS-style path to a file or folder
*
* Example:
* M33 miscel~1/armchair/armcha~1.gco
*
* Output:
* /Miscellaneous/Armchair/Armchair.gcode
*/
inline void gcode_M33() {
card.printLongPath(current_command_args);
}
#endif
/**
* M928: Start SD Write
*/
inline void gcode_M928() {
card.openLogFile(current_command_args);
}
#endif // SDSUPPORT
}
/**
* M42: Change pin status via GCode
......@@ -7061,16 +7013,8 @@ void process_next_command() {
gcode_M29(); break;
case 30: // M30 <filename> Delete File
gcode_M30(); break;
case 32: // M32 - Select file and start SD print
case 32: // M32 - Make directory
gcode_M32(); break;
#if ENABLED(LONG_FILENAME_HOST_SUPPORT)
case 33: // M33 - Get the long full path to a file or folder
gcode_M33(); break;
#endif
case 928: // M928 - Start SD write
gcode_M928(); break;
#endif //SDSUPPORT
case 31: // M31 take time since the start of the SD print or an M109 command
......
......@@ -83,7 +83,6 @@
#define SERIAL_COMPILED "Compiled: "
#define SERIAL_FREE_MEMORY "Free Memory: "
#define SERIAL_PLANNER_BUFFER_BYTES " PlannerBufferBytes: "
#define SERIAL_FILE_SAVED "Done saving file."
#define SERIAL_ERR_LINE_NO "Line Number is not Last Line Number+1, Last Line: "
#define SERIAL_ERR_CHECKSUM_MISMATCH "checksum mismatch, Last Line: "
#define SERIAL_ERR_NO_CHECKSUM "No Checksum with line number, Last Line: "
......@@ -118,6 +117,7 @@
#define SERIAL_HOTEND_OFFSET "Hotend offsets:"
#define SERIAL_EMPTY_PLANE "Autolevel can only be execute on an actual plane, make sure width and height are not 0!"
#define SERIAL_FILRUNOUT_PIN "filament_runout_pin: "
#define SERIAL_SD_ERRORCODE "SD errorCode:"
#define SERIAL_SD_CANT_OPEN_SUBDIR "Cannot open subdir"
#define SERIAL_SD_INIT_FAIL "SD init fail"
#define SERIAL_SD_VOL_INIT_FAIL "volume.init failed"
......@@ -129,13 +129,16 @@
#define SERIAL_SD_SIZE " Size: "
#define SERIAL_SD_FILE_SELECTED "File selected"
#define SERIAL_SD_WRITE_TO_FILE "Writing to file: "
#define SERIAL_SD_FILE_SAVED "Done saving file."
#define SERIAL_SD_PRINTING_BYTE "SD printing byte "
#define SERIAL_SD_NOT_PRINTING "Not SD printing"
#define SERIAL_SD_ERR_WRITE_TO_FILE "error writing to file"
#define SERIAL_SD_CANT_ENTER_SUBDIR "Cannot enter subdir: "
#define SERIAL_SD_FILE_DELETED "File deleted:"
#define SERIAL_SD_FILE_DELETED "File deleted"
#define SERIAL_SD_FILE_DELETION_ERR "Deletion failed"
#define SERIAL_SD_DIRECTORY_CREATED "Directory created"
#define SERIAL_SD_CREATION_FAILED "Creation failed"
#define SERIAL_SD_SLASH "/"
#define SERIAL_SD_FILE_DELETION_ERR "Deletion failed, File: "
#define SERIAL_SD_MAX_DEPTH "trying to call sub-gcode files with too many levels. MAX level is:"
#define SERIAL_STEPPER_TOO_HIGH "Steprate too high: "
......
......@@ -540,27 +540,22 @@ void lcd_implementation_drawedit(const char* pstr, char* value) {
}
#if ENABLED(SDSUPPORT)
static void _drawmenu_sd(bool isSelected, uint8_t row, const char* pstr, const char* filename, char* const longFilename, bool isDir) {
static void _drawmenu_sd(bool isSelected, uint8_t row, const char* pstr, const char* longFilename, bool isDir) {
char c;
uint8_t n = LCD_WIDTH - 1;
if (longFilename[0]) {
filename = longFilename;
longFilename[n] = '\0';
}
lcd_implementation_mark_as_selected(row, isSelected);
if (isDir) lcd_print(LCD_STR_FOLDER[0]);
while ((c = *filename)) {
while ((c = *longFilename)) {
n -= lcd_print(c);
filename++;
longFilename++;
}
while (n--) lcd_print(' ');
}
#define lcd_implementation_drawmenu_sdfile(sel, row, pstr, filename, longFilename) _drawmenu_sd(sel, row, pstr, filename, longFilename, false)
#define lcd_implementation_drawmenu_sddirectory(sel, row, pstr, filename, longFilename) _drawmenu_sd(sel, row, pstr, filename, longFilename, true)
#define lcd_implementation_drawmenu_sdfile(sel, row, pstr, longFilename) _drawmenu_sd(sel, row, pstr, longFilename, false)
#define lcd_implementation_drawmenu_sddirectory(sel, row, pstr, longFilename) _drawmenu_sd(sel, row, pstr, longFilename, true)
#endif //SDSUPPORT
......
......@@ -109,8 +109,8 @@ static void lcd_status_screen();
#if ENABLED(SDSUPPORT)
static void lcd_sdcard_menu();
static void menu_action_sdfile(const char* filename, char* longFilename);
static void menu_action_sddirectory(const char* filename, char* longFilename);
static void menu_action_sdfile(const char* longFilename);
static void menu_action_sddirectory(const char* longFilename);
#endif
#define ENCODER_FEEDRATE_DEADZONE 10
......@@ -417,9 +417,9 @@ static void lcd_return_to_status() { lcd_goto_menu(lcd_status_screen); }
#if ENABLED(SDSUPPORT)
static void lcd_sdcard_pause() { card.pauseSDPrint(); }
static void lcd_sdcard_pause() { card.pausePrint(); }
static void lcd_sdcard_resume() { card.startFileprint(); }
static void lcd_sdcard_resume() { card.startPrint(); }
static void lcd_sdcard_stop() {
quickStop();
......@@ -481,8 +481,6 @@ static void lcd_main_menu() {
#if ENABLED(SDSUPPORT) && ENABLED(MENU_ADDAUTOSTART)
static void lcd_autostart_sd() {
card.autostart_index = 0;
card.setroot();
card.checkautostart(true);
}
#endif
......@@ -1517,7 +1515,7 @@ static void lcd_control_volumetric_menu() {
#if !PIN_EXISTS(SD_DETECT)
static void lcd_sd_refresh() {
card.initsd();
card.mount();
currentMenuViewOffset = 0;
}
#endif
......@@ -1534,31 +1532,23 @@ static void lcd_control_volumetric_menu() {
*/
void lcd_sdcard_menu() {
if (lcdDrawUpdate == 0 && LCD_CLICKED == 0) return; // nothing to do (so don't thrash the SD card)
uint16_t fileCnt = card.getnrfilenames();
card.updateSDFileCount();
uint16_t fileCnt = card.nrFiles;
char LongFileName[LONG_FILENAME_LENGTH + 1];
START_MENU(lcd_main_menu);
MENU_ITEM(back, MSG_MAIN, lcd_main_menu);
card.getWorkDirName();
if (card.filename[0] == '/') {
#if !PIN_EXISTS(SD_DETECT)
MENU_ITEM(function, LCD_STR_REFRESH MSG_REFRESH, lcd_sd_refresh);
#endif
dir_t* p = NULL;
SdBaseFile *root = card.fat.vwd();
root->rewind();
while ((p = root->getLongFilename(p, tempLongFilename, 0, NULL)) != NULL) {
if (_menuItemNr == _lineNr) {
strcpy(LongFileName, tempLongFilename);
if (DIR_IS_SUBDIR(p)) {
MENU_ITEM(sddirectory, MSG_CARD_MENU, LongFileName);
}
else {
MENU_ITEM(function, LCD_STR_FOLDER "..", lcd_sd_updir);
MENU_ITEM(sdfile, MSG_CARD_MENU, LongFileName);
}
for (uint16_t i = 0; i < fileCnt; i++) {
if (_menuItemNr == _lineNr) {
card.getfilename(
#if ENABLED(SDCARD_RATHERRECENTFIRST)
fileCnt-1 -
#endif
i
);
if (card.filenameIsDir)
MENU_ITEM(sddirectory, MSG_CARD_MENU, card.filename, card.longFilename);
else
MENU_ITEM(sdfile, MSG_CARD_MENU, card.filename, card.longFilename);
}
else {
MENU_ITEM_DUMMY();
......@@ -1714,18 +1704,18 @@ static void menu_action_function(menuFunc_t func) { (*func)(); }
#if ENABLED(SDSUPPORT)
static void menu_action_sdfile(const char* filename, char* longFilename) {
static void menu_action_sdfile(const char* longFilename) {
char cmd[30];
char* c;
sprintf_P(cmd, PSTR("M23 %s"), filename);
sprintf_P(cmd, PSTR("M23 %s"), longFilename);
for (c = &cmd[4]; *c; c++) *c = tolower(*c);
enqueuecommand(cmd);
enqueuecommands_P(PSTR("M24"));
lcd_return_to_status();
}
static void menu_action_sddirectory(const char* filename, char* longFilename) {
card.chdir(filename);
static void menu_action_sddirectory(const char* longFilename) {
card.chdir(longFilename);
encoderPosition = 0;
}
......@@ -1851,11 +1841,11 @@ void lcd_update() {
);
if (sd_status) {
card.initsd();
card.mount();
if (lcd_sd_status != 2) LCD_MESSAGEPGM(MSG_SD_INSERTED);
}
else {
card.release();
card.unmount();
if (lcd_sd_status != 2) LCD_MESSAGEPGM(MSG_SD_REMOVED);
}
......
......@@ -11,8 +11,8 @@
void lcd_update();
void lcd_init();
bool lcd_hasstatus();
void lcd_setstatus(const char* message, const bool persist=false);
void lcd_setstatuspgm(const char* message, const uint8_t level=0);
void lcd_setstatus(const char* message, const bool persist = false);
void lcd_setstatuspgm(const char* message, const uint8_t level = 0);
void lcd_setalertstatuspgm(const char* message);
void lcd_reset_alert_level();
bool lcd_detected(void);
......
......@@ -782,29 +782,25 @@ void lcd_implementation_drawedit(const char* pstr, char* value) {
#if ENABLED(SDSUPPORT)
static void lcd_implementation_drawmenu_sd(bool sel, uint8_t row, const char* pstr, const char* filename, char* longFilename, uint8_t concat, char post_char) {
static void lcd_implementation_drawmenu_sd(bool sel, uint8_t row, const char* pstr, const char* longFilename, uint8_t concat, char post_char) {
char c;
uint8_t n = LCD_WIDTH - concat;
lcd.setCursor(0, row);
lcd.print(sel ? '>' : ' ');
if (longFilename[0]) {
filename = longFilename;
longFilename[n] = '\0';
}
while ((c = *filename) && n > 0) {
while ((c = *longFilename) && n > 0) {
n -= lcd_print(c);
filename++;
longFilename++;
}
while (n--) lcd.print(' ');
lcd.print(post_char);
}
static void lcd_implementation_drawmenu_sdfile(bool sel, uint8_t row, const char* pstr, const char* filename, char* longFilename) {
lcd_implementation_drawmenu_sd(sel, row, pstr, filename, longFilename, 2, ' ');
static void lcd_implementation_drawmenu_sdfile(bool sel, uint8_t row, const char* pstr, const char* longFilename) {
lcd_implementation_drawmenu_sd(sel, row, pstr, longFilename, 2, ' ');
}
static void lcd_implementation_drawmenu_sddirectory(bool sel, uint8_t row, const char* pstr, const char* filename, char* longFilename) {
lcd_implementation_drawmenu_sd(sel, row, pstr, filename, longFilename, 2, LCD_STR_FOLDER[0]);
static void lcd_implementation_drawmenu_sddirectory(bool sel, uint8_t row, const char* pstr, const char* longFilename) {
lcd_implementation_drawmenu_sd(sel, row, pstr, longFilename, 2, LCD_STR_FOLDER[0]);
}
#endif // SDSUPPORT
......
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
/* Arduino Sd2Card Library
* Copyright (C) 2009 by William Greiman
*
* This file is part of the Arduino Sd2Card Library
*
* This Library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the Arduino Sd2Card Library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "../../base.h"
#if ENABLED(SDSUPPORT)
#ifndef Sd2Card_h
#define Sd2Card_h
/**
* \file
* \brief Sd2Card class for V2 SD/SDHC cards
*/
#include "SdFatConfig.h"
#include "SdInfo.h"
//------------------------------------------------------------------------------
// SPI speed is F_CPU/2^(1 + index), 0 <= index <= 6
/** Set SCK to max rate of F_CPU/2. See Sd2Card::setSckRate(). */
uint8_t const SPI_FULL_SPEED = 0;
/** Set SCK rate to F_CPU/4. See Sd2Card::setSckRate(). */
uint8_t const SPI_HALF_SPEED = 1;
/** Set SCK rate to F_CPU/8. See Sd2Card::setSckRate(). */
uint8_t const SPI_QUARTER_SPEED = 2;
/** Set SCK rate to F_CPU/16. See Sd2Card::setSckRate(). */
uint8_t const SPI_EIGHTH_SPEED = 3;
/** Set SCK rate to F_CPU/32. See Sd2Card::setSckRate(). */
uint8_t const SPI_SIXTEENTH_SPEED = 4;
//------------------------------------------------------------------------------
/** init timeout ms */
uint16_t const SD_INIT_TIMEOUT = 2000;
/** erase timeout 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
/** timeout error for command CMD0 (initialize card in SPI mode) */
uint8_t const SD_CARD_ERROR_CMD0 = 0X1;
/** CMD8 was not accepted - not a valid SD card*/
uint8_t const SD_CARD_ERROR_CMD8 = 0X2;
/** card returned an error response for CMD12 (write stop) */
uint8_t const SD_CARD_ERROR_CMD12 = 0X3;
/** card returned an error response for CMD17 (read block) */
uint8_t const SD_CARD_ERROR_CMD17 = 0X4;
/** card returned an error response for CMD18 (read multiple block) */
uint8_t const SD_CARD_ERROR_CMD18 = 0X5;
/** card returned an error response for CMD24 (write block) */
uint8_t const SD_CARD_ERROR_CMD24 = 0X6;
/** WRITE_MULTIPLE_BLOCKS command failed */
uint8_t const SD_CARD_ERROR_CMD25 = 0X7;
/** card returned an error response for CMD58 (read OCR) */
uint8_t const SD_CARD_ERROR_CMD58 = 0X8;
/** SET_WR_BLK_ERASE_COUNT failed */
uint8_t const SD_CARD_ERROR_ACMD23 = 0X9;
/** ACMD41 initialization process timeout */
uint8_t const SD_CARD_ERROR_ACMD41 = 0XA;
/** card returned a bad CSR version field */
uint8_t const SD_CARD_ERROR_BAD_CSD = 0XB;
/** erase block group command failed */
uint8_t const SD_CARD_ERROR_ERASE = 0XC;
/** card not capable of single block erase */
uint8_t const SD_CARD_ERROR_ERASE_SINGLE_BLOCK = 0XD;
/** 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
/** Standard capacity V1 SD card */
uint8_t const SD_CARD_TYPE_SD1 = 1;
/** Standard capacity V2 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
*/
//------------------------------------------------------------------------------
#if MEGA_SOFT_SPI && (defined(__AVR_ATmega1280__)||defined(__AVR_ATmega2560__))
#define SOFTWARE_SPI
#elif USE_SOFTWARE_SPI
#define SOFTWARE_SPI
#endif // MEGA_SOFT_SPI
//------------------------------------------------------------------------------
// SPI pin definitions - do not edit here - change in SdFatConfig.h
//
#if DISABLED(SOFTWARE_SPI)
// hardware pin defs
/** The default chip select pin for the SD card is SS. */
uint8_t const SD_CHIP_SELECT_PIN = SDSS;
// The following three pins must not be redefined for hardware SPI.
/** SPI Master Out Slave In pin */
uint8_t const SPI_MOSI_PIN = MOSI_PIN;
/** SPI Master In Slave Out pin */
uint8_t const SPI_MISO_PIN = MISO_PIN;
/** SPI Clock pin */
uint8_t const SPI_SCK_PIN = SCK_PIN;
#else // SOFTWARE_SPI
/** SPI chip select pin */
uint8_t const SD_CHIP_SELECT_PIN = SOFT_SPI_CS_PIN;
/** SPI Master Out Slave In pin */
uint8_t const SPI_MOSI_PIN = SOFT_SPI_MOSI_PIN;
/** SPI Master In Slave Out pin */
uint8_t const SPI_MISO_PIN = SOFT_SPI_MISO_PIN;
/** SPI Clock pin */
uint8_t const SPI_SCK_PIN = SOFT_SPI_SCK_PIN;
#endif // SOFTWARE_SPI
//------------------------------------------------------------------------------
/**
* \class Sd2Card
* \brief Raw access to SD and SDHC flash memory cards.
*/
class Sd2Card {
public:
/** Construct an instance of Sd2Card. */
Sd2Card() : errorCode_(SD_CARD_ERROR_INIT_NOT_CALLED), type_(0) {}
uint32_t cardSize();
bool erase(uint32_t firstBlock, uint32_t lastBlock);
bool eraseSingleBlockEnable();
/**
* Set SD error code.
* \param[in] code value for error code.
*/
void error(uint8_t code) {errorCode_ = code;}
/**
* \return error code for last error. See Sd2Card.h for a list of error codes.
*/
int errorCode() const {return errorCode_;}
/** \return error data for last error. */
int errorData() const {return status_;}
/**
* Initialize an SD flash memory card with default clock rate and chip
* select pin. See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin).
*
* \return true for success or false for failure.
*/
bool init(uint8_t sckRateID = SPI_FULL_SPEED,
uint8_t chipSelectPin = SD_CHIP_SELECT_PIN);
bool readBlock(uint32_t block, uint8_t* dst);
/**
* Read a card's CID register. The CID contains card identification
* information such as Manufacturer ID, Product name, Product serial
* number and Manufacturing date.
*
* \param[out] cid pointer to area for returned data.
*
* \return true for success or false for failure.
*/
bool readCID(cid_t* cid) {
return readRegister(CMD10, cid);
}
/**
* Read a card's CSD register. The CSD contains Card-Specific Data that
* provides information regarding access to the card's contents.
*
* \param[out] csd pointer to area for returned data.
*
* \return true for success or false for failure.
*/
bool readCSD(csd_t* csd) {
return readRegister(CMD9, csd);
}
bool readData(uint8_t* dst);
bool readStart(uint32_t blockNumber);
bool readStop();
bool setSckRate(uint8_t sckRateID);
/** Return the card type: SD V1, SD V2 or SDHC
* \return 0 - SD V1, 1 - SD V2, or 3 - SDHC.
*/
int type() const {return type_;}
bool writeBlock(uint32_t blockNumber, const uint8_t* src);
bool writeData(const uint8_t* src);
bool writeStart(uint32_t blockNumber, uint32_t eraseCount);
bool writeStop();
private:
//----------------------------------------------------------------------------
uint8_t chipSelectPin_;
uint8_t errorCode_;
uint8_t spiRate_;
uint8_t status_;
uint8_t type_;
// private functions
uint8_t cardAcmd(uint8_t cmd, uint32_t arg) {
cardCommand(CMD55, 0);
return cardCommand(cmd, arg);
}
uint8_t cardCommand(uint8_t cmd, uint32_t arg);
bool readData(uint8_t* dst, uint16_t count);
bool readRegister(uint8_t cmd, void* buf);
void chipSelectHigh();
void chipSelectLow();
void type(uint8_t value) {type_ = value;}
bool waitNotBusy(uint16_t timeoutMillis);
bool writeData(uint8_t token, const uint8_t* src);
};
#endif // Sd2Card_h
#endif
\ No newline at end of file
This diff is collapsed.
/* Arduino SdFat Library
* Copyright (C) 2009 by William Greiman
*
* This file is part of the Arduino SdFat Library
*
* This Library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the Arduino SdFat Library. If not, see
* <http://www.gnu.org/licenses/>.
*/
/**
* \file
* \brief configuration definitions
*/
#include "../../base.h"
#if ENABLED(SDSUPPORT)
#ifndef SdFatConfig_h
#define SdFatConfig_h
#include <stdint.h>
//------------------------------------------------------------------------------
/**
* To use multiple SD cards set USE_MULTIPLE_CARDS nonzero.
*
* Using multiple cards costs 400 - 500 bytes of flash.
*
* Each card requires about 550 bytes of SRAM so use of a Mega is recommended.
*/
#define USE_MULTIPLE_CARDS 0
//------------------------------------------------------------------------------
/**
* Call flush for endl if ENDL_CALLS_FLUSH is nonzero
*
* The standard for iostreams is to call flush. This is very costly for
* SdFat. Each call to flush causes 2048 bytes of I/O to the SD.
*
* SdFat has a single 512 byte buffer for SD I/O so it must write the current
* data block to the SD, read the directory block from the SD, update the
* directory entry, write the directory block to the SD and read the data
* block back into the buffer.
*
* The SD flash memory controller is not designed for this many rewrites
* so performance may be reduced by more than a factor of 100.
*
* If ENDL_CALLS_FLUSH is zero, you must call flush and/or close to force
* all data to be written to the SD.
*/
#define ENDL_CALLS_FLUSH 0
//------------------------------------------------------------------------------
/**
* Allow use of deprecated functions if ALLOW_DEPRECATED_FUNCTIONS is nonzero
*/
#define ALLOW_DEPRECATED_FUNCTIONS 1
//------------------------------------------------------------------------------
/**
* Allow FAT12 volumes if FAT12_SUPPORT is nonzero.
* FAT12 has not been well tested.
*/
#define FAT12_SUPPORT 0
//------------------------------------------------------------------------------
/**
* SPI init rate for SD initialization commands. Must be 5 (F_CPU/64)
* or 6 (F_CPU/128).
*/
#define SPI_SD_INIT_RATE 5
//------------------------------------------------------------------------------
/**
* 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.
*/
#define SET_SPI_SS_HIGH 1
//------------------------------------------------------------------------------
/**
* Define MEGA_SOFT_SPI nonzero to use software SPI on Mega Arduinos.
* Pins used are SS 10, MOSI 11, MISO 12, and SCK 13.
*
* MEGA_SOFT_SPI allows an unmodified Adafruit GPS Shield to be used
* on Mega Arduinos. Software SPI works well with GPS Shield V1.1
* but many SD cards will fail with GPS Shield V1.0.
*/
#define MEGA_SOFT_SPI 0
//------------------------------------------------------------------------------
/**
* Set USE_SOFTWARE_SPI nonzero to always use software SPI.
*/
#define USE_SOFTWARE_SPI 0
// define software SPI pins so Mega can use unmodified 168/328 shields
/** Software SPI chip select pin for the SD */
uint8_t const SOFT_SPI_CS_PIN = 10;
/** Software SPI Master Out Slave In pin */
uint8_t const SOFT_SPI_MOSI_PIN = 11;
/** Software SPI Master In Slave Out pin */
uint8_t const SOFT_SPI_MISO_PIN = 12;
/** Software SPI Clock pin */
uint8_t const SOFT_SPI_SCK_PIN = 13;
//------------------------------------------------------------------------------
/**
* The __cxa_pure_virtual function is an error handler that is invoked when
* a pure virtual function is called.
*/
#define USE_CXA_PURE_VIRTUAL 1
/** Number of UTF-16 characters per entry */
#define FILENAME_LENGTH 13
/**
* Defines for long (vfat) filenames
*/
/** Number of VFAT entries used. Every entry has 13 UTF-16 characters */
#define MAX_VFAT_ENTRIES (2)
/** Total size of the buffer used to store the long filenames */
#define LONG_FILENAME_LENGTH (FILENAME_LENGTH * MAX_VFAT_ENTRIES + 1)
#endif // SdFatConfig_h
#endif
/* Arduino SdFat Library
* Copyright (C) 2009 by William Greiman
*
* This file is part of the Arduino SdFat Library
*
* This Library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the Arduino SdFat Library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "../../base.h"
#if ENABLED(SDSUPPORT)
#include "SdFile.h"
/** 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] oflag Values for \a oflag are constructed by a bitwise-inclusive
* OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
*/
SdFile::SdFile(const char* path, uint8_t oflag) : SdBaseFile(path, oflag) {
}
//------------------------------------------------------------------------------
/** Write data to an open file.
*
* \note Data is moved to the cache but may not be written to the
* storage device until sync() is called.
*
* \param[in] buf Pointer to the location of the data to be written.
*
* \param[in] nbyte Number of bytes to write.
*
* \return For success write() returns the number of bytes written, always
* \a nbyte. If an error occurs, write() returns -1. Possible errors
* include write() is called before a file has been opened, write is called
* 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) {
return SdBaseFile::write(buf, nbyte);
}
//------------------------------------------------------------------------------
/** Write a byte to a file. Required by the Arduino Print class.
* \param[in] b the byte to be written.
* Use writeError to check for errors.
*/
#if ARDUINO >= 100
size_t SdFile::write(uint8_t b) {
return SdBaseFile::write(&b, 1);
}
#else
void SdFile::write(uint8_t b) {
SdBaseFile::write(&b, 1);
}
#endif
//------------------------------------------------------------------------------
/** Write a string to a file. Used by the Arduino Print class.
* \param[in] str Pointer to the string.
* Use writeError to check for errors.
*/
void SdFile::write(const char* str) {
SdBaseFile::write(str, strlen(str));
}
//------------------------------------------------------------------------------
/** Write a PROGMEM string to a file.
* \param[in] str Pointer to the PROGMEM string.
* Use writeError to check for errors.
*/
void SdFile::write_P(PGM_P str) {
for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c);
}
//------------------------------------------------------------------------------
/** Write a PROGMEM string followed by CR/LF to a file.
* \param[in] str Pointer to the PROGMEM string.
* Use writeError to check for errors.
*/
void SdFile::writeln_P(PGM_P str) {
write_P(str);
write_P(PSTR("\r\n"));
}
#endif
/* Arduino SdFat Library
* Copyright (C) 2009 by William Greiman
*
* This file is part of the Arduino SdFat Library
*
* This Library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the Arduino SdFat Library. If not, see
* <http://www.gnu.org/licenses/>.
*/
/**
* \file
* \brief SdFile class
*/
#include "../../base.h"
#if ENABLED(SDSUPPORT)
#include "SdBaseFile.h"
#include <Print.h>
#ifndef SdFile_h
#define SdFile_h
//------------------------------------------------------------------------------
/**
* \class SdFile
* \brief SdBaseFile with Print.
*/
class SdFile : public SdBaseFile, public Print {
public:
SdFile() {}
SdFile(const char* name, uint8_t oflag);
#if ARDUINO >= 100
size_t write(uint8_t b);
#else
void write(uint8_t b);
#endif
int16_t write(const void* buf, uint16_t nbyte);
void write(const char* str);
void write_P(PGM_P str);
void writeln_P(PGM_P str);
};
#endif // SdFile_h
#endif
/* Arduino Sd2Card Library
* Copyright (C) 2009 by William Greiman
*
* This file is part of the Arduino Sd2Card Library
*
* This Library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the Arduino Sd2Card Library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "../../base.h"
#if ENABLED(SDSUPPORT)
#ifndef SdInfo_h
#define SdInfo_h
#include <stdint.h>
// Based on the document:
//
// SD Specifications
// Part 1
// Physical Layer
// Simplified Specification
// Version 3.01
// May 18, 2010
//
// http://www.sdcard.org/developers/tech/sdcard/pls/simplified_specs
//------------------------------------------------------------------------------
// SD card commands
/** GO_IDLE_STATE - init card in spi mode if CS low */
uint8_t const CMD0 = 0X00;
/** SEND_IF_COND - verify SD Memory Card interface operating condition.*/
uint8_t const CMD8 = 0X08;
/** SEND_CSD - read the Card Specific Data (CSD register) */
uint8_t const CMD9 = 0X09;
/** SEND_CID - read the card identification information (CID register) */
uint8_t const CMD10 = 0X0A;
/** STOP_TRANSMISSION - end multiple block read sequence */
uint8_t const CMD12 = 0X0C;
/** SEND_STATUS - read the card status register */
uint8_t const CMD13 = 0X0D;
/** READ_SINGLE_BLOCK - read a single data block from the card */
uint8_t const CMD17 = 0X11;
/** READ_MULTIPLE_BLOCK - read a multiple data blocks from the card */
uint8_t const CMD18 = 0X12;
/** WRITE_BLOCK - write a single data block to the card */
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 */
uint8_t const R1_READY_STATE = 0X00;
/** status for card in the idle state */
uint8_t const R1_IDLE_STATE = 0X01;
/** status bit for illegal command */
uint8_t const R1_ILLEGAL_COMMAND = 0X04;
/** start data token for read or write single block*/
uint8_t const DATA_START_BLOCK = 0XFE;
/** stop token for write multiple blocks*/
uint8_t const STOP_TRAN_TOKEN = 0XFD;
/** start data token for write multiple blocks*/
uint8_t const WRITE_MULTIPLE_TOKEN = 0XFC;
/** mask for data response tokens after a write block operation */
uint8_t const DATA_RES_MASK = 0X1F;
/** write data accepted token */
uint8_t const DATA_RES_ACCEPTED = 0X05;
//------------------------------------------------------------------------------
/** Card IDentification (CID) register */
typedef struct CID {
// byte 0
/** Manufacturer ID */
unsigned char mid;
// byte 1-2
/** OEM/Application ID */
char oid[2];
// byte 3-7
/** Product name */
char pnm[5];
// byte 8
/** Product revision least significant digit */
unsigned char prv_m : 4;
/** Product revision most significant digit */
unsigned char prv_n : 4;
// byte 9-12
/** Product serial number */
uint32_t psn;
// byte 13
/** Manufacturing date year low digit */
unsigned char mdt_year_high : 4;
/** not used */
unsigned char reserved : 4;
// byte 14
/** Manufacturing date month */
unsigned char mdt_month : 4;
/** Manufacturing date year low digit */
unsigned char mdt_year_low : 4;
// byte 15
/** not used always 1 */
unsigned char always1 : 1;
/** CRC7 checksum */
unsigned char crc : 7;
} cid_t;
//------------------------------------------------------------------------------
/** CSD for version 1.00 cards */
typedef struct CSDV1 {
// byte 0
unsigned char reserved1 : 6;
unsigned char csd_ver : 2;
// byte 1
unsigned char taac;
// byte 2
unsigned char nsac;
// byte 3
unsigned char tran_speed;
// byte 4
unsigned char ccc_high;
// byte 5
unsigned char read_bl_len : 4;
unsigned char ccc_low : 4;
// byte 6
unsigned char c_size_high : 2;
unsigned char reserved2 : 2;
unsigned char dsr_imp : 1;
unsigned char read_blk_misalign : 1;
unsigned char write_blk_misalign : 1;
unsigned char read_bl_partial : 1;
// byte 7
unsigned char c_size_mid;
// byte 8
unsigned char vdd_r_curr_max : 3;
unsigned char vdd_r_curr_min : 3;
unsigned char c_size_low : 2;
// byte 9
unsigned char c_size_mult_high : 2;
unsigned char vdd_w_cur_max : 3;
unsigned char vdd_w_curr_min : 3;
// byte 10
unsigned char sector_size_high : 6;
unsigned char erase_blk_en : 1;
unsigned char c_size_mult_low : 1;
// byte 11
unsigned char wp_grp_size : 7;
unsigned char sector_size_low : 1;
// byte 12
unsigned char write_bl_len_high : 2;
unsigned char r2w_factor : 3;
unsigned char reserved3 : 2;
unsigned char wp_grp_enable : 1;
// byte 13
unsigned char reserved4 : 5;
unsigned char write_partial : 1;
unsigned char write_bl_len_low : 2;
// byte 14
unsigned char reserved5: 2;
unsigned char file_format : 2;
unsigned char tmp_write_protect : 1;
unsigned char perm_write_protect : 1;
unsigned char copy : 1;
/** Indicates the file format on the card */
unsigned char file_format_grp : 1;
// byte 15
unsigned char always1 : 1;
unsigned char crc : 7;
} csd1_t;
//------------------------------------------------------------------------------
/** CSD for version 2.00 cards */
typedef struct CSDV2 {
// byte 0
unsigned char reserved1 : 6;
unsigned char csd_ver : 2;
// byte 1
/** fixed to 0X0E */
unsigned char taac;
// byte 2
/** fixed to 0 */
unsigned char nsac;
// byte 3
unsigned char tran_speed;
// byte 4
unsigned char ccc_high;
// byte 5
/** This field is fixed to 9h, which indicates READ_BL_LEN=512 Byte */
unsigned char read_bl_len : 4;
unsigned char ccc_low : 4;
// byte 6
/** not used */
unsigned char reserved2 : 4;
unsigned char dsr_imp : 1;
/** fixed to 0 */
unsigned char read_blk_misalign : 1;
/** fixed to 0 */
unsigned char write_blk_misalign : 1;
/** fixed to 0 - no partial read */
unsigned char read_bl_partial : 1;
// byte 7
/** not used */
unsigned char reserved3 : 2;
/** high part of card size */
unsigned char c_size_high : 6;
// byte 8
/** middle part of card size */
unsigned char c_size_mid;
// byte 9
/** low part of card size */
unsigned char c_size_low;
// byte 10
/** sector size is fixed at 64 KB */
unsigned char sector_size_high : 6;
/** fixed to 1 - erase single is supported */
unsigned char erase_blk_en : 1;
/** not used */
unsigned char reserved4 : 1;
// byte 11
unsigned char wp_grp_size : 7;
/** sector size is fixed at 64 KB */
unsigned char sector_size_low : 1;
// byte 12
/** write_bl_len fixed for 512 byte blocks */
unsigned char write_bl_len_high : 2;
/** fixed value of 2 */
unsigned char r2w_factor : 3;
/** not used */
unsigned char reserved5 : 2;
/** fixed value of 0 - no write protect groups */
unsigned char wp_grp_enable : 1;
// byte 13
unsigned char reserved6 : 5;
/** always zero - no partial block read*/
unsigned char write_partial : 1;
/** write_bl_len fixed for 512 byte blocks */
unsigned char write_bl_len_low : 2;
// byte 14
unsigned char reserved7: 2;
/** Do not use always 0 */
unsigned char file_format : 2;
unsigned char tmp_write_protect : 1;
unsigned char perm_write_protect : 1;
unsigned char copy : 1;
/** Do not use always 0 */
unsigned char file_format_grp : 1;
// byte 15
/** not used always 1 */
unsigned char always1 : 1;
/** checksum */
unsigned char crc : 7;
} csd2_t;
//------------------------------------------------------------------------------
/** union of old and new style CSD register */
union csd_t {
csd1_t v1;
csd2_t v2;
};
#endif // SdInfo_h
#endif
This diff is collapsed.
/* Arduino SdFat Library
* Copyright (C) 2009 by William Greiman
*
* This file is part of the Arduino SdFat Library
*
* This Library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the Arduino SdFat Library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "../../base.h"
#if ENABLED(SDSUPPORT)
#ifndef SdVolume_h
#define SdVolume_h
/**
* \file
* \brief SdVolume class
*/
#include "SdFatConfig.h"
#include "Sd2Card.h"
#include "SdFatStructs.h"
//==============================================================================
// SdVolume class
/**
* \brief Cache for an SD data block
*/
union cache_t {
/** Used to access cached file data blocks. */
uint8_t data[512];
/** Used to access cached FAT16 entries. */
uint16_t fat16[256];
/** Used to access cached FAT32 entries. */
uint32_t fat32[128];
/** Used to access cached directory entries. */
dir_t dir[16];
/** 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
* \brief Access FAT16 and FAT32 volumes on SD and SDHC cards.
*/
class SdVolume {
public:
/** Create an instance of SdVolume */
SdVolume() : fatType_(0) {}
/** 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.
* \return A pointer to the cache buffer or zero if an error occurs.
*/
cache_t* cacheClear() {
if (!cacheFlush()) return 0;
cacheBlockNumber_ = 0XFFFFFFFF;
return &cacheBuffer_;
}
/** Initialize a FAT volume. Try partition one first then try super
* floppy format.
*
* \param[in] dev The Sd2Card where the volume is located.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure. Reasons for
* failure include not finding a valid partition, not finding a valid
* FAT file system or an I/O error.
*/
bool init(Sd2Card* dev) { return init(dev, 1) ? true : init(dev, 0);}
bool init(Sd2Card* dev, uint8_t part);
// inline functions that return volume info
/** \return The volume's cluster size in blocks. */
uint8_t blocksPerCluster() const {return blocksPerCluster_;}
/** \return The number of blocks in one FAT. */
uint32_t blocksPerFat() const {return blocksPerFat_;}
/** \return The total number of clusters in the volume. */
uint32_t clusterCount() const {return clusterCount_;}
/** \return The shift count required to multiply by blocksPerCluster. */
uint8_t clusterSizeShift() const {return clusterSizeShift_;}
/** \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();
/** \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. */
uint32_t rootDirStart() const {return rootDirStart_;}
/** Sd2Card object for this volume
* \return pointer to Sd2Card object.
*/
Sd2Card* sdCard() {return sdCard_;}
/** Debug access to FAT table
*
* \param[in] n cluster number.
* \param[out] v value of entry
* \return true for success or false for failure
*/
bool dbgFat(uint32_t n, uint32_t* v) {return fatGet(n, v);}
//------------------------------------------------------------------------------
private:
// Allow SdBaseFile access to SdVolume private data.
friend class SdBaseFile;
// value for dirty argument in cacheRawBlock to indicate read from cache
static bool const CACHE_FOR_READ = false;
// value for dirty argument in cacheRawBlock to indicate write to cache
static bool const CACHE_FOR_WRITE = true;
#if USE_MULTIPLE_CARDS
cache_t cacheBuffer_; // 512 byte cache for device blocks
uint32_t cacheBlockNumber_; // Logical number of block in the cache
Sd2Card* sdCard_; // Sd2Card object for cache
bool cacheDirty_; // cacheFlush() will write block if true
uint32_t cacheMirrorBlock_; // block number for mirror FAT
#else // USE_MULTIPLE_CARDS
static cache_t cacheBuffer_; // 512 byte cache for device blocks
static uint32_t cacheBlockNumber_; // Logical number of block in the cache
static Sd2Card* sdCard_; // Sd2Card object for cache
static bool cacheDirty_; // cacheFlush() will write block if true
static uint32_t cacheMirrorBlock_; // block number for mirror FAT
#endif // USE_MULTIPLE_CARDS
uint32_t allocSearchStart_; // start cluster for alloc search
uint8_t blocksPerCluster_; // cluster size in blocks
uint32_t blocksPerFat_; // FAT size in blocks
uint32_t clusterCount_; // clusters in one FAT
uint8_t clusterSizeShift_; // shift to convert cluster count to block count
uint32_t dataStartBlock_; // first data block number
uint8_t fatCount_; // number of FATs on volume
uint32_t fatStartBlock_; // start block for first FAT
uint8_t fatType_; // volume type (12, 16, OR 32)
uint16_t rootDirEntryCount_; // number of entries in FAT16 root dir
uint32_t rootDirStart_; // root start block for FAT16, cluster for FAT32
//----------------------------------------------------------------------------
bool allocContiguous(uint32_t count, uint32_t* curCluster);
uint8_t blockOfCluster(uint32_t position) const {
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);
}
cache_t* cache() {return &cacheBuffer_;}
uint32_t cacheBlockNumber() {return cacheBlockNumber_;}
#if USE_MULTIPLE_CARDS
bool cacheFlush();
bool cacheRawBlock(uint32_t blockNumber, bool dirty);
#else // USE_MULTIPLE_CARDS
static bool cacheFlush();
static bool cacheRawBlock(uint32_t blockNumber, bool dirty);
#endif // USE_MULTIPLE_CARDS
// used by SdBaseFile write to assign cache to SD location
void cacheSetBlockNumber(uint32_t blockNumber, bool dirty) {
cacheDirty_ = dirty;
cacheBlockNumber_ = blockNumber;
}
void cacheSetDirty() {cacheDirty_ |= CACHE_FOR_WRITE;}
bool chainSize(uint32_t beginCluster, uint32_t* size);
bool fatGet(uint32_t cluster, uint32_t* value);
bool fatPut(uint32_t cluster, uint32_t value);
bool fatPutEOC(uint32_t cluster) {
return fatPut(cluster, 0x0FFFFFFF);
}
bool freeChain(uint32_t cluster);
bool isEOC(uint32_t cluster) const {
if (FAT12_SUPPORT && fatType_ == 12) return cluster >= FAT12EOC_MIN;
if (fatType_ == 16) return cluster >= FAT16EOC_MIN;
return cluster >= FAT32EOC_MIN;
}
bool readBlock(uint32_t block, uint8_t* dst) {
return sdCard_->readBlock(block, dst);
}
bool writeBlock(uint32_t block, const uint8_t* dst) {
return sdCard_->writeBlock(block, dst);
}
//------------------------------------------------------------------------------
// Deprecated functions - suppress cpplint warnings with NOLINT comment
#if ALLOW_DEPRECATED_FUNCTIONS && DISABLED(DOXYGEN)
public:
/** \deprecated Use: bool SdVolume::init(Sd2Card* dev);
* \param[in] dev The SD card where the volume is located.
* \return true for success or false for failure.
*/
bool init(Sd2Card& dev) {return init(&dev);} // NOLINT
/** \deprecated Use: bool SdVolume::init(Sd2Card* dev, uint8_t vol);
* \param[in] dev The SD card where the volume is located.
* \param[in] part The partition to be used.
* \return true for success or false for failure.
*/
bool init(Sd2Card& dev, uint8_t part) { // NOLINT
return init(&dev, part);
}
#endif // ALLOW_DEPRECATED_FUNCTIONS
};
#endif // SdVolume
#endif
This diff is collapsed.
......@@ -3,82 +3,77 @@
#if ENABLED(SDSUPPORT)
#define MAX_DIR_DEPTH 10 // Maximum folder depth
#define SD_MAX_FOLDER_DEPTH 5 // Maximum folder depth
#define MAX_VFAT_ENTRIES (2)
#define FILENAME_LENGTH 13
/** Total size of the buffer used to store the long filenames */
#define LONG_FILENAME_LENGTH (FILENAME_LENGTH * MAX_VFAT_ENTRIES + 1)
#define SHORT_FILENAME_LENGTH 14
#include "SdFile.h"
extern char tempLongFilename[LONG_FILENAME_LENGTH + 1];
extern char fullName[LONG_FILENAME_LENGTH * SD_MAX_FOLDER_DEPTH + SD_MAX_FOLDER_DEPTH + 1];
enum LsAction { LS_SerialPrint, LS_Count, LS_GetFilename };
#include "SdFat.h"
class CardReader {
public:
SdFat fat;
//Sd2Card card; // ~14 Byte
//SdVolume volume;
//SdFile root;
//SdFile dir[SD_MAX_FOLDER_DEPTH+1];
SdFile file;
CardReader();
void initsd();
void mount();
void unmount();
void ls();
void startPrint();
void pausePrint();
void continuePrint(bool intern = false);
void stopPrint();
void write_command(char* buf);
//files auto[0-9].g on the sd card are performed in a row
//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
void checkautostart(bool x);
void openFile(char* name, bool read, bool replace_current = true, bool lcd_status = true);
void openLogFile(char* name);
void removeFile(char* name);
bool selectFile(const char *filename, bool silent = false);
void printStatus();
void startWrite(char* filename, bool lcd_status = true);
void deleteFile(char* filename);
void finishWrite();
void makeDirectory(char* filename);
void closeFile(bool store_location = false);
void parseKeyLine(char* key, char* value, int &len_k, int &len_v);
void unparseKeyLine(const char* key, char* value);
void release();
void startFileprint();
void pauseSDPrint();
void getStatus();
char *createFilename(char *buffer, const dir_t &p);
void printingHasFinished();
void updateSDFileCount();
void chdir(const char* name);
#if ENABLED(LONG_FILENAME_HOST_SUPPORT)
void printLongPath(char* path);
#endif
void getfilename(uint16_t nr, const char* const match = NULL);
uint16_t getnrfilenames();
void getAbsFilename(char* t);
void ls();
void chdir(const char* relpath);
void updir();
void setroot(bool temporary = false);
void setlast();
void parseKeyLine(char* key, char* value, int &len_k, int &len_v);
void unparseKeyLine(const char* key, char* value);
FORCE_INLINE void setIndex(uint32_t newpos) { sdpos = newpos; file.seekSet(sdpos); }
FORCE_INLINE bool isFileOpen() { return file.isOpen(); }
FORCE_INLINE bool eof() { return sdpos >= filesize; }
FORCE_INLINE void updir() { chdir(".."); }
FORCE_INLINE int16_t get() { sdpos = file.curPosition(); return (int16_t)file.read(); }
FORCE_INLINE void setIndex(long index) { sdpos = index; file.seekSet(index); }
FORCE_INLINE uint8_t percentDone() { return (isFileOpen() && filesize) ? sdpos / ((filesize + 99) / 100) : 0; }
FORCE_INLINE char* getWorkDirName() { workDir.getFilename(filename); return filename; }
//files init.g on the sd card are performed in a row
//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
void checkautostart(bool x);
public:
bool saving, logging, sdprinting, cardOK, filenameIsDir;
char filename[FILENAME_LENGTH], longFilename[LONG_FILENAME_LENGTH];
int autostart_index;
bool saving, sdprinting, cardOK, filenameIsDir;
uint16_t nrFiles; // counter for the files in the current directory and recycled as position counter for getting the nrFiles'th name in the directory.
uint8_t folderLevel;
char cwd[SD_MAX_FOLDER_DEPTH*LONG_FILENAME_LENGTH+2];
private:
SdFile root, *curDir, workDir, lastDir, workDirParents[MAX_DIR_DEPTH];
uint16_t workDirDepth;
SdFile root, *curDir, workDir;
Sd2Card card;
SdVolume volume;
SdFile file;
#define SD_PROCEDURE_DEPTH 1
#define MAXPATHNAMELENGTH (FILENAME_LENGTH*MAX_DIR_DEPTH + MAX_DIR_DEPTH + 1)
uint8_t file_subcall_ctr;
uint32_t filespos[SD_PROCEDURE_DEPTH];
char filenames[SD_PROCEDURE_DEPTH][MAXPATHNAMELENGTH];
uint32_t filesize;
millis_t next_autostart_ms;
uint32_t sdpos;
bool autostart_stilltocheck; //the sd start is delayed, because otherwise the serial cannot answer fast enought to make contact with the hostsoftware.
LsAction lsAction; //stored for recursion.
uint16_t nrFiles; //counter for the files in the current directory and recycled as position counter for getting the nrFiles'th name in the directory.
char* diveDirName;
void lsDive(const char* prepend, SdFile parent, const char* const match = NULL);
};
extern CardReader card;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment