Issue with converting String to unsigned long
-
22-04-2021 - |
Question
I have a little problem with converting a char string array to an unsigned long. This is my input for executeCommand().
0001000118218;326
And this is what i get back.
Received command: 0001000118218;326
transmit code: 1821
transmit period: 32
I don't understand why the last digit is dropped...
#define id_length 4
#define command_length 4
const String my_id = "0001";
//Command execution methods
void executeCommand(String inputData) {
if(!my_id.equals(inputData.substring(0, id_length))) {
return;
}
Serial.print("Received command: ");
Serial.println(inputData);
String command = inputData.substring(id_length, id_length + command_length);
String parameters = inputData.substring(id_length + command_length);
for (int i = 0; i < 3; i++) {
if(command == "0001") { //RF power command
unsigned long rfid_long;
unsigned long periodid_long;
char rfid[parameters.indexOf(';')];
char periodid[3];
parameters.substring(0, parameters.indexOf(';')).toCharArray(rfid, parameters.indexOf(';'));
parameters.substring(parameters.indexOf(';') + 1).toCharArray(periodid, 3);
rfid_long = strtoul(rfid, NULL, 10);
periodid_long = strtoul(periodid, NULL, 10);
sendRF(rfid_long, periodid_long);
}
else {
Serial.println("Unknown command received");
}
delay(10);
}
}
void sendRF(unsigned long transmitCode, unsigned int transmitPeriod) {
//digitalWrite(transmitLedPin, HIGH);
Serial.print("transmit code: ");
Serial.println(transmitCode);
Serial.print("transmit period: ");
Serial.println(transmitPeriod);
RemoteSwitch::sendTelegram(generateTelegram(transmitCode, transmitPeriod), rfSubmitPin);
//digitalWrite(transmitLedPin, LOW);
}
Solution
char periodid[3];
Should be char periodid[4]
if you want to have a string of length 3 in it; 3 elements for the contents and 1 for the zero terminator.
You'll also have to change toCharArray(periodid, 3);
to toCharArray(periodid, 4);
or better, toCharArray(periodid, sizeof(periodid));
OTHER TIPS
What if you convert command to a character array and use strchr?
char* separator = strchr(command, ';');
if (separator == NULL) return;
char* rfid = command + id_length;
char* periodid = separator + 1;
unsigned long rfid_long = strtoul(rfid, &separator, 10);
unsigned long periodid_long = strtoul(periodid, NULL, 10);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow