这里有两种方法可以解决这个问题。 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
// ...
//
//
}
不能保证精确的代码,因为它是从更大的示例中篡改和修剪的,它们可以工作。
虽然它不是我所需要的,但它帮助我找到了一种方法来做到这一点,即“+ =”运算符。谢谢。 – Thums 2013-02-24 00:40:26