Created Tue, 01 Jan 2013 06:28:25 +0000 by spencoid
Tue, 01 Jan 2013 06:28:25 +0000
i can't get the following (also attached as a text file) simple test to work. i am trying to convert a long integer into bytes, write them to the SD card and read them back and convert back to a long integer. the conversion seems to work because as long as i just convert and do not write to the card it works. i am not stuck on converting to bytes and back but thought this was the only way to write a 32 bit integer to the SD card. i am open to any other method that achieves the same thing.
#include <SD.h> // was suggested that these need to be declared first
#include <SPI.h> // this was recommended, not sure why
File SDfile;
unsigned char bytes[sizeof(long)];
void setup() {
Serial.begin(115200);
pinMode(9, INPUT);
pinMode(4, OUTPUT);
digitalWrite(4, HIGH); // chip select on SD card
digitalWrite(9, HIGH); // turn on pullup resistors
pinMode(8, INPUT);
digitalWrite(8, HIGH); // turn on pullup resistors
pinMode(35, INPUT);
digitalWrite(35, HIGH); // turn on pullup resistors
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
else{
Serial.println("initialization success!");
}
long in_value = 20000;
long out_value = 0;
unsigned char read_byte;
SDfile.close(); //
SDfile = SD.open("test.txt", FILE_WRITE);
if (SDfile) {
Serial.print("opening SD for writing ");
Serial.println("test.txt");
}
else{
Serial.println("SD card failure");
}
for (int i = 0; i < sizeof(long); i++){
bytes[i] = in_value & 0xFF;
in_value >>= 8;
SDfile.write(bytes[i]);
}
// SDfile.write(bytes, sizeof(long)); // tried using this instead of writing individual bytes in above for loop
SDfile.close();
SDfile = SD.open("test.txt");
// for (int i = 0; i < sizeof(long); i++){ // this does not work if the same bytes are written to and then read from the SD card
// read_byte = SDfile.read(); // must have something to do with bit or byte order that i have not been able to figure out
// out_value |= (read_byte << (i * 8));
// }
for (int i = 0; i < sizeof(long); i++){ // this works fine so it shows that the conversion from integer to bytes and back is correct
out_value |= (bytes[i] << (i * 8));
}
Serial.print("got value ");
Serial.println(out_value);
}
void loop() {
}
Tue, 01 Jan 2013 08:20:03 +0000
i think i figured this out. i think it was just that i was not removing the old test file. i am used to perl in which files are overwritten unless opened for "append" so i didn't realize that i was not writing a new file by opening for writing.