Hello all,
Storing data on SD takes more than 10 ms, so it is impossible to store data at 100 Hz sample rate in between subsequent samples. The supposed solutions I found on the internet were getting complicated very fast. I wanted something that was both beginner friendly and working at higher sample rates.
The code below is what I came up with. I used a Pro Micro, but I think it will run fine on an Uno or Nano as well. It is currently storing data from a counter at 1000 Hz without missing any 'measurements'.
I hereby challenge all experienced programmers (which I am not) to improve on this code by either making it more beginner friendly or by make it performing better without getting more complicated.
/**************************************************************************
Problem fixed by this sketch:
Writing data to SD takes more than 10 ms.
At 100 Hz sample rate it is impossible to write data to SD between subsequent samples.
Solution:
Timer interrupt will sample data into a buffer.
When the first or second half of the buffer has just been filled, it will toggle the main loop to store that half on SD.
**************************************************************************/
#include <TimerOne.h>
#include <SPI.h>
#include <SdFat.h>
SdFat SD;
#define SD_CS A1
File dataFile;
int buf[200];
boolean Aready=false;
boolean Bready=false;
int aap=0;
int counter=0;
void setup(void) {
if (!SD.begin(SD_CS)) {
while (1);
}
dataFile = SD.open("test.csv", O_WRITE | O_CREAT );
for (int i = 0; i<200; i++)
buf[i] = 0;
Timer1.initialize(1000); // 1000 Hz sampling rate
Timer1.attachInterrupt( ISRtimer1 );
}
void loop() {
WriteSD();
}
void WriteSD() {
if(Aready){
Aready=false;
for (int i=0;i<100;i++){
dataFile.print(String(buf[i])+",");
}
dataFile.flush();
}
if(Bready){
Bready=false;
for (int i=100;i<200;i++){
dataFile.print(String(buf[i])+",");
}
dataFile.flush();
}
}
void ISRtimer1()
{
aap++;
buf[counter]=aap; // aap could be an AnalogRead
counter++;
if(counter==100) Aready=true;
if(counter==200) {
counter=0;
Bready=true;
}
}