AdvancedExperimental Lab

Real-Time Brainwave Visualizer

Visualise brainwaves (Alpha, Beta, Theta) in real time with sample data or a compatible EEG headset.

Time
3–4 h with sample data; extra sessions with a headset
Estimated cost
Free with sample data · EEG headset not included
Hardware
Python 3.10+ · optional ESP32 feedback

Experimental — educational only

Try it in the browser

What you will build

A live dashboard on your computer that shows raw EEG traces per channel, a signal-quality warning per channel, and bars for Theta (4–8 Hz), Alpha (8–13 Hz) and Beta (13–30 Hz) band power. It starts with built-in synthetic data, so everyone can build it, then switches to a real headset with one line of code. An optional ESP32 light bar mirrors the Alpha level.

How it works

EEG headsets measure microvolt-level electrical activity at the scalp. BrainFlow, an open-source library, reads data from many commercial headsets (and a synthetic board) through one API. Every second the Python app takes the last 4 seconds of data, filters out mains hum (50 Hz in the UK) and slow drift, and computes the average power in each frequency band. The numbers are relative: they change with electrode contact, blinking, jaw clenching and movement as much as with brain state.

Stage Runs on Notes
Signal acquisition Commercial EEG headset Isolated, battery-powered, manufacturer electrodes
Filtering + band power Python (BrainFlow) 4 s window, 1 s update, 50 Hz notch
Visualisation Python (matplotlib) or browser Source label always visible
Optional feedback ESP32 + LED bar over USB Receives numbers only, never touches electrodes

Parts

Part Qty Purpose Required
Computer with Python 3.10+ 1 Processing and display Yes
EEG headset supported by BrainFlow (e.g. OpenBCI Ganglion/Cyton, Muse 2/S) 1 Real signals For live mode
ESP32-DevKitC V4 + 8-LED WS2812B stick + USB cable 1 Light-bar feedback Optional

Check BrainFlow's current supported-boards list and the headset's own data-access terms before buying.

Build steps

  1. pip install brainflow numpy matplotlib pyserial.
  2. Run brainwaves.py as it is. It uses BrainFlow's synthetic board; the window title says SYNTHETIC DATA.
  3. Checkpoint: four traces scroll, the three bars update once per second, and units are shown.
  4. Read the headset manual: fit it, check contact quality in the maker's own app first.
  5. Change BOARD to your headset's BrainFlow ID and set serial_port or mac_address if needed. The title changes to LIVE EEG — [device].
  6. Experiment: sit still, eyes open for 30 s, then eyes closed for 30 s. Many people see Alpha rise with eyes closed. Now blink hard and clench your jaw: see how much larger these artefacts are than brain signals.
  7. Optional light bar: WS2812B DIN → GPIO 26, 5V → VIN, GND → GND. Upload the ESP32 sketch, run with --esp COM5 (or /dev/ttyUSB0).

Try it in the browser

Demo Mode. Compare simulated eyes-open and eyes-closed sessions. The bars show synthetic values for Alpha, Beta and Theta, with no headset connection and no personal brain activity.

Code

Python dashboard.

Download brainwaves.py

# brainwaves.py — XBOTNOW · Educational only, not a medical device.
# pip install brainflow numpy matplotlib pyserial
import argparse, numpy as np, matplotlib.pyplot as plt
from brainflow.board_shim import BoardShim, BrainFlowInputParams, BoardIds
from brainflow.data_filter import DataFilter, DetrendOperations, FilterTypes

BOARD = BoardIds.SYNTHETIC_BOARD          # change to your headset's ID for live mode
WINDOW_S = 4

ap = argparse.ArgumentParser(); ap.add_argument("--esp"); args = ap.parse_args()
esp = None
if args.esp:
    import serial; esp = serial.Serial(args.esp, 115200)

params = BrainFlowInputParams()           # set params.serial_port / mac_address if needed
board = BoardShim(BOARD.value, params)
board.prepare_session(); board.start_stream()
fs = BoardShim.get_sampling_rate(BOARD.value)
chans = BoardShim.get_eeg_channels(BOARD.value)[:4]
source = "SYNTHETIC DATA" if BOARD == BoardIds.SYNTHETIC_BOARD else f"LIVE EEG — {BOARD.name}"

