I'm trying to do a data logger. Writes into SD card has to stop when millis()=1000. Maybe I have a problem between millis() and my interrupt, because datalogger doesn't stop after millis()=1000. I'm working with Arduino Mega.
#include <SPI.h>
#include <SD.h>
volatile unsigned int cuenta = 0;
unsigned char contador = 0x00;
const int chipSelect = 53;
long currentMillis = 0;
long previousMillis = 0;
long interval = 1000;
void setup() {
DDRA = B11111111;
cli();//stop interrupts
TCCR0A = 0;// set entire TCCR2A register to 0
TCCR0B = 0;// same for TCCR2B
TCNT0 = 0;//initialize counter value to 0
// set compare match register for 10000khz increments
OCR0A = 25;// = (16*10^6) / (1000*64) - 1 (must be <256)
// turn on CTC mode
TCCR0A |= (1 << WGM01);
// Set CS01 and CS00 bits for 64 prescaler
TCCR0B |= (1 << CS01) | (1 << CS00);
// enable timer compare interrupt
TIMSK0 |= (1 << OCIE0A);
sei();//allow interrupts
//periodo de cada pulso 255ms del tren total de pulsos aproximadamnte 255ms
Serial.begin(9600);
while (!Serial) {
;
}
Serial.print("Initializing SD card...");
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
while (1);
}
Serial.println("card initialized.");
}
ISR(TIMER0_COMPA_vect) {
cuenta++;
if (cuenta > 9) {
PORTA = ++contador;
cuenta = 0;
} else {
PORTA = 0X00;
}
}
void loop() {
currentMillis = millis();
if (currentMillis - previousMillis <= interval)
{
String dataString = "";
for (int analogPin = 0; analogPin < 1; analogPin++) {
int sensor = analogRead(analogPin);
dataString = String(sensor);
if (analogPin = 1) {
dataString += ",";
}
}
File dataFile = SD.open("datalog2.txt", FILE_WRITE);
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
else {
Serial.println("error opening datalog.txt");
}
}
}