Go Down

Topic: Problem saving data to SD (Read 4326 times) previous topic - next topic


The format part of the sprintf argument list is the part between the "". If you want the message array to contain a CR\LF, add \n at the end:

Code: [Select]
sprintf(message,"%ld,%ld\n", temp, Vcc);

If you want to write more data into message, message must be longer.

As for the format "magic", see this:
The art of getting good answers lies in asking good questions.


Thanks so much PaulS,

It works perfectly now.

The link is great and looks very useful to learn more about C.

Now i post here the final code as i have it working. May be it could be useful to somebody else in the future.

Code: [Select]
#include <FileLogger.h>
#define MEM_PW 8

long readTemp() {
 long result;
 // Read temperature sensor against 1.1V reference
 ADMUX = _BV(REFS1) | _BV(REFS0) | _BV(MUX3);
 delay(20); // Wait for Vref to settle
 ADCSRA |= _BV(ADSC); // Convert
 while (bit_is_set(ADCSRA,ADSC));
 result = ADCL;
 result |= ADCH<<8;
 result = (result - 125) * 1075;
 return result;

long readVcc() {
 long result;
 // Read 1.1V reference against AVcc
 ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
 delay(2); // Wait for Vref to settle
 ADCSRA |= _BV(ADSC); // Convert
 while (bit_is_set(ADCSRA,ADSC));
 result = ADCL;
 result |= ADCH<<8;
 result = 1126400L / result; // Back-calculate AVcc in mV
 return result;

void setup() {
 pinMode(MEM_PW, OUTPUT);
 digitalWrite(MEM_PW, HIGH);
 Serial.println("Arduino inner temperature and inner voltage");

void loop() {
 // To read the inner temperature and voltage
 long temp=readTemp();
 long Vcc=readVcc();
 // To prepare and to save the data tostore in the microSD
 char message[20];
 sprintf(message,"%ld, %ld\n", temp, Vcc);
 unsigned long length = strlen(message);
 FileLogger::append("data.log", (byte*)message, length);
 // Now i show the result in serial
 Serial.print(temp, DEC); // show the inner temperature of arduino
 Serial.print(" x10^-4 degC   ");
 Serial.print(Vcc, DEC); // show the voltage
 Serial.println("  mVolts");
 // Wait 1 second until to take a new measurement

You could apply it to any other measurement acquired by temperature sensors, accelerometers, or whatever.... just only pay attention to the expression to be save, and the length of the message to be stored in the SD, as you could read in the previous post and the great explanations by PaulS.

Thanks PaulS. Enjoy everyone!

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131