将String转换为unsigned long的问题

时间:2012-02-04 21:40:14

标签: c arduino arrays unsigned-long-long-int

将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);
}

2 个答案:

答案 0 :(得分:2)

char periodid[3];
如果你想要一个长度为3的字符串,那么

应该是char periodid[4];内容的3个元素和零终止符的1个元素。

您还必须将toCharArray(periodid, 3);更改为toCharArray(periodid, 4);或更高,toCharArray(periodid, sizeof(periodid));

答案 1 :(得分:1)

如果将命令转换为字符数组并使用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);