Skip to content
Snippets Groups Projects
Commit 860f544c authored by nrs1g15's avatar nrs1g15
Browse files

Added state machine and retries every 1s if begin fails

parent 5ad65415
No related branches found
No related tags found
No related merge requests found
......@@ -6,6 +6,13 @@
#include "buffer.h"
#include "SdFat.h"
enum SdState {
stopped = 0,
writing,
};
SdState sdState = stopped;
SdFat sd;
SdFile file;
......@@ -17,30 +24,46 @@ CirBuffer sdCirBuffer;
uint8_t sdBegin()
{
if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(10))) {
sdState = stopped;
return 0;
}
if (sd.exists(SD_FILE_NAME)) {
if (!file.open(SD_FILE_NAME, O_WRITE | O_APPEND)) {
sdState = stopped;
return 0;
}
}
else {
if (!file.open(SD_FILE_NAME, O_WRITE | O_CREAT)) {
sdState = stopped;
return 0;
}
}
if (!cirBufferBegin(&sdCirBuffer, sdBuffer, SD_BUFFER_LEN, sizeof(uint8_t))) {
sdState = stopped;
return 0;
}
sdState = writing;
return 1;
}
void sdWrite(void *data, uint8_t len)
{
cirBufferWriteBytes(&sdCirBuffer, data, len);
if (sdState == writing) {
cirBufferWriteBytes(&sdCirBuffer, data, len);
}
}
void sdProcess()
......@@ -48,11 +71,24 @@ void sdProcess()
static uint8_t sdPayload[SD_WRITE_LEN];
static uint8_t sdWritesCntBeforeFlush = 0;
if (cirBufferAvailable(&sdCirBuffer) >= SD_WRITE_LEN) {
if (sdState != writing) {
uint32_t currentMs = millis();
static uint32_t lastTryMs = 0;
if ((currentMs - lastTryMs) >= SD_START_TRY_AGAIN_MS) {
sdBegin();
lastTryMs = millis();
}
}
else if (cirBufferAvailable(&sdCirBuffer) >= SD_WRITE_LEN) {
cirBufferReadBytes(&sdCirBuffer, sdPayload, SD_WRITE_LEN);
file.write(sdPayload, SD_WRITE_LEN);
if (!file.write(sdPayload, SD_WRITE_LEN)) {
sdState = stopped;
}
sdWritesCntBeforeFlush++;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment