Arduino 串行解析

Arduino Serial parsing

本文关键字:Arduino      更新时间:2023-10-16

我正在研究Arduino草图,我正在尝试用串行更改变量。我正在使用我在 arduino.cc 上找到的一些示例代码作为开始。我正在尝试使用"if 语句"修改代码以使用integerFromPC更新变量timevar;我遇到的问题是,如果我输入一个高于 4 位的数字,例如 99999,它会打印出错误的数据,并且变量timevar无法正确更新?我不知道该怎么办?

unsigned long timevar = 1000000;
const byte numChars = 32;
char receivedChars[numChars];
char tempChars[numChars];        // temporary array for use when parsing
// variables to hold the parsed data
char messageFromPC[numChars] = {0};
int integerFromPC = 0;
int ifpc = 0;
float floatFromPC = 0.0;

boolean newData = false;
//============
void setup() {
Serial.begin(9600);
Serial.println("This demo expects 3 pieces of data - text, an integer and a floating point value");
Serial.println("Enter data in this style <HelloWorld, 12, 24.7>  ");
Serial.println();
}
//============
void loop() {
recvWithStartEndMarkers();
if (newData == true) {
strcpy(tempChars, receivedChars);
// this temporary copy is necessary to protect the original data
// because strtok() used in parseData() replaces the commas with 
parseData();
showParsedData();
newData = false;
}
}
//============
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = ''; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
}
//============
void parseData() {      // split the data into its parts
char * strtokIndx; // this is used by strtok() as an index
strtokIndx = strtok(tempChars,",");      // get the first part - the string
strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC
strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
integerFromPC = atoi(strtokIndx);

strtokIndx = strtok(NULL, ",");
floatFromPC = atof(strtokIndx);     // convert this part to a float
}
//============
void showParsedData() {
if (strcmp(messageFromPC, "set time") == 0) 
timevar = integerFromPC;
Serial.print("Time Set To ");
Serial.println(integerFromPC);
Serial.println(timevar);
}
//do other stuff

你声明int integerFromPC. Arduino 上的int是 16 位。99999 不适合 16 位,因此将显示 mod 2^16 为 34463。请改用long,就像timeVar一样,最多 +/- 2^31 就可以了。