Reputation: 16912
I'm trying to parse the following output taken from a GSM module in Arduino, to get the Voltage (3.900V
) part only. However, I can't get it to work.
"
+CBC: 0,66,3.900V
OK
"
I have tried the following code, but it fails and even crashes.
float getVoltage() {
if (atCmd("AT+CBC\r") == 1) {
char *p = strchr(buffer, ',');
if (p) {
p += 3; // get voltage
int vo = atof(p) ;
p = strchr(p, '.');
if (p) vo += *(p + 1) - '0'; // ??
return vo;
}
}
return 0;
}
How can this be done in a better or more transparent way?
Upvotes: 0
Views: 1328
Reputation: 3736
You can do it using the C function strtok
to tokenize the buffer
void setup() {
Serial.begin(115200);
char buffer[20] = "+CBC: 1,66,3.900V";
const char* delims = " ,V";
char* tok = strtok(buffer, delims); // +CVB:
tok = strtok(NULL, delims);
int first = atoi(tok);
tok = strtok(NULL, delims);
int second = atoi(tok);
tok = strtok(NULL, delims);
float voltage = atof(tok);
Serial.println(first);
Serial.println(second);
Serial.println(voltage);
}
void loop() {
}
Upvotes: 1
Reputation: 16912
This fixed it:
float getVoltage() {
if (atCmd("AT+CBC\r") == 1) {
char *p = strchr(buffer, 'V');
if (p) {
p -= 5; // get voltage
double vo = atof(p) ;
//printf("%1.3f\n", vo);
return vo;
}
}
return 0;
}
Upvotes: 0