Hi! Can you please help me with my code? I attach a copy below. In this code I have included string , I want to extract the string after each comma and want to convert the floating point numbers into degree
String message= "$PTNTHPR,74.5,N,-2.9,N,3.3,N,*24"; // an example string
int commaPosition; // the position of the next comma in the string
void setup()
{
Serial.begin(9600);
}
void loop()
{
//Serial.println("Message: ");
Serial.println(message); // show the source string
do
{
commaPosition = message.indexOf(',');
if(commaPosition != -1)
{
Serial.println( message.substring(0,commaPosition));
message = message.substring(commaPosition+1, message.length());
}
else
{ // here after the last comma is found
if(message.length() > 0)
Serial.println(message); // if there is text after the last comma print it
break;
}
}
while(commaPosition >=0);
delay(5000);
}
/code]
Does it have to be a String (capital S. An object created using the String library that many believe causes memory fragmentation problems) or could it be a string (lowercase s. A lean, less memory hungry array of chars) ?
Strings cause memory problems and program crashes on 8-bit Arduinos, so it is better to use C-strings (zero terminated character arrays). Use the functions in <string.h> and others like atoi(), atof(), etc. to parse them.
Example:
void setup() {
Serial.begin(9600);
char message[] = "$PTNTHPR,74.5,N,-2.9,N,3.3,N,*24"; // an example string
char* next; //pointer to substring (token)
float value;
next = strtok(message, ","); //get first substring (token)
Serial.println(next); // and print "$PTNTHPR"
Serial.println(next = strtok(NULL, ",")); //get and print the string "75.4"
value = atof(next); //convert string to float
Serial.println(value, 4); // and print
}
void loop() {}
If you insist on using Strings, you will need to extract the substring()s that are of interest, based on the indexOf() the commas before and after the values, and then use the toFloat() method.