Sub topic 8
Updating readings without flicker or leftover characters
This chapter assumes you can already print text on a 16x2 HD44780 LCD with LiquidCrystal and show text on an SSD1306 OLED with the Adafruit libraries. It also assumes you know millis() and analogRead(). The goal is to update a changing value on either display so it looks steady and never shows stale characters.
Why displays show the wrong thing
A display does not erase anything on its own. Two different models cause two different bugs.
- Character LCD. The controller keeps one character per cell. Writing to a cell replaces only that cell. If the value
100is on screen and you print99at the same position, the screen shows990. The final0is left over from the old text. - OLED. Your sketch draws into a frame buffer in RAM, and
display()copies the whole buffer to the screen. Pixels you never clear stay lit in the buffer. If you calldisplay()while the buffer is half drawn, the screen briefly shows that half-finished frame. Repeated often, this looks like flicker.
| Symptom | Display | Cause | Fix |
|---|---|---|---|
| Extra trailing digits | LCD | A shorter value was printed over a longer one | Pad every field to a fixed width |
| Whole screen blinks | LCD | `lcd.clear()` called in `loop()` | Overwrite fields instead |
| Text flashes or half-drawn frames | OLED | `display()` called between clear and draw | Draw the full frame, then call `display()` once |
| Sketch feels slow | OLED | `display()` called on every pass of `loop()` | Redraw only on change and at a limited rate |
| Digits jitter constantly | Both | Noisy sensor reading | Add a dead band, or show fewer digits |
The update pattern
Both displays follow the same loop. Wait until an update is due, read the sensor, skip the redraw if nothing meaningful changed, format the value into fixed-width text, and draw it.
The timer uses millis() instead of delay(), so the sketch can still do other work between updates. Subtracting lastUpdate from millis() stays correct when the counter wraps after about 49 days, because unsigned arithmetic wraps the same way.
Updating an LCD field without clearing
lcd.clear() takes about 1.5 ms and blanks the whole screen, so calling it every pass shows up as blinking. Overwrite instead. The helper below writes the text, then fills the rest of the field with spaces. That erases any leftover characters from a longer previous value.
#include <LiquidCrystal.h>
// RS, E, D4, D5, D6, D7
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const unsigned long UPDATE_MS = 250;
unsigned long lastUpdate = 0;
int lastValue = -1000;
// Write text at (col, row), then pad with spaces up to width characters.
void printField(byte col, byte row, const char *text, byte width) {
lcd.setCursor(col, row);
byte i = 0;
while (i < width && text[i] != '\0') {
lcd.write(text[i]);
i++;
}
while (i < width) {
lcd.write(' ');
i++;
}
}
void setup() {
lcd.begin(16, 2);
lcd.print("Sensor reading");
lcd.setCursor(0, 1);
lcd.print("A0 = ");
}
void loop() {
if (millis() - lastUpdate < UPDATE_MS) {
return;
}
lastUpdate = millis();
int value = analogRead(A0);
if (abs(value - lastValue) < 2) {
return; // dead band: ignore 1-count noise
}
lastValue = value;
char buf[8];
snprintf(buf, sizeof(buf), "%d", value);
printField(5, 1, buf, 4); // the value occupies columns 5 to 8
}Static labels such as "A0 = " are printed once in setup(). Only the value field is rewritten, and the cell positions of the label never change. This is the cheapest way to avoid flicker, because the label is never redrawn.
The field width must be at least as wide as the longest value you expect. A 10-bit analogRead() reaches 1023, so four characters are enough. If you pick a width that is too small, the value is cut off by the helper.
You can also let snprintf do the padding. The format "%-4d" left-aligns in four characters and "%4d" right-aligns. Right alignment is easier to read for numbers because the digits line up by place value.
Showing decimals with integers
Store the reading as an integer in tenths, then split it for display. This avoids float formatting and keeps the width predictable.
int tenths = 237; // 23.7
char buf[10];
snprintf(buf, sizeof(buf), "%d.%d C", tenths / 10, abs(tenths % 10));For negative values, -5 tenths gives 0.5 because -5 / 10 is 0. Handle the sign separately if your sensor can go below zero.
Updating an OLED without flicker
On the OLED, the standard approach is to redraw the whole frame. Call clearDisplay(), draw everything, and then call display() once at the end. The screen only ever receives complete frames, so it never shows a blank or half-drawn one.
Two mistakes cause most OLED flicker:
- Calling
display()right afterclearDisplay(). This sends a blank frame to the screen. - Calling
display()several times in one pass, once per drawing call. Each call sends the full buffer.
display() sends the whole 1024-byte buffer of a 128x64 screen, even if only one digit changed. Adafruit's library raises the I2C clock to 400 kHz while it transfers, which makes one call take roughly 25 to 30 ms. At the 100 kHz default it would take about four times as long. That cost is why you limit the redraw rate.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display(128, 64, &Wire, -1);
const unsigned long UPDATE_MS = 100;
unsigned long lastUpdate = 0;
int lastValue = -1000;
void setup() {
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
for (;;) {} // display not found: stop here
}
display.setTextColor(SSD1306_WHITE);
}
void loop() {
if (millis() - lastUpdate < UPDATE_MS) {
return;
}
lastUpdate = millis();
int value = analogRead(A0);
if (abs(value - lastValue) < 2) {
return; // nothing worth redrawing
}
lastValue = value;
long millivolts = (long)value * 5000L / 1023L;
char line[16];
snprintf(line, sizeof(line), "%ld.%03ld V", millivolts / 1000, millivolts % 1000);
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
display.print(F("Battery"));
display.setTextSize(2);
display.setCursor(0, 20);
display.print(line);
display.display(); // one transfer per frame
}The sketch assumes a 5 V reference. Change the 5000L constant if your board uses 3.3 V as the analog reference.
Nothing is padded here, because clearDisplay() already wiped every pixel in the buffer. Width only matters on the OLED if you decide to redraw part of the frame.
Redrawing only part of the frame
You can skip clearDisplay() and erase a rectangle around the value, then draw the new text there. This is useful when the rest of the screen holds a static layout that costs many drawing calls.
display.fillRect(0, 20, 128, 16, SSD1306_BLACK); // erase the value area
display.setCursor(0, 20);
display.print(line);
display.display();Another option is to give the text a background color, as in display.setTextColor(SSD1306_WHITE, SSD1306_BLACK). Each character cell is then painted black behind the glyph, so a shorter string erases the characters it covers. It does not erase cells beyond the new string, so you still need to pad to a fixed width. The fillRect approach is the more reliable of the two.
Partial redraws save drawing work in the buffer, not transfer time. display() still sends everything, so the redraw interval is still your main control over how busy the I2C bus is.
Choosing the dead band and interval
Noise is the usual reason a display never looks steady. A 10-bit ADC often wobbles by one or two counts even with a fixed input, so a plain "changed?" test fires almost every pass. You have three ways to deal with it:
- Dead band. Redraw only if the new value differs from the shown value by at least a threshold, as in the sketches above. Set it to the visible resolution you care about.
- Fewer digits. Round before display, for example show tenths of a volt instead of millivolts.
- Averaging. Take several readings and show their mean. This is a sensor technique, not a display one, but it removes the jitter at its source.
Compare the value you read with the value currently shown, not with the previous reading. Otherwise a slow drift can move the true value many counts away without ever crossing the dead band between two reads.
For the interval, a good starting point is 100 to 250 ms for an OLED and 200 to 500 ms for an LCD. Character LCDs with slow liquid crystal also look smeared when text changes faster than that.
Exercise
An LCD row shows Count: 100. Your code calls lcd.setCursor(7, 0); lcd.print(count); and the count drops to 99. What does the row show, and what is the smallest change to the code that fixes it?
Show answer
The row shows Count: 990. The 99 overwrites the first two digits and the old 0 stays. Print the value into a buffer and pad it to three characters, for example snprintf(buf, sizeof(buf), "%-3d", count); lcd.print(buf);, or use the printField() helper with width 3.
Exercise
An OLED sketch calls display.clearDisplay(), then display.display(), then draws a title and a value and calls display.display() again. The screen flickers. What is wrong, and how many display() calls should each pass of the loop make?
Show answer
The first display() sends a blank frame to the screen before the real content is drawn, so the screen alternates between blank and filled. Remove it. Each pass should make exactly one display() call, after all drawing for that frame is done.
Exercise
Your sketch reads analogRead(A0) every pass and redraws only when value != lastValue, but the OLED still redraws almost every time. Why, and what two changes help most?
Show answer
The ADC reading jitters by a count or two, so the value differs on almost every read. Add a dead band such as abs(value - lastValue) < 2 so small changes are ignored, and limit the redraw rate with a millis() timer such as 100 ms.