> For the complete documentation index, see [llms.txt](https://doc.eimtechnology.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://doc.eimtechnology.com/fe11-fundamental-ee-starter/project-1-real-time-audio-visualizer.md).

# Project 1: Real-Time Audio Visualizer

Build a Pocket Audio Oscilloscope with RP2040

## Project Overview

This project captures sound from a microphone circuit, converts the analog waveform into digital data, and displays the live signal on a TFT screen — while RGB LEDs react dynamically to the audio intensity.

{% embed url="<https://www.youtube.com/watch?v=Y-dMkLfj6jU>" %}

## Material List

Build from scratch using discrete compoents or using the PCB included in the kit. The key components required for this project is listed below:

| Component  | Description                |
| ---------- | -------------------------- |
| Controller | STEPICO / RP2040 board     |
| Sensor     | Microphone analog frontend |
| Display    | ST7789 240×240 IPS LCD     |
| LEDs       | 4× WS2812 RGB LEDs         |
| Power      | USB / onboard supply       |

## Hardware Wiring

<figure><img src="https://2117864350-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHy5TN04jkEM9s96yIKLT%2Fuploads%2FOrd06cKwBLkxOkkPe7cR%2Fproject_figure1_new.png?alt=media&amp;token=d0a59439-0eeb-4016-a26d-9cbe3ea3ebb1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2117864350-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHy5TN04jkEM9s96yIKLT%2Fuploads%2FlgT2YQhHS9ARdnBUyQvs%2Fproject_figure2_new.png?alt=media&amp;token=fa309bf6-e0e9-4b44-bd72-2e836a47acf0" alt=""><figcaption></figcaption></figure>

#### TFT Display (SPI)

| ST7789 | RP2040 |
| ------ | ------ |
| SCK    | GP10   |
| MOSI   | GP11   |
| MISO   | GP12   |
| CS     | GP13   |
| DC     | GP16   |
| RESET  | GP17   |

The display runs through SPI communication at up to 40MHz for smooth waveform refreshing.

#### Microphone Input

| Signal        | RP2040   |
| ------------- | -------- |
| Analog Output | ADC GP28 |

The ADC continuously samples the incoming audio voltage and converts it into waveform data.

#### RGB LEDs

| Device      | RP2040 |
| ----------- | ------ |
| WS2812 Data | GP23   |

Four onboard LEDs visualize the audio envelope.

## Download Code

#### Files

Upload both files to your RP2040 board.

AudioVisualizer/\
│\
├── main.py\
│\
└── st7789py.py

<mark style="color:red;">**When you copy and paste the following code into your RP2040 (e.g., using Thonny), you may notice that every line has an extra level of indentation. Since Python is indentation-sensitive, you'll need to remove this extra indentation before running the code. The quickest way to do this is to press**</mark><mark style="color:red;">**&#x20;**</mark><mark style="color:red;">**`Ctrl + A`**</mark><mark style="color:red;">**&#x20;**</mark><mark style="color:red;">**to select all the code, then press**</mark><mark style="color:red;">**&#x20;**</mark><mark style="color:red;">**`Shift + Tab`**</mark><mark style="color:red;">**&#x20;**</mark><mark style="color:red;">**once to remove the leading indentation from every line.**</mark>

{% code title="main.py" lineNumbers="true" expandable="true" %}

```py
"""
=============================================================
  RP2040 Real-Time Audio Oscilloscope + WS2812 Breathing LEDs
  Hardware: Raspberry Pi Pico + ST7789 240x240 IPS LCD
            + 4x WS2812 LEDs on GP23
=============================================================
"""

import machine
import utime
import neopixel

WIDTH  = 240
HEIGHT = 240
HALF_H = HEIGHT // 2

BLACK       = 0x0000
NEON_BLUE   = 0x051F
NEON_CYAN   = 0x07FF
WHITE       = 0xFFFF

GRID_LINE   = 0x0208
GRID_DOT    = 0x0104
CENTRE_LINE = 0x0210


class ST7789:
    def __init__(self, spi, cs, dc, rst, width=240, height=240):
        self.spi = spi
        self.cs  = cs
        self.dc  = dc
        self.rst = rst
        self.w   = width
        self.h   = height
        self._init_display()

    def _cmd(self, cmd):
        self.cs(0)
        self.dc(0)
        self.spi.write(bytes([cmd]))
        self.cs(1)

    def _data(self, data):
        self.cs(0)
        self.dc(1)
        self.spi.write(data)
        self.cs(1)

    def _init_display(self):
        self.rst(0)
        utime.sleep_ms(120)
        self.rst(1)
        utime.sleep_ms(120)

        for cmd, data, delay in (
            (0x01, None, 150),
            (0x11, None, 10),
            (0x3A, b'\x05', 0),
            (0x36, b'\x00', 0),
            (0xB2, b'\x0C\x0C\x00\x33\x33', 0),
            (0xB7, b'\x35', 0),
            (0xBB, b'\x19', 0),
            (0xC0, b'\x2C', 0),
            (0xC2, b'\x01', 0),
            (0xC3, b'\x12', 0),
            (0xC4, b'\x20', 0),
            (0xC6, b'\x0F', 0),
            (0xD0, b'\xA4\xA1', 0),
            (0x29, None, 0),
        ):
            self._cmd(cmd)
            if data:
                self._data(data)
            if delay:
                utime.sleep_ms(delay)

    def _set_window(self, x0, y0, x1, y1):
        self._cmd(0x2A)
        self._data(bytes([x0 >> 8, x0 & 0xFF, x1 >> 8, x1 & 0xFF]))

        self._cmd(0x2B)
        self._data(bytes([y0 >> 8, y0 & 0xFF, y1 >> 8, y1 & 0xFF]))

        self._cmd(0x2C)

    def fill_rect(self, x, y, w, h, color):
        if w <= 0 or h <= 0:
            return

        self._set_window(x, y, x + w - 1, y + h - 1)

        hi = color >> 8
        lo = color & 0xFF
        chunk = bytearray([hi, lo] * 64)

        total = w * h * 2
        sent = 0

        self.cs(0)
        self.dc(1)

        while sent < total:
            n = min(128, total - sent)
            self.spi.write(chunk[:n])
            sent += n

        self.cs(1)

    def pixel(self, x, y, color):
        if x < 0 or x >= self.w or y < 0 or y >= self.h:
            return

        self._set_window(x, y, x, y)

        self.cs(0)
        self.dc(1)
        self.spi.write(bytes([color >> 8, color & 0xFF]))
        self.cs(1)

    def vline(self, x, y0, y1, color):
        if y0 > y1:
            y0, y1 = y1, y0

        if y0 < 0:
            y0 = 0
        if y1 >= self.h:
            y1 = self.h - 1

        self.fill_rect(x, y0, 1, y1 - y0 + 1, color)


# ──────────────────────────────────────────────
# Hardware
# ──────────────────────────────────────────────
spi = machine.SPI(
    1,
    baudrate=40_000_000,
    polarity=0,
    phase=0,
    sck=machine.Pin(10),
    mosi=machine.Pin(11),
    miso=machine.Pin(12),
)

cs  = machine.Pin(13, machine.Pin.OUT, value=1)
dc  = machine.Pin(16, machine.Pin.OUT)
rst = machine.Pin(17, machine.Pin.OUT)

adc = machine.ADC(28)

display = ST7789(spi, cs, dc, rst)


# ──────────────────────────────────────────────
# WS2812 Breathing Audio LEDs
# ──────────────────────────────────────────────
LED_PIN   = 23
LED_COUNT = 4

np = neopixel.NeoPixel(machine.Pin(LED_PIN), LED_COUNT)

led_phase = 0
led_env   = 0
led_peak  = 8


def wheel(pos):
    pos = pos % 256

    if pos < 85:
        return (255 - pos * 3, pos * 3, 0)
    elif pos < 170:
        pos -= 85
        return (0, 255 - pos * 3, pos * 3)
    else:
        pos -= 170
        return (pos * 3, 0, 255 - pos * 3)


def update_leds(amplitude):
    global led_phase, led_env, led_peak

    # Auto-gain peak tracking
    if amplitude > led_peak:
        led_peak = amplitude
    else:
        led_peak = (led_peak * 995) // 1000

    if led_peak < 6:
        led_peak = 6

    # Normalize amplitude to 0~255
    level = (amplitude * 255) // led_peak

    if level > 255:
        level = 255

    # Fast attack, slow release
    if level > led_env:
        led_env = (led_env * 3 + level) // 4
    else:
        led_env = (led_env * 14 + level) // 15

    # Breathing brightness curve
    brightness = (led_env * led_env) // 255

    # Strong dimming
    brightness = brightness // 8

    if brightness < 1:
        brightness = 1

    if brightness > 18:
        brightness = 18

    # Louder sound = slightly faster colour breathing
    led_phase = (led_phase + 1 + led_env // 70) % 256

    r, g, b = wheel(led_phase)

    r = (r * brightness) // 255
    g = (g * brightness) // 255
    b = (b * brightness) // 255

    for i in range(LED_COUNT):
        np[i] = (r, g, b)

    np.write()


def clear_leds():
    for i in range(LED_COUNT):
        np[i] = (0, 0, 0)
    np.write()


# ──────────────────────────────────────────────
# Grid
# ──────────────────────────────────────────────
H_DIVS = 6
V_DIVS = 6

CELL_W = WIDTH  // H_DIVS
CELL_H = HEIGHT // V_DIVS

SUB_W = CELL_W // 4
SUB_H = CELL_H // 4


def grid_color_at(x, y):
    if y == HALF_H:
        return CENTRE_LINE

    if y % CELL_H == 0 and 0 < y < HEIGHT - 1:
        return GRID_LINE

    if x % CELL_W == 0 and x > 0:
        return GRID_LINE

    if x % SUB_W == 0 and y % SUB_H == 0:
        return GRID_DOT

    return BLACK


def draw_full_grid():
    display.fill_rect(0, 0, WIDTH, HEIGHT, BLACK)

    for row in range(1, V_DIVS):
        y = row * CELL_H
        c = CENTRE_LINE if y == HALF_H else GRID_LINE
        display.fill_rect(0, y, WIDTH, 1, c)

    display.fill_rect(0, HALF_H, WIDTH, 1, CENTRE_LINE)

    for col in range(1, H_DIVS):
        display.fill_rect(col * CELL_W, 0, 1, HEIGHT, GRID_LINE)

    for y in range(0, HEIGHT, SUB_H):
        for x in range(0, WIDTH, SUB_W):
            if grid_color_at(x, y) == GRID_DOT:
                display.pixel(x, y, GRID_DOT)


# ──────────────────────────────────────────────
# ADC
# ──────────────────────────────────────────────
def read_centered():
    return adc.read_u16() - 32768


def sample_pixel_offset():
    raw = (
        read_centered()
        + read_centered()
        + read_centered()
        + read_centered()
    ) >> 2

 # If the microphone signal is too weak, reduce the value from 32768.
# For example: 16384 increases the sensitivity, and 8192 makes it even more sensitive.
    offset = (raw * (HALF_H - 4)) // 32768

    return max(-(HALF_H - 4), min(HALF_H - 4, offset))


# ──────────────────────────────────────────────
# Main loop
# ──────────────────────────────────────────────
ERASE_WIDTH = 3


def run():
    draw_full_grid()
    clear_leds()

    prev_y = HALF_H
    x = 0

    while True:
        erase_col = (x + ERASE_WIDTH) % WIDTH

        display.fill_rect(erase_col, 0, 1, HEIGHT, BLACK)

        if erase_col % CELL_W == 0:
            display.fill_rect(erase_col, 0, 1, HEIGHT, GRID_LINE)
        else:
            for dy in range(0, HEIGHT, SUB_H):
                if dy % CELL_H != 0 and dy != HALF_H:
                    display.pixel(erase_col, dy, GRID_DOT)

            for row in range(1, V_DIVS):
                display.pixel(erase_col, row * CELL_H, GRID_LINE)

        display.pixel(erase_col, HALF_H, CENTRE_LINE)

        offset = sample_pixel_offset()
        curr_y = HALF_H - offset

        update_leds(abs(offset))

        color = NEON_CYAN if abs(offset) > (HALF_H * 2 // 3) else NEON_BLUE

        display.vline(x, prev_y, curr_y, color)
        display.pixel(x, curr_y, WHITE)

        prev_y = curr_y
        x = (x + 1) % WIDTH


print("Oscilloscope starting...")
print("WS2812 breathing LEDs on GP23.")
print("Speak, blow, or play music into the microphone!")

run()
```

{% endcode %}

{% code title="st7789py.py" lineNumbers="true" expandable="true" %}

```py
import time
import struct
import machine

class ST7789:
    def __init__(self, spi, width, height, reset, dc, cs=None, backlight=None, rotation=0):
        self.spi = spi
        self.width = width
        self.height = height
        self.reset = reset
        self.dc = dc
        self.cs = cs
        self.backlight = backlight
        
        self.reset.init(self.reset.OUT, value=1)
        self.dc.init(self.dc.OUT, value=0)
        if self.cs: self.cs.init(self.cs.OUT, value=1)
        
        self.hard_reset()
        self.init()

    def write(self, command, data=None):
        if self.cs: self.cs.off()
        self.dc.off()
        self.spi.write(bytearray([command]))
        if data:
            self.dc.on()
            self.spi.write(data)
        if self.cs: self.cs.on()

    def init(self):
        for cmd, data, delay in [
            (0x01, None, 150), (0x11, None, 255), (0x3A, b'\x55', 10),
            (0x36, b'\x00', 0), (0x2A, b'\x00\x00\x00\xEF', 0),
            (0x2B, b'\x00\x00\x00\xEF', 0), (0x21, None, 10),
            (0x13, None, 10), (0x29, None, 255)]:
            self.write(cmd, data)
            if delay > 0: time.sleep_ms(delay)

    def hard_reset(self):
        self.reset.on()
        time.sleep_ms(50)
        self.reset.off()
        time.sleep_ms(50)
        self.reset.on()
        time.sleep_ms(150)

    def set_window(self, x0, y0, x1, y1):
        self.write(0x2A, struct.pack(">HH", x0, x1))
        self.write(0x2B, struct.pack(">HH", y0, y1))
        self.write(0x2C)

    def fill(self, color):
        self.set_window(0, 0, self.width-1, self.height-1)
        chunk = struct.pack(">H", color) * self.width
        self.dc.on()
        if self.cs: self.cs.off()
        for _ in range(self.height):
            self.spi.write(chunk)
        if self.cs: self.cs.on()

    def pixel(self, x, y, color):
        self.set_window(x, y, x, y)
        self.write(0x2C, struct.pack(">H", color))

    def fill_rect(self, x, y, w, h, color):
        self.set_window(x, y, x + w - 1, y + h - 1)
        chunk = struct.pack(">H", color) * w
        self.dc.on()
        for _ in range(h):
            self.spi.write(chunk)
```

{% endcode %}

## Run the Project

1. Install MicroPython firmware
2. Open Thonny IDE
3. Connect your RP2040 board
4. Upload files
5. Run:

```
main.py
```

You should see:

```
Oscilloscope starting...
WS2812 breathing LEDs on GP23.Speak, blow, or play music into the microphone!
```

## Customize Your Project

#### Change waveform sensitivity

Inside:

```
offset = (raw * (HALF_H - 4)) // 32768
```

Increase sensitivity:

```
32768 → 16384 → 8192
```

Smaller number = larger waveform.

#### Change LED behavior

Modify:

```
LED_COUNT = 4
```

for different LED numbers.

Adjust brightness:

```
brightness = brightness // 8
```
