这里有两种方法可以解决这个问题。1st 将简单地连接一个字符串类型并在回车完成时将其转换为整数。
#define _CR 13
String readString;
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available()) {
char c = Serial.read(); //gets one byte from serial buffer
readString += c; //makes the string readString
delay(2); //slow looping to allow buffer to fill with next character
}
if ((readString.length() >0) || ( c == CR_)) {
Serial.println(readString); //so you can see the captured string
int n = readString.toInt(); //convert readString into a number
// do whatever you want
// ...
//
//
readString=""; //empty for next input
}
}
另一种方法是使用字符间超时。请注意,通常
while (!Serial.available()) {
// wait for Serial input
};
inkey = Serial.read();
正在阻塞。下面使用 char 数组的指针来构建输入,最多 5 位是 int16_t 的长度(即 65535)。嗯,它只处理积极因素。但是您可以对其进行调整以获取负数,以及其他命令,例如“+”、“-”等...
我使用 ICT 方法的原因是因为 Arduino 的 IDE 串行监视器实用程序默认为无 LF/CR。它只是一次发送输入而没有任何 LF/CR。
int16_t last_ms_char; // milliseconds of last recieved character from Serial port.
int8_t buffer_pos; // next position to recieve character from Serial port.
char buffer[6]; // 0-35K+null
int16_t fn_index;
int16_t Serial_Input_Number;
void setup() {
Serial.begin(115200);
last_ms_char = millis(); // stroke the inter character timeout.
buffer_pos = 0; // start the command string at zero length.
}
void loop() {
char inByte;
if (Serial.available() > 0) {
inByte = Serial.read();
if (isDigit(inByte)) { // macro for ((inByte >= '0') && (inByte <= '9'))
// else if it is a number, add it to the string
buffer[buffer_pos++] = inByte;
} else {
// input char is a letter command
buffer_pos = 0;
parse_menu(inByte);
}
buffer[buffer_pos] = 0; // update end of line
last_ms_char = millis(); // stroke the inter character timeout.
} else if ((millis() - last_ms_char) > 500 && ( buffer_pos > 0 )) {
// ICT expired and have something
if (buffer_pos == 1) {
// look for single byte (non-number) menu commands
parse_menu(buffer[buffer_pos - 1]);
} else if (buffer_pos > 5) {
// dump if entered command is greater then uint16_t
Serial.println(F("Ignored, Number is Too Big!"));
} else {
// otherwise its a number, scan through files looking for matching index.
Serial_Input_Number = atoi(buffer);
//
//
// Do something with "Serial_Input_Number"
// one time here. Or set flag and do something out of this big if
// ...
//
//
}
//reset buffer to start over
buffer_pos = 0;
buffer[buffer_pos] = 0; // delimit
//
//
// do other stuff repeatedly between new characters
// ...
//
//
}
无法保证确切的代码,因为它是从更大的示例中剪裁和修剪的,确实有效。