I am doing a project for college and using arduino uno. I am required to record accelerometer data (using ADXL335) with time stamps (using millis function) and save it to SD card. The interval that I must use is 10ms but when I run my code the output is wildly different with bigger intervals on the serial monitor (would start at zero then go to 43 or 51, and so on). I don’t know if I have just made a mess or what else I can do. I read multiple posts on this forum and others but couldn’t find an answer so any help would be appreciated. Also, I did read that millis drifts since it is not exactly 1ms but 1.024ms, is that why I am having issues, and how can i fix it?
//including libraries
#include <SD.h>
#include <SPI.h>
File myFile;
const int pinCS = 10; //chip select
const int xpin = A3; // x-axis of the accelerometer
const int ypin = A2; // y-axis
const int zpin = A1; // z-axis
unsigned long eventInterval = 10;
unsigned long previousTime = 0;
void setup() {
Serial.begin(9600);
pinMode (pinCS, OUTPUT);
//SD card initialization - prints a failed statement if the card is not working
if (SD.begin())
{
} else
{
Serial.println("SD card initialization failed");
return;
}
// create/open file
myFile = SD.open("walking.csv", FILE_WRITE);
//if file opened ok, write to it:
if (myFile) {
myFile.println("TIME, X, Y, Z");
myFile.close(); //close the file
Serial.println("TIME, X, Y, Z");
}
// if the file didn't open, print error:
else {
Serial.println("error opening test.txt");
}
}
void loop() {
unsigned long currentTime = millis(); //setting current time to the millis () function counter
if (currentTime - previousTime >= eventInterval) {
myFile = SD.open("walking.csv", FILE_WRITE);
myFile.print(previousTime);
myFile.print(",");
myFile.print(analogRead(xpin));
myFile.print(",");
myFile.print(analogRead(ypin));
myFile.print(",");
myFile.println(analogRead(zpin));
Serial.print(previousTime);
Serial.print(",");
Serial.print(analogRead(xpin));
Serial.print(",");
Serial.print(analogRead(ypin));
Serial.print(",");
Serial.println(analogRead(zpin));
previousTime = currentTime; //setting previous time to current time once interval is reached
}
myFile.close(); //close the file
}