Here is my code. The incoming string is "*CRB12344,Temp25,Humidity55,CC5#"
I am unable to get value of Temp which is 25 and Humidity which is 55 and CC which 5. It only display the value of CR i.e B12344 (in this case). May be issue with strtok function?
String inputString = "";
boolean stringComplete = false, StartCapturing = false;
char inData[50];
char inChar, IncomingWeight;
char IncomingString[50];
const int httpPort = 80;
char *i, *k,*p;
String CardID;
int Temprature, Humidity, TC, CC;
byte SendData = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
serialEvent();
if (stringComplete)
{
inputString.toCharArray(IncomingString, 50);
Serial.println();
Serial.println(IncomingString);
i = strstr(IncomingString, "CR");
{
if (i)
{
p = i+2;
CardID = strtok(p, ",");
Serial.print("Card Number :");
Serial.print(CardID);
Serial.println();
}
}
i = strstr(IncomingString, "Temp");
{
if (i)
{
Temprature = strtoul(i + 4 , NULL, 10);
Serial.print("Temprature :");
Serial.print(Temprature);
Serial.println();
}
}
i = strstr(IncomingString, "Humidity");
{
if (i)
{
Humidity = strtoul(i + 8 , NULL, 10);
Serial.print("Humidity :");
Serial.print(Humidity);
Serial.println();
}
}
i = strstr(IncomingString, "TC");
{
if (i)
{
TC = strtoul(i + 2 , NULL, 10);
Serial.print("Total Count :");
Serial.print(TC);
Serial.println();
}
}
i = strstr(IncomingString, "CC");
{
if (i)
{
CC = strtoul(i + 2 , NULL, 10);
Serial.print("Current Count :");
Serial.print(CC);
Serial.println();
}
}
stringComplete = false;
inputString = "";
delay(10);
}
1 Answer 1
strtok()
is a destructive function. It replaces the token with an end-of-string marker (0円
). Thus once used the original string is irevocably lost.
Your first use of strtok()
changes the string from:
*CRB12344,Temp25,Humidity55,CC5#0円
to:
*CRB123440円Temp25,Humidity55,CC5#0円
Thus any future references to InputString
only see up to the end-of-string marker:
*CRB123440円
Instead you should use strtok()
in a while
loop to slice the string into tokens and examine what the token is:
char *tok = strtok(IncomingString, ",");
while (tok) {
if (strncmp(tok, "*CR", 3) == 0) { // tok is *CRB1234
// ... whatever ...
} else if (strncmp(tok, "Temp", 4) == 0) { // tok is Temp25
// ... whatever ...
} else if (strncmp(tok, "Humidity", 8) == 0) { // tok is Humidity55
// ... whatever ...
} else if (strncmp(tok, "CC", 2) == 0) { // tok is CC5#
// ... whatever ...
}
tok = strtok(NULL, ","); // Note: NULL, not IncomingString
}
-
Didn't know this. I understand the mistake now.MICRO– MICRO2016年11月12日 11:57:37 +00:00Commented Nov 12, 2016 at 11:57