仅限Arduino只读一个字符。

时间:2012-12-03 16:04:28

标签: c++ arduino

该程序用于读取输入,并在Arduino的串行监视器中写出。它只在串行监视器中写入一个字符的问题。

void setup()
{
Serial.begin(9600); //Set the serial monitor.
lcd.begin(16, 2); //Set the LCD
}
// Alignment variables
boolean left = true; //Set boolean left to true to begin to display text in middle of screen.
boolean right = false; //Other possible align booleans set to false
boolean select = false;
//Text show/hide variables
boolean show1 = true;  //Both values set to true to display on start up.
boolean show2 = true;
//Serial input
char serialinput [4] = {0}; //For 3 value input, and null character to end.
char line1;
void loop()
 {

 if (Serial.available() > 0) { //If the serial monitor is open it will read a value.
    line1 = Serial.read();
    Serial.print(line1);
    memmove (serialinput, &serialinput[1], 3); //copy the value to memory
    serialinput [2] = Serial.read(); //value is read.
    //if statements for each possible input.

}

2 个答案:

答案 0 :(得分:0)

您向line1读取一个字节,然后打印该字节。一条线应该以环形或类似方式打印。还有这个评论:

if (Serial.available() > 0) { 
//If the serial monitor is open it will read a value.

不是真的。 Serial.available()返回当前缓冲区中的字节数。因此,这一行:serialinput[2] = Serial.read();正在调用read(),而不会验证是否有任何要读取的内容。显然//if statements for each possible input.末尾有loop(),这些有什么作用?我怀疑没有逻辑断言在serialinput[]特定字节结束的位置。在此处发布的代码中发送超过2个字节的消息将覆盖这些值。

答案 1 :(得分:0)

Serial.read不会等待字符串的结尾。如果你试图读取几个字符(由[4]暗示),你只需要在serial.read之后包含一个短延迟(),以便有足够的时间让缓冲区完全转储字符串。

if (Serial.available() > 0) { //If the serial monitor is open it will read a value.
 line1 = Serial.read();
 delay(100);
 Serial.print(line1);