Fantastical Project Built with MCU, TFT Display and LVGL Graphics
Dungeons and Dragons is a complex, fantasy role-playing game, in which various players roll polyhedral dice with 4 to 20 faces to determine outcomes at various decision points. Andrew describes an electronic device he created to simulate rolling the dice using a Raspberry Pi RP2040 MCU, a TFT with touchscreen to show the rolling dice and display the scores from each roll, and an STM amplifier to add the element of drama with sound effects.
My daughter is a big fan of Dungeons and Dragons, the fantasy role-playing game. This game has been around since the 1970s but has become hugely popular during the last few years. One of the key aspects of the game mechanics is the use of polyhedral dice to decide the outcome at various decision points. A typical set of dice, shown in Figure 1, includes seven dice. Six with 4, 6, 8, 10, 12, or 20 faces (designated D4, D6, and so on), along with a second, 10-faced die, the “percent” die. As the name suggests, the “D%” die is used together with the D10 to get a score ranging from 1 to 100 percent; one die gives the tens digit and the other gives the ones digit.

Playing Dungeons and Dragons requires the use of a set of polyhedral dice like these. For serious players, the die rolling experience is integral to the enjoyment of the game, and many beautifully crafted and decorated sets are available.
There is sometimes a requirement for a Yes/No decision. This can be done in various ways – for example by using a D6 and designating odd numbers to indicate a No and even numbers a Yes, or by using a special coin-like token. There is frequently the requirement to roll several dice and use the sum of their values to determine game outcomes.
If you look online, you will see that a plethora of beautifully decorated D&D dice sets are available. The die-rolling experience is an integral part of the enjoyment of the game, and the dedicated D&D aficionado will have several sets to choose from.
Of course, the electronics engineer in me saw an opportunity to make an electronic die roller, which should have been a simple project. It soon became apparent that matching the experience of physical dice would require something a bit special. This project is the result.
First, I wanted the aesthetics of the user interface to reflect the fantastical nature of the game, so a modern touchscreen graphical user interface with suitable artwork was mandatory. This would allow for some effects reminiscent of a real die roll. Second, I wanted to do something to make the sensory experience as engaging as using physical dice. For this, I elected to provide a range of sound effects that I think achieve the desired result nicely.
HARDWARE
With the above requirements in mind, I embarked on the hardware design. The schematic diagram for the project is shown in Figure 2. I chose the Raspberry Pi RP2040 microcontroller [1] for this project. This is a low-cost micro with two Arm Cortex M0+ cores. The RP2040 does not have an on-board flash memory, but instead uses an external QSPI flash memory. This allowed me to use a 16MB flash, which has plenty of room for the program plus a bunch of graphical images, fonts and sound files.

