Display (ST7789)
The Firefly T1 display is driven by an ST7789 controller at 135 × 240. The firmware ships two things: tft_config (board-level setup that wires up SPI, the pins and the backlight for you) and st7789 (the driver itself, where every drawing, text and image API lives). Two lines of code light the screen up.
tft = tft_config.config(0) gives you the object, tft.init() lights the screen, and from then on every drawing call is tft.xxx().
SPI1 / 40 MHz, DC / CS / RST and the backlight PWM are all configured inside config() — nothing to wire yourself.
16-bit RGB565 color; rotation takes 0/1/2/3 to change direction, and landscape is 240×135.
Hardware and Pins
tft_config.config() has already wired up everything in the table below, so you never write a line of hardware configuration yourself:
| Item | Value |
|---|---|
| Bus | SPI(1), baud rate 40 MHz, polarity=0, phase=0 |
| MOSI / SDA | GPIO6 |
| SCK / CLK | GPIO7 |
| DC (command/data) | GPIO8 |
| CS (chip select) | GPIO10 |
| RST (reset) | GPIO9 |
| BLK (backlight) | GPIO11, brightness controlled with PWM |
| Resolution | 135 × 240 (rotation=0/2 portrait; 1/3 landscape 240 × 135) |
| Color format | RGB565 (16-bit) |
Quick Start
import tft_config
import st7789
tft = tft_config.config(0) # 0 = portrait, pass 1 for landscape
tft.init() # required: initializes the panel and clears the screen
tft.fill(st7789.BLACK) # clear the screen
tft.fill_rect(10, 10, 60, 30, st7789.RED) # draw a red rectangle
tft.text(font, "Hello", 10, 60, st7789.WHITE, st7789.BLACK)
What you'll see: the screen is cleared to black, then a red rectangle appears in the top-left corner. init() itself fills the whole screen with black, so calling fill() right afterwards is not strictly necessary — it is just the conventional way to write it.
font must be imported first, for example import vga2_16x32 as font. For how font libraries work, see Font Library.
Screen Orientation and Coordinate System
config(rotation) and tft.rotation(v) accept only the rotation values 0 / 1 / 2 / 3 (internally the value is taken % 4):
rotation | Orientation | width() × height() | Notes |
|---|---|---|---|
0 | Portrait | 135 × 240 | Default orientation |
1 | Landscape | 240 × 135 | Common in light-painting apps |
2 | Portrait flipped | 135 × 240 | Upside down |
3 | Landscape flipped | 240 × 135 | Upside down |
The origin (0, 0) is always the top-left corner of the current orientation, with x growing right and y growing down. Rotation swaps width and height, so never hard-code 135 / 240 in layout code — always use tft.width() and tft.height():
tft = tft_config.config(0)
tft.init()
x = (tft.width() - 100) // 2
y = (tft.height() - 100) // 2
tft.fill_rect(x, y, 100, 100, st7789.GREEN)
Colors
Colors are 16-bit RGB565 integers. Three ways to get one:
import st7789
st7789.BLACK # 8 common color constants: BLACK / BLUE / RED / GREEN
st7789.WHITE # CYAN / MAGENTA / YELLOW / WHITE
st7789.color565(255, 128, 0) # compute from RGB components (0-255 each)
st7789.color565(r, g, b) is a module-level function, so no instance is needed: it packs 8-bit RGB into an RGB565 integer. The channel order is decided by a constructor argument, and tft_config uses the default RGB.
That is a color-order (RGB/BGR) mismatch. The board ships configured for its panel, so you normally don't touch it; if you wire your own panel and the colors are off, change the BGR bit of MADCTL with tft.madctl(...).
API Reference
tft_config.config(rotation=0, buffer_size=0, options=0, backlight=300) returns a st7789.ST7789 instance (referred to as tft from here on). Every method hangs off that object.
Initialization: tft_config.config()
import tft_config
tft = tft_config.config(rotation=0, buffer_size=0, options=0, backlight=300)
| Parameter | Type | Default | Description |
|---|---|---|---|
rotation | int | 0 | Screen orientation, 0/1/2/3 (see the table above) |
buffer_size | int | 0 | Bytes of the resident buffer. 0 = allocate per operation and free it when done |
options | int | 0 | Driver option bit mask; accepts st7789.WRAP / WRAP_H / WRAP_V |
backlight | int | 300 | Backlight PWM duty, range 0–1023 (300 ≈ 30% brightness) |
Internally it does three things: create the SPI(1) bus, set the backlight pin GPIO11 to PWM and write the backlight value, and construct the st7789.ST7789 object.
config()only creates the object — it does not light the screen. You must calltft.init()yourself afterwards.- Call it once per program: every call creates a new SPI and PWM object, so repeated calls simply waste resources.
- Backlight brightness uses 0–1023, not percentages: for 50% brightness pass
512.
Lighting the screen: tft.init()
tft.init()
No arguments, no return value. It runs the panel initialization sequence, fills the whole screen with black, and finally turns the display on.
- Must be called once before any drawing, otherwise the screen stays white or shows noise.
- Screen contents are cleared after initialization, so don't expect the image from before power-on to survive.
- To change rotation later, call
tft.rotation(v)— you don't have toinit()again.
Orientation and Size
tft.rotation(v)
tft.rotation(1)
Switches the screen orientation. No return value. Internally v is taken % 4, so passing 4 is equivalent to 0; width() / height() swap accordingly.
tft.width() / tft.height()
w = tft.width() # width for the current orientation
h = tft.height() # height for the current orientation
Returns the pixel dimensions for the current orientation. No arguments.
tft.offset(col, row)
tft.offset(52, 40)
Sets the display window offset relative to the panel. No return value. The offset values for every orientation of this board are already built into the driver, so you generally don't change them by hand; you only need to override them when using a different panel (a 240×320 one, for example).
tft.madctl([v])
tft.madctl() # read back the current MADCTL register value
tft.madctl(0x60) # write a new MADCTL value
With no argument it returns the current MADCTL byte; with an argument it writes and returns it. It controls scan direction, row/column exchange and RGB/BGR color order — a low-level interface.
Display Control
tft.on() / tft.off()
tft.on() # turn the backlight on
tft.off() # turn the backlight off
No arguments, no return value. They operate on the backlight pin, and only take effect if backlight= was passed at construction time — tft_config does not hand the backlight pin to the driver (it controls GPIO11 with PWM itself), so on this board these two calls do not change brightness. To adjust brightness, drive the PWM directly:
from machine import Pin, PWM
bl = PWM(Pin(11))
bl.duty(0) # fully dark (backlight off)
bl.duty(1023) # brightest
tft.sleep_mode(enable)
tft.sleep_mode(True) # enter sleep (lower power, display off)
tft.sleep_mode(False) # wake up
Writes the panel's SLPIN / SLPOUT commands. While asleep the panel stops refreshing, and after waking you need to init() again or redraw the contents.
tft.inversion_mode(enable)
tft.inversion_mode(True)
Turns display inversion on or off (INVON / INVOFF). Note this is whole-screen inversion, which is not the same thing as negating a color565 value.
tft.hard_reset() / tft.soft_reset()
tft.hard_reset() # pull the RST pin low for a hard reset
tft.soft_reset() # send a SWRESET soft reset
No arguments, no return value. init() already handles resetting under normal circumstances, so these two are mainly for troubleshooting.
tft.vscrdef(tfa, vsa, bfa) / tft.vscsad(vssa)
tft.vscrdef(40, 160, 40) # 40 fixed rows on top, 160 scrolling rows, 40 fixed rows at the bottom
tft.vscsad(20) # set the first visible row of the scrolling area to row 20
No return value. vscrdef() splits the screen vertically into "top fixed area + scrolling area + bottom fixed area" (tfa / vsa / bfa are all row counts and should add up to the screen height); vscsad() sets which row of the scrolling area is currently displayed at the top.
It only configures the panel's scroll window; it does not animate anything by itself — to scroll you have to keep changing vscsad() in a loop. Scrolling logs, or a fixed status bar with scrolling content, both rely on it. tft_config exposes TFA = 40 / BFA = 40 as ready-made reference row counts for these two areas.
Drawing
All drawing methods take coordinates in the screen coordinates of the current orientation.
tft.fill(color)
tft.fill(st7789.BLACK)
Fills the whole screen with color. No return value. This is what you use to clear the screen.
tft.fill_rect(x, y, w, h, color)
tft.fill_rect(x, y, w, h, color)
Draws a filled rectangle with its top-left corner at (x, y), width w and height h. No return value.
tft.rect(x, y, w, h, color)
tft.rect(x, y, w, h, color)
Draws the border of a rectangle (no fill), with the same parameters as above. The border is made of 2 horizontal lines plus 2 vertical lines.
tft.hline(x, y, w, color) / tft.vline(x, y, h, color)
tft.hline(x, y, w, color) # draw w pixels right from (x, y)
tft.vline(x, y, h, color) # draw h pixels down from (x, y)
Draws horizontal / vertical line segments. No return value. They are far faster than line() (they take a fast path in a single direction), so prefer them for table rules and separators.
tft.line(x0, y0, x1, y1, color)
tft.line(0, 0, 100, 60, st7789.WHITE)
Draws an arbitrary diagonal segment. No return value. Internally it plots pixels one by one with Bresenham's algorithm, so it is slower than straight lines.
tft.pixel(x, y, color)
tft.pixel(10, 10, st7789.GREEN)
Draws a single pixel. No return value. It is fairly expensive (each point needs its own window setup), so it is not suited to plotting large numbers of points.
tft.circle(x, y, r, color) / tft.fill_circle(x, y, r, color)
tft.circle(67, 120, 40, st7789.CYAN) # hollow circle (outline)
tft.fill_circle(67, 120, 40, st7789.BLUE) # filled circle
Draws a circle centered on (x, y) with radius r. No return value. The hollow version traces the outline point by point; the filled version fills the interior with vertical lines, which is much faster than a row of pixel() calls.
Text
The three text APIs correspond to three different font formats and cannot be mixed:
| API | Font format required | Description |
|---|---|---|
tft.text(font, s, x, y[, fg, bg]) | Fixed-width bitmap vga1_* / vga2_* | Opaque and fast |
tft.write(font, s, x, y[, fg, bg, bg_tuple, fill]) | Variable-width bitmap (generated by font2bitmap) | Supports Chinese and can be drawn over a background image |
tft.draw(font, s, x, y[, color, scale]) | Vector fonts (the 26 modules under vector/) | Draws glyphs with line segments and scales to any size |
tft.text(font, s, x, y[, fg, bg])
tft.text(font, "Hello", 0, 0) # white on black
tft.text(font, "Hello", 0, 0, st7789.YELLOW) # yellow on black
tft.text(font, "Hello", 0, 0, st7789.YELLOW, st7789.BLUE)
| Parameter | Type | Default | Description |
|---|---|---|---|
font | module | — | A fixed-width bitmap font such as vga1_* / vga2_* |
s | int / str / bytes | — | The content to display; an int draws the single character with that code point |
x / y | int | — | Starting coordinate |
fg | int | WHITE | Text color |
bg | int | BLACK | Text background color |
No return value. Key points:
- Opaque: every character fills its whole
WIDTH × HEIGHTcell, andbgis that cell's background, so you cannot draw it over an image (it covers the background). - Character width is fixed at the font's
WIDTH, andxadvances automatically by that width. - Characters outside the font's range are skipped entirely:
vga1_*only covers0x20–0x7F, so using it to show Chinese characters gives you a blank area. - If a single character would cross the right edge of the screen (
x + WIDTH > width()), that character is simply not drawn, and there is no wrapping.
tft.write(font, s, x, y[, fg, bg, bg_tuple, fill])
tft.write(font, "Hello", 10, 10)
tft.write(font, "Hello", 10, 10, st7789.WHITE, st7789.BLACK, (bg, w, h), 1)
| Parameter | Type | Default | Description |
|---|---|---|---|
font | module | — | A variable-width font generated by font2bitmap |
s | str | — | The string to draw |
x / y | int | — | Starting coordinate |
fg | int | WHITE | Color used for pixels that are 1 in the glyph bitmap |
bg | int | BLACK | Color used for pixels that are 0 when there is no background image |
bg_tuple | tuple | none | (background buffer, width, height), used to draw text over a background image |
fill | int | 0 | When 1, every character is padded to the widest glyph in the font; used together with a background image |
Returns the actual printed pixel width (useful for computing later coordinates). It advances character by character using each glyph's own width, so mixed Chinese and English text has no large gaps.
To draw text over a background image, the idea is to cut out the piece of background where the text will appear and pass it as bg_tuple: pixels that are 1 in the glyph bitmap are painted fg, and pixels that are 0 keep the original background color. For the full technique see Image Display.
tft.draw(font, s, x, y[, color, scale])
import romans as font
tft.draw(font, "Hello", 10, 40, st7789.WHITE, 1.5)
| Parameter | Type | Default | Description |
|---|---|---|---|
font | module | — | A vector font under vector/ (containing INDEX / FONT) |
s | int / str | — | The content to display |
x / y | int | — | Starting coordinate |
color | int | WHITE | Line color |
scale | float / int | 1.0 | Scale factor; decimals are allowed |
No return value. It draws glyphs with line segments only and paints no background color, so it can be layered directly on top of existing content; when scaled up the edges stay straight instead of going blurry the way bitmap fonts do. The character range is likewise ASCII 32–127.
tft.write_len(font, s) / tft.draw_len(font, s[, scale])
w = tft.write_len(font, "Hello") # how wide this text will be when drawn
w = tft.draw_len(font, "Hello", 1.5) # how wide it will be at 1.5x scale
Returns the pixel width this text will occupy on screen without actually drawing it. Use it for centering and right alignment:
s = "Hello"
x = (tft.width() - tft.write_len(font, s)) // 2 # centered horizontally
tft.write(font, s, x, 10)
Images and Pixel Buffers
Full usage of the image APIs (FAST/SLOW selection, size limits, animation, transparency) is in Image Display; only the signatures are listed here.
tft.jpg(src, x, y[, mode])
tft.jpg('/sd/image/photo.jpg', 0, 0, st7789.SLOW)
| Parameter | Type | Default | Description |
|---|---|---|---|
src | str / bytes | — | File path, or JPEG data in memory |
x / y | int | — | Top-left corner of the image |
mode | int | st7789.FAST | FAST(0) decodes the whole image first and then pushes it; SLOW(1) decodes and pushes in blocks |
No return value.
tft.png(filename, x, y[, mask])
tft.png('/sd/image/icon.png', 10, 10)
tft.png('/sd/image/icon.png', 10, 10, True) # honor the alpha channel
Accepts file paths only and decodes row by row, so it only needs one row of pixels of memory. With mask=True, pixels with alpha 0 are skipped and whatever is already on screen shows through.
tft.bitmap(module, x, y[, index])
tft.bitmap(sprites, 30, 88) # omit index = show frame 0
tft.bitmap(sprites, 30, 88, 3) # show frame 3
Displays a bitmap module produced by the conversion script (containing WIDTH / HEIGHT / BPP / PALETTE / BITMAP, plus BITMAPS for multi-frame bitmaps). An index beyond BITMAPS raises OSError: index out of range.
tft.blit_buffer(buffer, x, y, w, h)
buf, w, h = tft.jpg_decode('/sd/image/photo.jpg')
tft.blit_buffer(buf, 10, 10, w, h)
Pastes a block of RGB565 pixel buffer onto the screen. All 6 arguments are mandatory. The number of bytes actually sent is min(buffer length, w × h × 2) — a buffer that is too small simply shows part of the image and does not raise.
tft.jpg_decode(src[, x, y, w, h])
buf, w, h = tft.jpg_decode('/sd/image/photo.jpg') # decode the whole image
buf, w, h = tft.jpg_decode('/sd/image/photo.jpg', 10, 10, 32, 32) # crop only 32×32
Returns a (bytearray, width, height) triple, where the buffer holds RGB565 data ready to be passed to blit_buffer() (the bytes are already swapped). When x, y, w, h are given, they mean which region to crop in the source image, not screen coordinates. Passing a number of arguments other than 2 or 6 raises TypeError.
In the source, every jpg_decode() call allocates 2 × width × height bytes and never frees them. So don't call it repeatedly inside a loop — the correct approach is to decode once and call blit_buffer() repeatedly.
Polygons
A polygon is represented by a list of coordinate points (((x0, y0), (x1, y1), ...)).
tft.polygon(poly, x, y, color[, angle, cx, cy])
triangle = ((0, 0), (60, 0), (30, 50))
tft.polygon(triangle, 20, 20, st7789.WHITE) # hollow (outline)
tft.polygon(triangle, 20, 20, st7789.WHITE, 30, 30, 25) # rotate 30° around (cx, cy)
Draws the edges of the polygon at (x, y) (no fill). angle is the rotation angle in degrees, and cx / cy are the center of rotation (in coordinates relative to the polygon itself).
tft.fill_polygon(poly, x, y, color[, angle, cx, cy])
tft.fill_polygon(triangle, 20, 20, st7789.RED)
Same as above, but fills the interior.
tft.polygon_center(poly)
cx, cy = tft.polygon_center(triangle)
Returns the center coordinates of the polygon (the average of its vertices), commonly used as the center of rotation.
tft.bounding([status, as_rect])
tft.bounding() # returns (min_x, min_y, max_x, max_y)
tft.bounding(1) # reset the bounding record
tft.bounding(1, True) # returns the rectangle form (min_x, min_y, w, h)
The driver keeps a bounding box of "which pixels have been drawn" internally, used to measure dirty regions and do partial refreshes. Passing status=1 also resets the bounding box.
Module-level Functions
st7789.color565(r, g, b)
color = st7789.color565(255, 128, 0)
Packs 8-bit RGB components (each 0–255) into an RGB565 integer using plain int arithmetic. No instance is needed.
st7789.map_bitarray_to_rgb565(bitarray, buffer, width, color, bg_color)
buf = bytearray(32 * 16 * 2)
st7789.map_bitarray_to_rgb565(bits, buf, 32, st7789.WHITE, st7789.BLACK)
tft.blit_buffer(buf, 0, 0, 32, 16)
Expands a 1-bit bitmap (bitarray) into an RGB565 buffer, row by row, according to width: pixels whose bit is 1 use color, and pixels whose bit is 0 use bg_color. A common use is converting a monochrome image or a custom glyph quickly into data you can pass to blit_buffer().
Common Pitfalls
| Pitfall | Cause and correct approach |
|---|---|
| Screen all white / showing noise | You forgot to call tft.init() → call init() before any drawing |
| Red and blue swapped | Color-order (RGB/BGR) mismatch → the board is already tuned by default; you only change madctl() if you wired your own panel |
| Backlight brightness won't change | tft.on() / off() don't control the backlight on this board → use PWM(Pin(11)).duty(0–1023) |
| Layout hard-coded to 135 / 240 comes out misaligned | Rotation swaps width and height → always compute from tft.width() / tft.height() |
| Chinese text shows up blank | text() uses vga1_* (covering only 0x20–0x7F) → make your own font and use write() for Chinese |
| Text becomes a black block over an image | text() is opaque and fills its background → switch to draw(), or write() with bg_tuple |
| One character is missing | That character would cross the right edge (x + WIDTH > width()) and is skipped entirely → work out the position in advance |
circle() renders as a square shadow | Wrong method: circle() draws the outline, fill_circle() fills |
The display stutters after lots of pixel() calls | Every pixel sets the window once → switch to fill_rect() / hline() / bitmap() |
OSError: out of memory after jpg() in a loop | jpg(FAST) needs 2 × width × height contiguous memory → shrink the image or switch to png() |
Memory exhausted after repeated jpg_decode() calls | The memory it allocates is never freed → decode once and call blit_buffer() repeatedly |
| Scrolling / partial refresh does nothing | You must call vscrdef() first to define the scroll area, then use bounds to collect the dirty region |
More Recipes
Drawing a dashboard-style status bar
import tft_config
import st7789
import vga2_8x16 as font
tft = tft_config.config(1) # landscape 240×135
tft.init()
W = tft.width()
tft.fill(st7789.BLACK)
tft.fill_rect(0, 0, W, 20, st7789.BLUE) # top bar
tft.text(font, "Socolode", 6, 2, st7789.WHITE, st7789.BLUE)
tft.hline(0, 20, W, st7789.WHITE)
tft.text(font, "Battery 87%", 6, 30, st7789.GREEN, st7789.BLACK)
tft.rect(6, 60, 100, 40, st7789.YELLOW) # progress frame
tft.fill_rect(8, 62, 84, 36, st7789.YELLOW) # progress bar
Centering a line of text
import NotoSans_32 as font
s = "Hello"
x = (tft.width() - tft.write_len(font, s)) // 2
y = (tft.height() - font.HEIGHT) // 2
tft.write(font, s, x, y, st7789.WHITE, st7789.BLACK)
Drawing a large title with a vector font
import romans as title_font
tft.draw(title_font, "LIGHT", 20, 30, st7789.MAGENTA, 3) # 3x scale
Vector fonts stay sharp when scaled, so they look better than bitmap fonts for large titles.
Complete Example
Put the following into /sd/apps/my-draw-app/boot.py: on boot it clears the screen, draws a centered circle and title, and cycles the color scheme with the buttons.
from button import Button
import st7789
import tft_config
import romans as title_font
COLORS = [st7789.RED, st7789.GREEN, st7789.BLUE, st7789.YELLOW]
index = 0
running = True
tft = tft_config.config(1) # landscape
tft.init()
buttons = Button()
def render():
color = COLORS[index]
w = tft.width()
h = tft.height()
tft.fill(st7789.BLACK)
tft.fill_circle(w // 2, h // 2, 40, color) # a filled circle in the middle
tft.draw(title_font, "S1", w // 2 - 18, h // 2 - 10, st7789.WHITE, 1.5)
def on_up():
global index
index = (index - 1) % len(COLORS)
render()
def on_down():
global index
index = (index + 1) % len(COLORS)
render()
def on_center_long():
global running
running = False
buttons.register_callback('up', 'short', on_up)
buttons.register_callback('down', 'short', on_down)
buttons.register_callback('center', 'long', on_center_long)
render()
while running:
pass # all rendering happens inside the button callbacks
buttons.deinit()
tft.fill(st7789.BLACK)
Troubleshooting
| Symptom | Cause / Fix |
|---|---|
| Screen stays black | Backlight duty is 0 (config(backlight=0)), or init() was never called → pass backlight=300 and call init() |
| Screen is all white | init() didn't finish, or SPI isn't connected properly → check the wiring and that config() is called only once |
| Noise / tearing on screen | SPI clock too high or a bad contact → this is the on-board 40 MHz configuration and is stable normally; with home-made cables, keep the jumper wires short |
| All colors inverted | Color-order mismatch → the board is already tuned by default; on a self-wired panel adjust the BGR bit with madctl() |
| Coordinates are all wrong after rotating | 135 / 240 hard-coded → switch to width() / height() |
| Nothing you draw is visible | You're drawing off-screen → validate coordinates with width() / height() |
OSError: out of memory | Image or font too large → shrink the asset or switch to png() / bitmap() |
OSError: buffer too small. N bytes required. | A too-small buffer_size was passed at construction → go back to the default 0 |
ValueError: must specify dc pin | You constructed st7789.ST7789 directly and forgot dc= → use tft_config.config() and you won't hit this |
| Odd behavior after creating the object twice | config() was called repeatedly → call it once per program and reuse the same tft |
Related modules: Image Display (with GIF support) · Font Library · Buzzer (beep)
AI usage (coming soon)
Soon you won't have to remember the argument order of color565 or work out centering coordinates by hand: describe the screen you want in natural language, and the Agent will follow the APIs in this document and generate a complete program that runs on the Firefly T1.
For example, just tell it:
Draw a dashboard in landscape: a blue title bar across the top, a filled circle in the middle that changes color with the buttons, and a line of status text at the bottom.
It will combine the drawing and text APIs of tft_config and st7789 into a runnable program and put it under /sd/apps/ on the SD card.
The entry link will go here. Once it is live, one click takes you straight to describing the app you want.