我在将char字符串数组转换为无符号long时遇到了一个小问题。
这是我对executeCommand()的输入。
0001000118218;326
这就是我得到的。
接收命令:00010000118218;326
传输码:1821
传输周期:32
我不明白为什么最后一个数字掉了。。。
#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);
}
最佳答案
char periodid[3];
如果要在其中包含长度为3的字符串,则应为
char periodid[4]
;3个元素用于内容,1个元素用于零结束符。您还必须将
toCharArray(periodid, 3);
更改为toCharArray(periodid, 4);
或更好,toCharArray(periodid, sizeof(periodid));
关于c - 将String转换为unsigned long的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9144794/