say I got a String message from a sensor
String sensorMessage = "A0 B1 C2";
I can use .substring to separate the string into three groups, like String Value_1 = sensorMessage.substring(0,2), etc. But how could I convert these three string into three Int values? It seems that the toInt() function could only correctly interpret the input if it means DEC value.
Thanks in advance for your advice.
I would not use String at all, but here you go.
String sensorMessage = "A0 B1 C2";
int val1, val2, val3;
void setup() {
Serial.begin(250000);
val1 = strtol(sensorMessage.c_str(), nullptr, 16);
val2 = strtol(sensorMessage.c_str() + 3, nullptr, 16);
val3 = strtol(sensorMessage.c_str() + 6, nullptr, 16);
printIn(HEX);
printIn(DEC);
}
void printIn(int base) {
Serial.print(val1, base);
Serial.write(' ');
Serial.print(val2, base);
Serial.write(' ');
Serial.print(val3, base);
Serial.write(' ');
}
void loop() {}
A0 B1 C2 160 177 194
Thanks for your explicit code! It works. Just for curiosity, the sensor message is a String type, how do you mean that you would not use String at all?
String is merely an OOP wrapper of the native char-array-strings, using malloc/free new/delete to handle the buffers.
On systems with lots of memory that is not a problem., but most Arduinos don't have that.
There is no real gain from using String, but you loose long term stability if you really use them.