arduino 2字节serial.read

时间:2013-08-30 20:49:45

标签: serial-port arduino

我是编程的初学者,我需要一些帮助才能通过串口读取请求(0x01到msb和0x02到lsb)后出现的2个字节(msb / lsb),然后进行数学运算并显示在2x16显示屏。我的项目功能只使用1个字节。一个例子:

void funcao4()
{ 
 int MAP;
float MAP1;
delay(600);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("MAP[mmHG]");


Serial.write(0x06);  //request

if (Serial.available() > 0) 
{

MAP = Serial.read() ;   //read
MAP1 = (MAP * 2.8759 + 91); //operation

lcd.setCursor(0,1);
lcd.print(MAP1); //display

}
}   

问候。

2 个答案:

答案 0 :(得分:2)

等到串行缓冲区有两个字节,然后读取它们:

void funcao4()
{ 
 int MAP;
float MAP1;
delay(600);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("MAP[mmHG]");


Serial.write(0x06);  //request

while(Serial.available() < 2); //wait until there are two bytes in the buffer


MAP = Serial.read() << 8 ;   //read MSB into MAP
MAP += Serial.read();        //read LSB into MAP
MAP1 = (MAP * 2.8759 + 91); //operation

lcd.setCursor(0,1);
lcd.print(MAP1); //display


}  

此代码阻塞,因此您可能希望从while循环更改为延迟和一些if语句。另外我不确定你的LCD是先打印MSB还是LSB,我假设是MSB。

答案 1 :(得分:1)

if (Serial.available() >= 2) 
{
    MAP = Serial.read() << 8;
    MAP |= Serial.read();
}