0

该程序旨在将文本从串行端口写入 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
    }
}
4

1 回答 1

2

您将很多东西用单引号括起来,这不应该是:

  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. 请记住,串行链路另一端的设备并不总是一次写入一整行数据——在大多数情况下,它会一次写入一个字符。

于 2012-12-07T20:43:39.787 回答