Go Down

Topic: Read/Write short to SD card (Read 710 times) previous topic - next topic

ElJosho

Hey all,

This seems like a very simple question, however I am having some trouble with it.

I wish to write a 2 byte value (unsigned short) to an SD card, and then read that same 2 byte value later on.

Saving and reading to the SD card all works fine, however I can only find how to read and write 1 byte at a time, using the basic functions such as file.read(), file.write().

Any help would be appreciated!

majenko

So, read one byte twice, and combine them?

ElJosho

Sorry I should have been more specific, I do understand how to read 2 bytes and join them together, however I can only seem to write into the file as ascii.

For example, if I wanted to write in the file the number 425, file.print() writes it in as the seperate digits '4', '2', and '5'.

Is there any way to write into the file as a complete number? Or prehaps combine the seperate digits '4', '2' and '5' into a complete number again?

Cheers!

PaulS

Quote
For example, if I wanted to write in the file the number 425, file.print() writes it in as the seperate digits '4', '2', and '5'.

Sure, that's what print() does.

Quote
Is there any way to write into the file as a complete number?

Sure, that's what write() does.

Quote
Or prehaps combine the seperate digits '4', '2' and '5' into a complete number again?

Sure, that's what atoi() does, once you've stored the characters in a NULL terminated array of chars.

majenko

You could either store the value as ASCII on the SD card and convert it back using atoi(), or you can use the .write() function to write individual bytes.

You can separate bytes out, and recombine them, by using simple boolean algebra - AND (&), OR (|), left shift (<<) and right shift (>>).

For example, to turn a 16-bit integer into two 8-bit bytes:

Code: [Select]

int in = 3769;
byte b1,b2;

b1 = in >> 8;
b2 = in & 8;


And to re-combine them again:

Code: [Select]

in = (b1 << 8) | b2;

ElJosho

Thanks both for your replies,

I was having trouble as atoi() would write as an integer, and I wanted a short, and file.write() would only let me write 1 byte of a 2 byte number.

But I will use the method of splitting the number into seperate bytes before writing it, thanks!

majenko

The Arduino uses 16-bit integers.  That's the same as a short.

ElJosho

Well damn. I have no idea how I didn't already know that, too used to C I guess!

Thanks a bunch, thats some important info!

majenko

The Arduino is programmed in C.

Go Up