plt.ion()
fig, (ax_raw, ax_bands) = plt.subplots(2, 1, figsize=(9, 7))
fig.suptitle(f"{source} · educational only")
bands = {"Theta": (4, 8), "Alpha": (8, 13), "Beta": (13, 30)}

def band_power(sig, lo, hi):
    freqs = np.fft.rfftfreq(len(sig), 1 / fs)
    psd = np.abs(np.fft.rfft(sig * np.hanning(len(sig)))) ** 2
    return psd[(freqs >= lo) & (freqs < hi)].mean()

try:
    while plt.fignum_exists(fig.number):
        data = board.get_current_board_data(WINDOW_S * fs)
        if data.shape[1] < WINDOW_S * fs:
            plt.pause(0.5); continue
        powers = {b: [] for b in bands}
        ax_raw.clear()
        for i, ch in enumerate(chans):
            sig = data[ch].copy()
            DataFilter.detrend(sig, DetrendOperations.CONSTANT.value)
            DataFilter.perform_bandstop(sig, fs, 48.0, 52.0, 4, FilterTypes.BUTTERWORTH.value, 0)  # UK mains
            DataFilter.perform_bandpass(sig, fs, 1.0, 40.0, 4, FilterTypes.BUTTERWORTH.value, 0)
            flat = np.std(sig) < 0.5; saturated = np.max(np.abs(sig)) > 500
            label = f"ch{i+1}" + (" ⚠ flat" if flat else " ⚠ saturated" if saturated else "")
            ax_raw.plot(np.arange(len(sig)) / fs, sig + i * 150, lw=0.7, label=label)
            for b, (lo, hi) in bands.items():
                powers[b].append(band_power(sig, lo, hi))
        ax_raw.set_xlabel("seconds"); ax_raw.set_ylabel("µV (offset per channel)")
        ax_raw.legend(loc="upper right", fontsize=8)

        rel = np.array([np.mean(powers[b]) for b in bands]); rel = rel / rel.sum()
        ax_bands.clear(); ax_bands.bar(list(bands), rel * 100)
        ax_bands.set_ylim(0, 100); ax_bands.set_ylabel("relative band power (%)")
        if esp:
            esp.write(f"{int(rel[1] * 100)}\n".encode())   # Alpha % to the light bar
        plt.pause(1.0)
finally:
    board.stop_stream(); board.release_session()

Optional ESP32 light bar. Library: Adafruit NeoPixel.

Download brainwave-light-bar.ino

// Brainwave light bar — XBOTNOW · receives a 0–100 number per line
#include <Adafruit_NeoPixel.h>
const int PIN = 26, N = 8;
Adafruit_NeoPixel bar(N, PIN, NEO_GRB + NEO_KHZ800);
unsigned long lastData = 0;

void setup() { Serial.begin(115200); bar.begin(); bar.setBrightness(30); bar.show(); }

void loop() {
  if (Serial.available()) {
    int pct = constrain(Serial.parseInt(), 0, 100);
    int lit = map(pct, 0, 100, 0, N);
    for (int i = 0; i < N; i++) bar.setPixelColor(i, i < lit ? bar.Color(80, 60, 255) : 0);
    bar.show(); lastData = millis();
  }
  if (millis() - lastData > 3000) { bar.clear(); bar.show(); }   // no data: lights off
}

Troubleshooting

Symptom Likely cause Check
BrainFlowError on start Wrong board ID, port or MAC Check BrainFlow docs for your device's parameters
Channel shows ⚠ flat Poor contact or disconnected Re-seat the headset; check the maker's contact app
Huge spikes Blinks, jaw, movement Sit still and relaxed; these are artefacts, not "brain events"
Strong 50 Hz noise Mains interference Run the laptop on battery, away from chargers

Safety and limitations

Educational only. This project does not measure or diagnose attention, stress, sleep, emotion or any medical or neurological condition, and band-power bars must never be presented that way. Use only commercially made, battery-powered EEG devices used as their manufacturer instructs. Never connect electrodes to an ESP32, Arduino, or any homemade or mains-connected circuit. Do not use with people who have epilepsy or implanted medical devices without medical advice. Always label data as synthetic, recorded or live.

Checklist

Next project

Coming soon: Brain-Controlled Ambient Light: turn one documented signal feature into a light installation.

Back to the Project Library