[英]Issue with converting String to unsigned long
将char字符串数组转换为unsigned long时,我遇到了一个小问题。 这是我对executeCommand()的输入。
0001000118218; 326
这就是我得到的。
收到命令:0001000118218; 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]
为char periodid[4]
。 3个元素表示内容,1个元素表示零终止符。
您还必须将其更改为toCharArray(periodid, 3);
到toCharArray(periodid, 4);
或更好, toCharArray(periodid, sizeof(periodid));
如果将命令转换为字符数组并使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.