Display giving different values than serial moniter

For some reason the serial moniter and the lcd screen prints the same value for numbers increasing by 5 from 0 to 255, but then when it gets down to 100 the lcd starts printing random values while the serial moniter continues printing the correct numbers, why would this be?
Code Used:

// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
// The pin connected to the LED
int brightness = 0; // Initial brightness value
int fadeAmount = 5; // How much to increment the brightness each time (adjustable)
int i =0;

void setup() {
Serial.begin(9600);
pinMode(3, OUTPUT); // Set the LED pin as an output
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("Light Level: ");
}
void loop() {

lcd.setCursor(8, 2);
/------------------------------------------------/

analogWrite(3, brightness); // Set the LED brightness

// Increment the brightness
brightness += fadeAmount;
delay(900);
i = i +fadeAmount;

// Reverse the direction of fading when brightness reaches its limits
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount;
}
lcd.print(brightness);
Serial.print(brightness);
Serial.print(" ");
Serial.println();
}

Let me guess: you are seeing something like this sequence of numbers on your LCD display:
... 105, 100, 950, 900, 850, 800, 750, ...
where you are seeing the numbers you expect to see, except that they have an extra 0 at the end (950 instead of 95, then 900 instead of 90, and so on).
The reason you are seeing the extra zero is that 100 has three digits, but 95 only has two digits, so when you have the number 100 on the display and try to print 95, it doesn't get rid of the last 0 so you end up with 950 on the display.

Here is the fix I would use:
After this line:

lcd.print(brightness);

insert this line:

lcd.print(" ");

That will cover up the extra zero with a space, so you should see your display behave correctly now.

2 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.