【发布时间】:2018-04-03 08:12:09
【问题描述】:
我正在制作一个 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 \0
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] = '\0'; // 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
【问题讨论】:
-
“
timevar没有正确更新”是什么意思?它没有改变,还是改变为错误的值?如果是这样,它会变成什么值?另外,它的值总是高于 4 位,还是高于 32767? -
它没有得到正确的值。我不确定我在这里缺少哪些转换或如何进行转换。你是对的,它的值高于 32767..