0

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");
    }
  }
}
1

The millis() function is based on a counter which is incremented by the Timer 0 overflow interrupt. Since you reconfigured that timer to never overflow, that counter is not incremented anymore.

If you want to configure an Arduino timer for your own purposes, you have to either:

  • use any timer other than Timer 0, or
  • loose the Arduino standard timekeeping functions: millis(), micros() and delay().

I would favor the first option, especially on the Mega which has quite a few spare timers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.