Unable to display serially sent data on LCD Display 16U2A

#include <LiquidCrystal.h>

LiquidCrystal lcd(12,11,4,5,6,7);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
lcd.begin(16,2);
while (!Serial) {
}
}
void loop() { // run over and over
if (Serial.available()) {
  int distance = Serial.read();
  //Serial.write(distance);
  lcd.clear();
  lcd.print(distance);

Having trouble with displaying distance value that is sent serially from my NodeMCU to the Arduino. The LCD is connected to the Arduino. The value is supposed to be 14, but the LCD is displaying 50 to 54 everytime Serial.available is true. The serial monitor displays the distance value correctly.

I've attempted to replace the Serial.read() with 15 (and a few other numbers/strings)

int distance = 15 //instead of Serial.read()

and the LCD is able to display it perfectly. But when I change to distance, its displaying the wrong value despite the serial monitor showing the correct value.

Are you familiar with ASCII ASCII Table - ASCII codes,hex,decimal,binary,html ?

Characters are typically encoded as ASCII.

You have not shown the code that sends the data, but I am guessing it is sending ASCII, you are then displaying the ASCII character as a number. Have a look at the ASCII table I linked to and you'll see what's happening.

int distance = Serial.read();

Tells the compiler that what you are getting from the serial port is an integer, not a character. This is wrong for 2 reasons, you only get single bytes from a serial port, not integers (2 bytes) and, so far as I can tell, you are receiving data encoded as ASCII characters.

First step try:

char distance = Serial.read();

The code you posted is incomplete by the way.

You might find Serial input basics helpful

Why not start by simply printing "opqw" on a display you have just cleared and turned on the backlight LED. If you cannot get this to work you have problems. I am basing this on the assumption you correctly determined your code was correct.

You really are making things difficult for yourself! The NodeMCU is substantially more powerful than what I presume is a UNO or Nano; you should drive the display directly from the NodeMCU.

However I suspect you are concerned about the number of pins the display requires on the NodeMCU. You need an I2C "backpack" on the display which requires only two I2C pins - which can also be common to any other I2C attachments. These are one of the cheapest modules available,

PerryBebbington:
You might find Serial input basics helpful

Sorry for the late reply, much thanks for sharing this and the ASCII table. I've managed to display the value referring example 3. Turns out I was displaying the decimal of each character of the ASCII sent over serial. Everything's working as it should now, thank you..

This topic was automatically closed after 59 days. New replies are no longer allowed.