SD card read/write with Arduino

Nachtwind, and those who want it, my PHP for converting to CSV:

<?php
$packet=array(3,2,2); //the number of bytes to read for each value of the 'packet' of data to be converted to a csv line.

$f=fopen('data.bin','r');
while(!feof($f)){ //repeat until end of file
      $csv_line='';
      foreach($packet AS $bytes){ // loop through the packet and generate the CSV line
            if($csv_line) $csv_line.=","; //append a comma if needed
            $csv_line.=getVal($f,$bytes); //append the next value
      }
      echo $csv_line."\n"; //echo the line
}

//reads $bytes bytes from file $f and convert them to a value
//does this by reading each bite as a character, and converting it to its ASCII value
function getVal($f,$bytes){
      $val=0;
      for($i=0;$i<$bytes;$i++){ // loop for however many bytes we require
            $b=ord(fgetc($f)); // read a character and convert it to it's ASCII byte value with ord()
            $val=($val<<8)+$b; // shift the current value left eight bits (8 bits == 1 byte) and then add the byte we just read to the value
      }
      return $val;
}
?>

You must adjust $packet to reflect the number of bytes used for each value. (This is currently configured to read the data generated from my example in SDWriter)

The magic of joining the bytes into larger values happens on this line: $val=($val<<8)+$b
this shifting of bits is how we join two bytes back into an int
this could also be achieved by multiplying by 256: $val=($val*256)+$b;

val byte2 byte1 example values and how they would be stored in multiople bytes
255 255 as we probably know, 255 is the most one byte to contain
256 1 0 to store 256 or more we need another byte to store multiples of 256. (1*256) + 0 =256
261 1 5 (1*256) + 5 =261
65535 255 255 (255*256) + 255 = 65535 //max value of an int (2 bytes)

you could now add a third byte to store multiples of 65536
this can be done for as many bytes as you need to contain your range of numbers, with only a few more bytes you can store over billions!

sirmorris, I find the functionality of uFat is excellent and the trade-offs are not a problem, especially as it seems we are all really only wanting to log data, I can't really see the need for more functionality. If I wanted to do much more I think I would probably want a full FAT filesystem. But only the future can tell :wink:

Also your method of printing to the buffer looks really cool, I haven't got time to study it greatly now, but it looks like it's exactly what JB needs and wouldn't require my suggested writeString function. In fact I guess I could extend my SDWriter in the same way to add the print/println functionality to it :smiley:

Thanks!