Accelerometer data out of sync with RTC

Hi,

I am trying to get 20 accelerometer readings per second, with timestamp from RTC with first reading, and small sleep between readings. Then save it to an SD card.

This is my loop

void loop()
{
  tmElements_t tm;

  if (file) 
  {
    for (uint16_t i = 0; i < 1800; i++) {

      RTC.readTime();
      print2digits(RTC.getHours());
      file.print(':');
      print2digits(RTC.getMinutes());
      file.print(':');
      print2digits(RTC.getSeconds());

      for (i = 0; i < 20; i++){
        accel.read();

        file.print(','); 
        printCalculatedAccels();
        printOrientation();
        file.print (millis());
        file.println(); // Print new line every time.
      
        LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_ON); 
      }
    }
    file.flush();
  }
}

I get 20 readings between the timestamp, but sometimes two adjacent time stamps are the same. I know this is happening because my loop is happening faster than every tick of the RTC, and it is catching up.

Is there any way of syncing this?

Cheers,

Damien.

Writing to SD card is time-consuming. You'll want to see what it is capable of.

Hi,

If I just let the loop run with no delay or 20 count I get an awful lot more readings to the SD. I was something like 60 to 80 if I can remember.

I only want 20, but to be within the timestamp of one second.

Cheers,

Damien.

Ok this is the code I came up with. I know its probably not the best, but it seems to work.

void loop()
{
  tmElements_t tm;
  if (file) 
  {
     RTC.readTime();
     epochTime = RTC.date_to_epoch_seconds();
     if (epochTime > previousepochTime){
       previousepochTime = epochTime;
       print2digits(RTC.getHours());
       file.print(':');
       print2digits(RTC.getMinutes());
       file.print(':');
       print2digits(RTC.getSeconds());

       for (int i = 0; i < 20; i++){
         accel.read();

         file.print(','); 
         printCalculatedAccels();
         printOrientation();
         file.println(); // Print new line every time.
      
         LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_ON); 
        }
      }
      else{
         LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_ON);
      }
    }
  if ((epochTime - syncTime) < SYNC_INTERVAL) return;
  syncTime = epochTime;
  file.flush();
}

The LowPower.powerDown code seems to shut down the millis timer. As a test I displayed millis along with RTC and accelerometer data. Over 8 seconds on the RTC elapsed before millis counted to 1000. If I could get millis working I could get the 20 data points more evenly spaced over the second.

What I did learn from displaying millis was that each accelerometer read took around 10ms max, and RTC plus accelerometer reading took 20ms max. I called flush to sd every 30 mins, but seen no change in these speeds.

Damien.