Dial gauge on a colour TFT (ST7789)
Draw a round gauge on a 240x240 ST7789 display and move its needle with a knob, redrawing only what changes.
Displays · Intermediate
In a real product: E-bike display (Consumer electronics): A colour dial shows speed and battery.
Colour TFTs are slow to fill: 240 × 240 pixels at two bytes each is 115 KB over SPI. A gauge that redraws the whole screen every reading flickers. This one draws its dial once and then only erases and redraws the needle.
What you'll learn
- Driving an ST7789 through Adafruit GFX: shapes, lines and text
- Drawing incrementally: erase the old needle with the background colour, draw the new one
- Turning a value into a needle angle with sin and cos
How it works
tft.init(240, 240) sends the ST7789's start-up commands (including INVON, which its IPS glass needs to show colours right). drawDial() paints the face and its ticks once. Each loop reads the knob, maps it to −120°…+120°, and only if the needle moved: draws over the old needle in the face colour, draws the new one in red and prints the value.
Try this
- Turn the knob: the needle sweeps without the screen flashing.
- Replace the incremental redraw with
drawDial()every time and watch how much slower it gets. - Add a red zone on the dial above 80 % with
fillTriangle()slices.
sketch.ino
// A dial gauge on a 240x240 ST7789 (CS 10, DC 9, RST 8, hardware SPI): the knob on A0 moves the needle from -120 to
// +120 degrees. The face is drawn once; each change redraws only the needle and the number.
#include <Adafruit_GFX.h>
#include <Adafruit_ST7789.h>
Adafruit_ST7789 tft(10, 9, 8);
const int CX = 120, CY = 130, R = 100;
const uint16_t FACE = 0x18E3; // dark grey-blue
float lastAngle = 999;
void needle(float degrees, uint16_t colour) {
float a = (degrees - 90) * PI / 180;
tft.drawLine(CX, CY, CX + cos(a) * (R - 18), CY + sin(a) * (R - 18), colour);
tft.drawLine(CX + 1, CY, CX + 1 + cos(a) * (R - 18), CY + sin(a) * (R - 18), colour);
}
void drawDial() {
tft.fillScreen(ST77XX_BLACK);
tft.fillCircle(CX, CY, R, FACE);
for (int d = -120; d <= 120; d += 30) {
float a = (d - 90) * PI / 180;
tft.drawLine(CX + cos(a) * (R - 10), CY + sin(a) * (R - 10), CX + cos(a) * R, CY + sin(a) * R, ST77XX_WHITE);
}
tft.setTextColor(ST77XX_WHITE);
tft.setTextSize(2);
tft.setCursor(70, 8);
tft.print("KNOB %");
}
void setup() {
tft.init(240, 240);
drawDial();
}
void loop() {
int value = analogRead(A0);
float angle = -120 + 240.0 * value / 1023;
if (fabs(angle - lastAngle) < 1) return;
if (lastAngle != 999) needle(lastAngle, FACE);
needle(angle, ST77XX_RED);
tft.fillCircle(CX, CY, 6, ST77XX_WHITE);
lastAngle = angle;
tft.fillRect(90, 190, 70, 24, FACE);
tft.setCursor(98, 194);
tft.print(value * 100L / 1023);
}