Trouble reading from SD card on MKR Zero

My application is a fuel gage driver for a car that has been converted to electric drive. The code snippet posted here is attempting to read a value from an SD card at power up, then use that value to continue keeping track of the traction pack's SOC / amp-hours. The problem is that what is read back from the SD makes no sense. I'm thinking that I need some sort of data type conversion to fix this. The text file on the SD contains the vale 260.000. What the serial monitor is returning is 10.00. Any help would be appreciated!

#include <SPI.h>
#include <SD.h>
const int chipSelect = SDCARD_SS_PIN;
File myFile;
String oldAmpHours;
float ampHours;
String myString;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.println("Initializing SD card...");
  SD.begin(chipSelect);
  if (!SD.begin(chipSelect)) {
    Serial.println("SD card failed to initialize.");
    while (1)
      ;
  }
  Serial.println("SD card initialized.");
  myFile = SD.open("OldAh.txt");
  if (myFile) {
    while (myFile.available()) {
      ampHours = (myFile.read());
    }
    myFile.close();
  }
  Serial.print(ampHours);
}

void loop() {
  // put your main code here, to run repeatedly:
}
#include <SPI.h>
#include <SD.h>
const int chipSelect = SDCARD_SS_PIN;
File myFile;
String oldAmpHours;
float ampHours;
String myString;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.println("Initializing SD card...");
  SD.begin(chipSelect);
  if (!SD.begin(chipSelect)) {
    Serial.println("SD card failed to initialize.");
    while (1)
      ;
  }
  Serial.println("SD card initialized.");
  myFile = SD.open("OldAh.txt");
  if (myFile) {
    while (myFile.available()) {
      ampHours = (myFile.parseFloat());
    Serial.print(ampHours);
  }
    myFile.close();
  }
}

void loop() {
  // put your main code here, to run repeatedly:
}
1 Like

myFile.read() returns one byte.

It's important that we know how you wrote the value to the SD card; it probably was done using print in which case it's text and @kolaha's solution should do the trick. If you wrote it as binary, the story will be different.

1 Like

Sterretje,
Thanks for the reply! Here is the code snippet that writes the float value to the SD card.

void storeLastAh() {
  SD.begin(chipselect);  // SDCARD_SS_PIN
  myFile = SD.open("OldAh.txt", FILE_WRITE);
  myFile.println(ampHours, 3);
  myFile.close();
}

Kolaha,
Thanks for your quick response. I tried your solution. Strangely it worked only once. I am again getting 0.00 as the serial monitor response. I have not altered the value stored on the SD card.
UPDATE: I incorporated your fix in the full version of my program and it works every time! Thank you for the elegant solution!
Martin

1 Like