B4R Question SOLVED Sd.position seems not to work.

tigrot

Well-Known Member
Licensed User
Longtime User
Hi everybody,
I have an app updating a small random access file. It worked for months, but after I compiled again with last version of B4R and updated Arduino package, it appends the record instead of updating it.
Position value is correct and file is opened readwrite.
Thanks in Advance for hints.
Mauro
 
Last edited:

tigrot

Well-Known Member
Licensed User
Longtime User
Here it is, along with resulting file. Seems that reading works with position while write doesn't.
It's a mega 2560 arduino.
B4R vesion is 3.90
rSD is 1.21
SD arduino 1.2.4
 

Attachments

  • testupdate.zip
    1.3 KB · Views: 53
  • TEST.TXT
    360 bytes · Views: 52
Last edited:
Upvote 0

tigrot

Well-Known Member
Licensed User
Longtime User
C:
#include <SPI.h>
#include <SD.h>

const int chipSelect = 10;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }


  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");
}

void loop() {
  // make a string for assembling the data to log:
  String dataString = "";

  // read three sensors and append to the string:
  for (int analogPin = 0; analogPin < 3; analogPin++) {
    int sensor = analogRead(analogPin);
    dataString += String(sensor);
    if (analogPin < 2) {
      dataString += ",";
    }
  }

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.seek(0);
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.println(dataString);
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }
}
I have tested this code too. I took from samples and modified to implement a seek function.
No way seek doesn't work, the issue is in Arduino's libraries, or at least FILE_WRITE implies O_APPEND?
I will investigate...
 
Upvote 0

tigrot

Well-Known Member
Licensed User
Longtime User
Solved. Version of Arduino's SD library 1.2.4 has a definition for FILE_WRITE which includes O_APPEND.
This is the involved sd.h correction, with old line as well. Tested and working...

C:
#define FILE_READ O_READ
//#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)
#define FILE_WRITE (O_READ | O_WRITE | O_CREAT)

I cannot believe that since 2019 nobody had the same issue!
Happy evening
Mauro
 
Upvote 0
Top