Go Down

Topic: Passing char* to Serial.println (Read 283 times) previous topic - next topic

mad93

Hi, i'm trying to do my first project with arduino. So far i've done an accelerometer logger with an interruption to put the arduino to sleep. Now i want to make it use a new file to log the data every time the interruption is called so I've a counter to know the current file number and a function to return the filename where to store the data on the SD.

So I've this function to generate the string:

Code: [Select]
char* createFilename(int number)
{
   // Per tracejar l'exponent
   int counter = 0;
   
   // Per guardar el resultant de la divisiĆ³
   int rest;
   
   // Per emmagatzemar els diversos caracters a convertir
   char values[100] = "";
   
   // Per reordenr la cadena a tornar
   char output[100] = "";
   
   // Per emmagatzemar el resultat de la divisiĆ³
   int result = number;
   
   while(result>9)
   {
     rest = result%10;
     result = result/10;
     values[counter] = '0'+rest;
     counter++;
   }
   values[counter] = '0'+result;

   int j = counter;

   for(int i=0;i<=counter;i++)
   {
     output[i] = values[j]; 
     j--;
   }
   output[counter+1]='.';
   output[counter+2]='C';
   output[counter+3]='S';
   output[counter+4]='V';
   output[counter+5]='\0';
   return output;
}


I've a do a Serial.println(output) here the output is the desired one, for example: 1.CSV

But when I call this function from the loop I get random characters instead the desired output.

Code: [Select]
Serial.println(createFilename(availableFile));

I suspect that I'm doing something wrong with the pointers.

Thank you.

spatula

Hi,
your output is declared inside createFilename(), so when the function returns you cannot rely on it (it goes out of scope). The memory taken by your array within the function can be reused by the system at any time, so the pointer returned by createFilename() may point to totally different data. One of the things you can do is pass the char array as an argument to the function, as in:

Code: [Select]

char* createFilename(char* prefix, int number) { ... }


You may also consider sprintf().

mad93

Thank you spatula! Worked like a charm ;)

Trying to remember C, used long time ago..., the variable would have been preserved in memory if I used malloc to allocate the memory?

WizenedEE


Thank you spatula! Worked like a charm ;)

Trying to remember C, used long time ago..., the variable would have been preserved in memory if I used malloc to allocate the memory?


Yes, if you free it after you print it.

However, using malloc is often a bad idea and certainly something to avoid on a microcontroller, especially if you are allocating 5% of the memory at a time (100 bytes out of a possible 2048)

mad93

Thank you. You're right, I only used C on Computers where memory is cheap  ;)

Go Up