2012-12-07 34 views
0

该程序旨在将串行端口的文本写入Arduino的LCD以及串行监视器。但是,它会打印出一串很长的随机数字。字符需要存储在一个数组中,所以文本可以在LCD上移动而不必再次读取串口(我打算在后面加入)。我究竟做错了什么?通过C串行端口进行写入

下面是代码:

// 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 
    } 
} 
+0

您在不检查available()的情况下调用read()。垃圾就是结果。 –

+0

我回滚到第二个版本。我不认为纠正检测到的错误*将有助于未来的观众。它也会使答案看起来像无稽之谈。 – wildplasser

+0

为什么标题和标签要求的问题是关于“C”语言?它看起来就像那些OO增强的C变体之一。 – sawdust

回答

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

+0

谢谢,我是c新手,那就是问题所在。现在我有一套全新的问题,哈哈。 – user1739123

+0

有关'ÿ'的更多注意事项已添加到我的答案中。 – duskwuff