The hardware for this project is fairly simple. A Raspberry Pi RP2040 microcontroller with an external flash memory and an integrated USB port does all the heavy lifting. The only external peripherals are a touchscreen display and simple audio amplifier. A battery charger and switching regulator complete the hardware line-up.
The display, a 4D Systems 4DLCD-32QA 3.2” 320 x 240 TFT with touchscreen connects to the board via a 40-pin, flat-flex connector, J1. The display has an on-board IL9341 controller with a 16-bit parallel interface. The backlight is driven with a PWM signal from the MCU via MOSFET Q1 and current-limiting resistor R1. The resistive touchscreen is connected to four of the MCU’s analog-capable I/O pins, GPIO26 through GPIO29.
A micro-USB port, J3, is provided for charging and to allow the firmware to be updated using the RP2040’s “USB Boot” functionality. If the “Boot” switch (SW2) is closed at power-on, the MCU enters USB Boot mode where it appears as a disk drive on the host computer. Copying the .uf2 firmware file into this drive is all that is necessary to reprogram the microcontroller. This file can be downloaded from the Circuit Cellar Article Code and Files webpage. The USB port is also used as a virtual serial port to output debugging information.
I also added a single-wire debug (SWD) port on connector J2. This is handy for development, because it allows the use of a debugger to step through the code and see what’s going on deep inside the MCU. I also provided a Reset switch, SW1, and fault indicator LED1. Both are useful during code development. The flash memory is connected to the RP2040’s dedicated QSPI port.
Audio is output as a PWM signal on GPIO25. This is filtered by R10 and C13, then AC coupled via C14 into the audio amplifier chip U5. This is a STMicroelectronics TS4990 1.2W amplifier [2], the block diagram of which is shown in Figure 3. One side of the speaker (Vout 1) is driven by an internal inverting power op amp referenced to a mid-supply bias voltage, which appears on the Bypass pin.
![Figure 3
The TS4990 audio amplifier drives an 8Ω speaker with a peak-to-peak voltage of up to 6V, using a bridge arrangement, with just a single-ended 3.3V supply. This is done by driving each side of the speaker with identical signals that are 180˚ out of phase. Source: STMicroelectronics [2].](https://i0.wp.com/circuitcellar.com/wp-content/uploads/2025/05/412-Levido_Figure3.jpg?resize=810%2C554&ssl=1)
The TS4990 audio amplifier drives an 8Ω speaker with a peak-to-peak voltage of up to 6V, using a bridge arrangement, with just a single-ended 3.3V supply. This is done by driving each side of the speaker with identical signals that are 180˚ out of phase. Source: STMicroelectronics [2].
The gain of this amplifier is set to unity by the ratio of R13 and R12, which are both 100kΩ. The other side of the speaker (Vout 2) is driven by a second power op amp with an identical, but inverted, signal. This doubles the peak-to-peak voltage that can be produced across the speaker. The speaker is mounted on the case back and is connected to the board by the two-pin connector, J5.
Power is provided by single LiPo cell connected to J4. This is charged from the 5V USB power rail via U3. This is an MCP73831 linear LiPo charge management chip. It provides a three-stage charging process – preconditioning, constant current and then constant voltage as the cell approaches full charge. The constant current charge level is set to around 210mA by resistor R6, and the state of charge is indicated by LED2. This LED is on when the cell is charging in any of the three modes, and off when the cell is fully charged.
The USB voltage and the battery voltage are diode OR’ed by the dual Schottky diode pair, D1. Since the battery voltage is never higher than 4.2V, the USB voltage will be selected if it is available. The battery will charge at the same time.
After passing through the power switch (SW3), the supply voltage, which can be anywhere in the range of 3.2V to 5V, is passed to U4, as RT6150A buck/boost regulator. This neat device can accept an input voltage in the range 1.8V to 5.5 V and produce a regulated output voltage between 2.5V and 5.5 V, programmable by the divider consisting of R14 and R15. The values shown give an output voltage of 3.3V. LED 3 indicates that power is available.
FIRMWARE
That’s all there is to the hardware. Obviously, most of the complexity is in the firmware. Figure 4 is a block diagram of the firmware architecture. At the bottom is a series of drivers for the LCD, touchscreen, and audio hardware. A USB driver, provided as part of the RP2040 SDK, is used to send error and debug information to a terminal program to aid debugging.
![Figure 4
The firmware architecture has three levels. At the bottom are drivers for the LCD display, touchscreen, audio playback, and the USB device interface. Above this is a middleware layer to manage the user interface, based on the open-source LVGL graphics library [3]. A simple state machine makes up the application layer. The LVGL and USB code is provided by third parties; the rest is custom to the D&D Roller.](https://i0.wp.com/circuitcellar.com/wp-content/uploads/2025/05/412-Levido_Figure4.jpg?resize=810%2C390&ssl=1)
The firmware architecture has three levels. At the bottom are drivers for the LCD display, touchscreen, audio playback, and the USB device interface. Above this is a middleware layer to manage the user interface, based on the open-source LVGL graphics library [3]. A simple state machine makes up the application layer. The LVGL and USB code is provided by third parties; the rest is custom to the D&D Roller.
The user interface, built around the LVGL graphics library [3], takes care of displaying items on the screen and detecting touch events. The user interface assets, such as images, fonts, and audio files, are stored in the flash memory. The overall application logic is managed by a simple state machine that processes events such as on-screen button presses to produce the desired behaviour.
All of this firmware runs on just one of the RP2040’s two cores. The other is unused.
Let’s look at these blocks one at a time.
LCD Driver: The LCD driver interfaces to the display via a 16-bit digital interface and a handful of control lines. One of these, the nCMD signal, is used to tell the LCD controller whether the data presented on the bus is pixel data or a command. The driver only ever writes to the display so the nRD line is always held high. Since there is nothing on the bus except the display, the chip-select line, nCS, is always asserted (low). The reset line is toggled on initialization, to ensure the LCD is in its default state before it is used.
The driver therefore really only has to place the data on the bus and manage the states of the nCMD and nWrite control lines. I used the RP2040’s Programmable I/O (PIO) functionality to implement this. The PIO allows the user to write small assembler-like programs that manipulate I/O in a fast, deterministic manner to implement custom I/O peripherals. These are powerful and flexible, and well worth taking a close look at if you have not done so already. Without going into all the details, a six-line program is all that’s needed to implement the following behaviour.
Initially the PIO state machine is stalled waiting for the user to write one or more 16-bit data words into the transmit FIFO. At this time, the nCMD and nWR pins are maintained in a high state. When data is written to the FIFO, it is placed on the bus one word at a time, and the nWR line is pulsed low each time to latch the data into the LCD controller. If the PIO state machine’s scratch register Y is non-zero, the PIO state machine also pulses the nCMD low, signalling a command is being transmitted.
The user program (the LCD driver) just has to push data into the FIFO and set or clear the scratch register, to indicate whether it should be interpreted as pixel data or commands. The PIO takes care of the rest.
The display driver is also responsible for configuring the display – in our case for landscape operation with 16-bit (RGB565) color depth. It also controls the display backlight via one of the PR2040’s PWM peripherals. Finally, the driver provides a function to write a buffer-full of pixel data to a specified region on the display. We need this to provide a means for the LVGL library to write its display buffer to the screen.
Touchscreen Driver: The display is equipped with a resistive touchscreen. Figure 5 illustrates how this is read by the driver. These screens consist of two transparent plastic membranes separated by a small air gap, each coated in a transparent resistive material. One layer has electrodes on the vertical edges, forming a horizontal resistor (shown in red), and the other has them on the horizontal edges forming a vertical resistor (shown in green). When the screen is touched, the two layers come into contact, forming two connected voltage dividers. The relative resistances of the two legs of the dividers are determined by the x and y position of the touch point.

This diagram shows how the firmware reads the touchscreen. As shown at the bottom left, it initially checks if a touch has occurred by reading the digital input connected to the YU terminal. If it detects a touch, its x and y coordinates are determined by reading the ADC values, as shown in the middle and right of the diagram.
Most of the time the touchscreen driver connects the micro to the four terminals as shown at the bottom left. Both electrodes of the horizontal divider (XR an XL) are driven high. The YD electrode is left open, and the YU electrode is monitored by a digital input with an integral pull-down resistor. This digital input will therefore read low if the screen is not touched, and high if it is.
Thus, the driver can quickly determine whether a touch has occurred. If it detects one, the x and y coordinates are read sequentially. To read the x-coordinate, the electrodes are configured as shown in the middle diagram. The YD terminal is left open, and the YU terminal is connected to the ADC, which reads the voltage on the x-axis divider.
Similarly, the y-coordinate is determined by reading the voltage on the y-axis divider, using the configuration shown at the bottom right. The driver calculates the coordinate of the touch in pixels from these two voltage levels, using the display’s horizontal and vertical resolution.
Audio Driver: I wanted to keep the audio player as simple as possible, so I chose to use 8-bit PCM-encoded, mono audio at 11.025 ksps as the format for the audio data. This combination gives a good balance between the size of the audio arrays and sound quality. It is commonly used in .wav files, so its pretty easy to convert any file to the required format using one of the many online converters. We only use the data chunk (yes, that’s what it’s called) from the .wav file stored in a simple C-language byte array.
The driver plays each sample four times (4x oversampling), so the PWM frequency is four times the sample rate (44.1kHz). This makes it practical to use a simple RC filter to reconstruct the audio from the PWM signal.
Playback is initiated by calling a driver function, which opens the PWM channel and plays out the first sample before returning immediately. The balance of the samples are played out under interrupt control. Unfortunately, we can’t use DMA to do this, since there is a weird limitation in the RP2040 DMA, in that it can’t be used to transfer 8-bit data to the PWM peripheral.
User Interface: As mentioned earlier, the user interface takes advantage of the LVGL graphics library. LVGL [3], which stands for Light and Versatile Graphics Library, is a free, open-source library with a lot of features. It allows you to create fancy graphical interfaces with various buttons, sliders, checkboxes, and much more. You can use it with simple mono LCD displays, or build a fully-fledged smartphone-like application, complete with animations and transparency.
Most of the user interface heavy lifting is taken care of via the library, so the user just has to specify what elements (called “widgets”) appear where and on what screens, and how they should behave. You can use the built-in defaults, or provide your own images for things like buttons, or add fancy fonts as required.
The D&D Die Roller application consists of just two screens – a splash screen that appears briefly when the unit is first powered up. Shown in Figure 6, this screen shows the project name and some software version information.

The splash screen is based on an image I created using a drawing program. The text at the bottom of the screen is a label created at run time using an open-source TrueType font. The images and fonts are converted to C arrays, which are stored in the flash memory.
The base artwork was created in a drawing program and exported as a .png file, which was then converted to a C file by LVGL’s conversion utility. The version information is a text label placed on the base image at run-time, in a font that was similarly converted from a TrueType font file to a C file.
After a few seconds (and a little tune) the splash screen transitions to the second screen – the main screen shown in Figure 7. This has eight die buttons, which initiate rolls and a display of results on the right. In the middle is the result of the most recent roll (19 in this case). Above this is a roll history, showing that the last roll, the fourth in the series, was of a D20 die. The previous dice rolled, and the result are listed above this.

This is the main screen of the D&D Roller. The eight die buttons on the left use images I created off-line. The green panel shows the roll history, and the panel immediately below it shows the result of the last roll. Finally, a running total is maintained at the bottom right.
A running total of dice rolled is maintained in the bottom right of the screen. This display is also a button which, if pressed, resets the running total and clears the history.
Two images are associated with each button – the one you see here when the button is in its “unpressed” state and another, which is shown when it is pressed. This provides some positive visual feedback to the user. As before, all of the button images and the font assets are converted to C arrays, which get stored in the flash memory.
I added a little theatre to the process of rolling the die. Of course, the result of any roll is a random number between 1 and the maximum of that die. Generating random(ish) numbers in software takes just a few microseconds, but it would be pretty boring if the result were returned the instant that the button was pressed.
Instead, each time a roll is requested, a series of 10 random results is displayed, one after another. Initially, the delay between them is short, but it gradually lengthens, simulating in a simple way the ballistics of a rolling die. The entire roll takes about 2.5 seconds to settle on the final result and is accompanied by audio of a drum-roll.
To further increase the dramatics, if the result is the maximum number the die can produce, a “triumphant” sound is emitted. Conversely, if a 1 is rolled, a “failure” sound is played. The color of the result area’s background also changes – turning green for a maximum score and red for a 1.
State Machine: The logic of the D&D Die Roller is managed by an event-driven state machine. This has just three states: Uninitialized, Idle, or Rolling. The unit starts in the Uninitialized state, while the splash screen is displayed and some initial values are established, before transitioning to the Idle state as the main screen is displayed.
Once in the Idle state, any roll event, created by pressing one of the eight roll buttons, will start a roll sequence and trigger a transition to the Rolling state. The state machine also responds to the event generated when the running total is pressed by resetting the total and the roll history.
In the Rolling state, the roll sequence is displayed as described above, and the final result is added to the running total and to the roll history. When all this is done the state transitions back to Idle.
BUILDING IT
Physically, the D&D Die Roller is housed in a small, handheld enclosure, as shown in Figure 8. The front is dominated by a large cutout for the display, and the on/off switch and USB connector are on the end panel.

The D&D Roller is housed in a small, handheld case. The top is dominated by the opening for the display. The on/off switch and the USB port are visible on the end panel.
The PCB is mounted to the underside of the lid, with the display sandwiched between them. The display flat-flex cable emerges through a slot in the board and plugs into the connector on the component side. Everything except the speaker is mounted on this board, including the battery which is held in place with double-sided tape. Figure 9 shows the general arrangement.
— ADVERTISMENT—
—Advertise Here—

Everything except the speaker is mounted on the PCB as shown here. The battery is mounted to the board using double-sided tape. You can see the display flat-flex cable emerging from its slot and plugged into the 40-pin connector.
Building it was straightforward. I ordered a frameless solder stencil with my PCBs, and used this to apply solder paste to the pads on the board. The components were placed carefully, and the whole lot reflow soldered in a small toaster oven I reserve for this purpose. After the few through-hole components were soldered in, the board was ready for programming and testing.
Probably the most difficult part of the exercise was cutting the hole in the case for the display. To do this I first covered the front face of the box with masking tape. This allowed me to clearly mark the aperture and also protected the front of the case from scratches while I was working on it.
I then chain-drilled a series of 3mm holes inside, but as close as I dared to the marked line. I then used a hobby knife to join the holes and files to carefully open the hole up to the lines I had marked. It’s worth taking some care with this step, particularly in the corners, since its all too easy to overcut something and there is no going back.
Once this was done, I marked another set of lines about 3mm outside the first and used these as a guide to file a chamfer around the opening, purely for aesthetics. After a bit of smoothing with some fine sandpaper, I was pretty happy with the result. It’s not perfect, but it looks good enough from the normal operating distance.
In contrast, cutting the rectangular and trapezoidal holes in the end plate was a walk in the park! Finally, I drilled a pattern of 3mm holes in the enclosure bottom for the sound to escape. The speaker was hot glued to the bottom of the case over these holes. I also added adhesive rubber feet to raise the bottom of the case a few millimeters off the table to help with the sound.
The LCD was attached to the non-component side of the PCB with double sided tape as shown in Figure 10. I needed to juggle the position of the display to make sure the active display area was aligned with the opening. The speaker and battery wires were fitted with the appropriate connectors and plugged in, and the job was done.

This view shows the “back” side of the board, where the display is mounted with double-sided tape. Position this carefully before finally affixing, so the active area of the display is centered exactly inside the opening in the case.
CONCLUSION
I thought I had done a nice job with this project, but the real test was whether my daughter would approve. Fortunately, she was very pleased, and the D&D Die Roller has taken pride of place in her D&D bag. I can’t vouch for how much use it gets compared to the physical dice, but that’s not really the point is it?
RESOURCES
Raspberry Pi | www.raspberrypi.com
ST Microelectronics | www.st.com
LVGL | lvgl.io
REFERENCES
[1] “RP2040 Datasheet.” Accessed August 5, 2024. https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf
[2] “TS4990 – 1.2 W Audio Power Amplifier with Active Low Standby Mode – STMicroelectronics.” Accessed August 5, 2024. https://www.st.com/en/audio-ics/ts4990.html
[3] “LVGL — Light and Versatile Embedded Graphics Library.” Accessed August 5, 2024. https://lvgl.io/
PUBLISHED IN CIRCUIT CELLAR MAGAZINE • NOVEMBER 2024 #412 – Get a PDF of the issue
Sponsor this ArticleAndrew Levido (andrew.levido@gmail.com) earned a bachelor’s degree in Electrical Engineering in Sydney, Australia, in 1986. He worked for many years in R&D for power electronics and telecommunication companies, before moving into management roles. Andrew has maintained a hands-on interest in electronics, particularly embedded systems, power electronics and analog design. Over the years, he has written articles for various electronics publications, and provides consulting services as time allows.
