Reputation: 11
I am beginer in programming, and I need some help to read 2 bytes (msb/lsb) that comes after a request (0x01 to msb and 0x02 to lsb) via serial, and then, make an mathematical operation and display on an 2x16 display. I have the functions of my project that use only 1 byte working good. One example:
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
}
}
regards.
Upvotes: 1
Views: 11496
Reputation: 942109
if (Serial.available() >= 2)
{
MAP = Serial.read() << 8;
MAP |= Serial.read();
}
Upvotes: 1
Reputation: 1433
Wait until the Serial buffer has two bytes, then read them:
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
}
This code is blocking so you may want to change from a while loop to a delay and some if statements. Also I'm not sure if your LCD prints MSB or LSB first, I assumed MSB.
Upvotes: 2