In a sketch I measure temperature and convert it to degrees celsius, store that in a float.
I want to write that in a string and once every second a new measurement and a new string written over de Serial line.
However, after two or three repeats, the programm currently stops and I cannot figure out what is going wrong, except that I localized it to the string that contains the converted float value.
This is what I have now:
#include <stdlib.h>
int temp_val;
float temperature;
char temperatureText[ ] = "";
String stringMessage;
.
.
void setup() {
stringLogMessage = String();
}
.
.
void loop() {
.
.
temp_val = analogRead(tempSensor);
temperature = getVoltage(tempSensor); // get voltage reading from the thermistor
temperature = (temperature - .5) * 100; // converting from 10 mv per degree with 500 mv offset to degrees
.
.
dtostrf(temperature,5,2,temperatureText);
.
.
stringMessage = "#Msg,";
stringMessage += temperatureText;
stringMessage += "$";
Serial.println(stringLogMessage);
delay(10000);
}
There is (obviously) more in the code, but I stripped it for clarity's sake. The getVoltage function converts the analog value to a voltage reading.
As I said, there is no error message, but the sketch just stops working after 2 repeats. I think it has something to do with the fact that I am not "resetting" the character array or something, but I can't quite get it figured out.
Anybody any ideas? I am uploading to a Duemilanove/328 with the Arduino 0021 IDE.
I do not completely understand why this would solve it. The variable can now contain more data, but what happened before that caused it to lock up that is not happening now?
The dtostrf() function converts the double value passed in val into an ASCII representationthat will be stored under s. The caller is responsible for providing sufficient storage in s.
You shouls allocate space to store the string. In your code there no space allocated as the string is empty
I did read that, so hence I figured that the data could be anywhere between 4 (e.g. 1.00) and 6 (e.g. -15.00) and did not specify a specific size, so anything would fit. I guess that is not a correct assumption then?
The short answer is ... The Arduino programming language is not Visual Basic. Strings are a bit more difficult to manage.
The long answer...
This...
char temperatureText[ ] = "";
...sets aside storage for an array of one element and initializes the one element to a null. The array is to short to safely store anything of use.
This...
char temperatureText[10];
...sets aside storage for an array of ten elements. You can safely store a "string" of 9 ore fewer characters in this array.