1

该程序旨在读取输入,并将其写在 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.

}
4

2 回答 2

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 个字节的消息发送到您的代码,因为它发布在此处将覆盖这些值。

于 2012-12-03T18:30:52.990 回答
0

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

if (Serial.available() > 0) { //If the serial monitor is open it will read a value.
 line1 = Serial.read();
 delay(100);
 Serial.print(line1);
于 2012-12-04T10:45:47.107 回答