该程序旨在将文本从串行端口写入Arduino的LCD,并在串行监视器上。但是,它打印出一长串随机数。字符需要存储在一个数组中,因此文本可以在LCD周围移动,而无需再次读取串行端口(我计划稍后再放入)。我究竟做错了什么?

这是代码:

// These are the pins our LCD uses.
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup()
{
    Serial.begin(9600); //Set the serial monitor.
    lcd.begin(16, 2); //Set the LCD
}

char ch;
int index = 0;
char line1[17]; //17 is the max length of characters the LCD can display
char line2[17];
void loop() {
   lcd.setCursor(0,0); //Set the cursor to the first line.
   if( Serial.available() ) { //If the serial port is receiving something it will begin
        index=0;               //The index starts at 0
        do {
            char ch = Serial.read(); //ch is set to the input from the serial port.
            if( ch == '.' ) {        //There will be a period at the end of the input, to end the loop.
                line1[index]= '\0';   //Null character ends loop.
                index = 17;           //index = 17 to end the do while.
            }
            else
            {
                line1[index] = ch;    //print the character
                lcd.print('line1[index]');  //write out the character.
                Serial.print('line1[index]');
                index ++;            //1 is added to the index, and it loops again
            }
        } while (index != '17');  //Do while index does not = 17
    }
}

最佳答案

您将很多东西都用单引号引起来,而不应该这样:

  lcd.print('line1[index]');  //write out the character.
  Serial.print('line1[index]');


这些都应为line1[index](不带引号),因为您需要该表达式的结果。

} while (index != '17');  //Do while index does not = 17


这应该是17,而不是'17'

关于ÿ-字符255(也将显示为字符-1),表示Serial.read()数据用完并返回-1。请记住,串行链接另一端的设备将不会总是一次写入整行数据,在大多数情况下,它会一次滴入一个字符。

08-27 05:35