所以,我正在尝试用Arduino设置一种计算器。我已经设法从红外遥控器读取数据并将其显示在LCD 16x2显示器中。例如,如果输入“1”,显示屏上将显示“1”,但如何让程序理解如果在输入按钮之前按下两个或更多数字,则它是一个超过1的数字algarism?就像按1,然后2然后3等于123?
我可以做很多if语句来执行类似“如果1在现有1之后被按下而不是变量== 11”等等,但是这没有用。
无论如何,我该怎么做?或者你能指出我这种功能/算法的名称,所以我可以期待它。
感谢。
答案 0 :(得分:0)
以下是两种解决方法。 1st将简单地连接一个字符串类型,并在Carriage Return完成后将其转换为整数。
#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
}
}
另一种方法是使用Inter Character Timeout。请注意,通常
while (!Serial.available()) {
// wait for Serial input
};
inkey = Serial.read();
正在阻止。下面使用char数组的指针来构建输入,最多5位数字int16_t(即65535)的长度。嗯它只处理积极因素。但你可以调整它以获得否定,以及其他命令,如“+”,“ - ”等......
我使用ICT方法的原因是因为Arduino的IDE串行监视器实用程序默认为No 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
// ...
//
//
}
无法保证确切的代码,因为它从较大的示例中进行了修剪和修剪,确实有效。