Adafruit Data Logger Shield + Triple-axis Magnetometer

Hi, I’m trying to sample a magnetic field and write the data to an SD card. The datasheet for the sensor advertises a 155 Hz sample rate which is fast enough for my application, however when I look at the recorded data, it barely hits 30 Hz (i.e. ~30 ms between samples). It’s running on an Arduino Uno SMD
My hypothesis is that the SD card write speed is the bottleneck, but I couldn’t find any info on what it is. Furthermore, the card itself claims 300 Mb/s.
The only solution I can think of is double-buffering the data from the sensor, which I think would require rewriting the I2C ISR, and I am not even sure that it would solve the problem.

Can anyone give me an idiot check on this? Have I missed something obvious?

Most of the code is copied direct from the examples. The main loop is:

void loop() {
  DateTime now = rtc.now();
  String dataString = "";
  sensors_event_t event;

  lis3mdl.getEvent(&event);
  
  dataString += String(event.magnetic.x) + "," + String(event.magnetic.y) + "," + String(event.magnetic.z) + "," + now.unixtime() + "," + millis();
  
  File dataFile = SD.open("datalog.csv", FILE_WRITE);
  
  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    Serial.println(dataString);
    Serial.flush();
  }
  
  // if the file isn't open, pop up an error:
  else {
    Serial.print("error opening ");
    Serial.println(filename);
  }
}

The sensor is Adafruit Triple-axis Magnetometer - LIS3MDL [STEMMA QT / Qwiic] : ID 4479 : $5.95 : Adafruit Industries, Unique & fun DIY electronics and kits

mag_to_sd.ino (2.89 KB)

My hypothesis is that the SD card write speed is the bottleneck, but I couldn't find any info on what it is. Furthermore, the card itself claims 300 Mb/s.

Your hypothesis is probably correct. The maximum storage speed isn't relevant here, that's for much faster devices.
The main problem is in your code. For every line you write you open the file, write the line and close the file again. The SD card controller has to do much work to support these operations. It has to go the main directory, look for the file entry, then read the last block of the file, erase that block, then append the new line to the content and write the block again, in some cases even two blocks (in case you crossed the block limit) and update the table of used blocks.

So store as much content in RAM as possible an write it out in bigger chunks.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.