I've been a little away from programming and I'm actually doing one project in my university which needed me to learn arduino. I've been doing ok, but it seems I have this problem with sending a message. I've been searching but I couldn't find the right way do add a variable into a string (or array of characters). The point of this function is to create a message in which there is the name of a certain problem detected and the value encountered. I'm not sure how to add strings in arduino so I made it this way, however it seems it does not accept it and I don't know how to put the value of 'value' inside the string.
The code I have is the following:
char *createMessage(byte ID, float value){
String messageF = "Automatic Message from Cryo Lab: There seems to be a problem with ";
if (ID == 1){
messageF = messageF + "Electricity ";
}
Serial.println(messageF);
messageF = messageF + "which was found with the value of ";
Serial.println(messageF);
messageF = messageF + value;
Serial.println(messageF);
char message[200];
messageF.toCharArray(message, 200);
return message;
}
Never return a reference to an automatic variable.
Pass the char buffer into the function, if necessary.
"sprintf" may be a lot easier to use than the String class
Ok thank you! It seems to be working! I used sprintf() and for floats I used one little algorithm. It stayed like this and it gives me exactly what I want.
char *createMessage(byte ID, float value){
char message[200] = "Automatic Message from Cryo Lab: There seems to be a problem with";
if (ID == 1){
sprintf(message, "%s Electricity", message);
}
int d1 = value;
float f2 = value - d1;
int d2 = trunc(f2 * 100);
float f3 = f2 * 100 - d2;
sprintf(message, "%s with the value of %d.%02d\n", message, d1, d2);
Serial.println(message);
return message;
}
You're returning a pointer to an entity on the stack, mere nanoseconds before that entity goes out of scope.
Either make "message" static, use a global, or pass the pointer to the buffer into the function