An MBA Lights Up an LED on an AI Fusion Board 

Hello World AI on the Edge. Ever since I left Taiwan, I’ve wanted to get my hands back on physical hardware. I did it by building a voice-controlled breathing coach on a Raspberry Pi that listens to how you are feeling, picks a breathing technique, and guides you through it with light and spoken coaching. It runs online with Gemini or fully offline with nothing leaving the device. 

Here is why I built it and what I learned:

I worked in an office like this at a TV data company in Taiwan:

It changed my mind on how I look at software and actually see and touch the connection to actual hardware. I also had the opportunity to visit one of the biggest electronics manufacturing facilities in Europe and saw how most of the work is done by robotics and physical AI. Each warehouse was so huge it had two lanes, one for robots delivering equipment, and one for human supervisors of robots on bicycles. It rocked my world.

Now that I’m back in the US, I want to leverage that mindset and learn hands-on for what’s next. I’m looking to make a career pivot to working in digital health/sports/medtech or a “deeptech” area where my skills would be useful.

As part of that exploration, I wanted to build something end-to-end using health and wellness as a use case to accompany the learning I’ve been doing, such as reading books like Deep Medicine and The AI Revolution in Medicine: GPT-4 and Beyond.

Part of my purpose outside of my own curiosity and builder’s whimsy is to also show future collaborators that I’m not some MBA here to make slides. I’m willing to do the hard things I don’t know how to do, get humbled, and always maintain a beginner’s mindset. 

I bought a Raspberry Pi 4 and the Sunfounder AI Fusion Lab Kit, an expansion board that sits on top of the Raspberry Pi to augment a general-purpose system into something that can sense, move, listen, speak, and interact with the physical world, in other words physical AI. I wanted to connect it to an LLM in the wild as well to see how that interaction works between local hardware and an external model. I created two paths, one that called Gemini and one that stayed local. 

I first started by watching a few videos while I unboxed. There were definitely moments where I just stared at this and the schematic on the website and procrastinated because of mental intimidation and fear of failure.

I used AI tools to teach me what things were, in addition to reading tutorials. For example, asking Claude to ELI5: what is a potentiometer? What are resistors and what do they do? 

I also wanted to explore TTS interactions and use the LEDs I was able to light up for a more real-world use case rather than classwork

I’ve become interested in digital health and medtech from recent life experiences:

  • I moved back to the US unexpectedly to deal with a family illness and saw firsthand how empowering patients to see their own medical imagery and diagnostics live on large monitors during exams and log into a patient portal that showed clinical notes, bloodwork readings, and other detailed information could convince reluctant patients to feel ready to make medical decisions.
  • Seeing my recovery score metrics on WHOOP from readings by a relatively simple PPG sensor combined with an LLM fitness prompter allowed me to be more compassionate toward myself, especially when healing from a bad back injury. I made more progress than I would have otherwise.

Another digital wellness tool I’ve been using is the Calm app for daily meditation. What I feel like I’m missing from that app experience is some sort of response to the meditation practice. It also felt like yet more screentime. 

I thought I could build a simple breathwork pacer that called an LLM that would recommend a meditation based on what a user asked via voice, and then guided the user via voice and LED light that adjusted brightness to match their breathing.

From a privacy and safety guardrails perspective, I also provided two options for interaction with a tradeoff for robustness: one utilized Gemini for voice interaction and the other a local business rules interaction so no information left the hardware device for privacy. I also iterated the user flow a few times to manage the edge case of users being in distress, as a wellness meditation shouldn’t be used for cases of a panic attack, for example.

Ideally I’d run a local model for interaction, but I was concerned about straining the Raspberry Pi 4 hardware so I went with a rules-based approach for local-only, and Gemini externally for better interaction functionality. I also wanted to interact with an external API as part of the learning process. 

I consider this first phase an almost happy path. As of this writing, I’m in my New York City home. I built this project in my home in LA (split my time). Given my busy work schedule over the next few weeks and the fact that bringing a lot of metal boards with wires in my carry-on would not result in the best time at the airport, I didn’t bring it with me. 

When I revisit this project, I’d probably try to take a shot at making it a fully local model since the AI Fusion Board does come with local LLM models. I’d also eliminate the keyboard inputs needed at startup by having the user make selections through voice alone, since my goal was to reduce screen interaction.

Overall, a really enjoyable project that got me out of my comfort zone by interacting with hardware software layers while keeping user experience in mind. 

The How I Built This below was developed with Claude:

I Built a Voice-Controlled Breathing Coach on a Raspberry Pi to Teach Me about Edge AI and Experiment with Digital Wellness

I went from not knowing what a breadboard was to a working voice-AI wellness device in a few focused sessions. The device listens to how you are feeling, picks a breathing technique, and coaches you through it with light and voice. In offline mode, nothing leaves the device. Building it taught me more about what “AI on the edge” actually means than any slide deck ever could.

What It Does

You tell the Breathwork Pacer how you’re feeling, for example, “Help me relax.”  A language model figures out what you need and picks one of five breathing techniques: diaphragmatic, box, 4-7-8, lion’s breath, or breath counting. An LED turns the technique’s color and breathes on the exact timing while a speaker coaches each phase. The techniques are adapted from Calm’s guide to breathing exercises.

At startup you choose offline or online modes.

Offline runs entirely on the Raspberry Pi. Keyword matching picks the technique, Piper speaks the coaching, Vosk transcribes your voice, all local. Your words about your stress or anxiety never leave the device.

Online sends your words to Google’s Gemini, which understands natural language and writes coaching that responds to what you actually said. For example,”I need to relax” gets diaphragmatic breathing.

Iterations for Crisis Mode

If someone says something that signals genuine distress (panic, chest pain, thoughts of self-harm), the device stops. No breathing session. It points toward real human support.

During testing, I found the language model ignored the crisis instruction in its prompt and tried to start a session anyway. So I moved the check before the model call entirely, a hard-coded gate that fires regardless of what any AI decides to do.

Takeaways

Build bottom-up. I tested the LED alone, then voice alone, then the classifier alone, then the full system. When something broke, I knew which layer. The same discipline that found a backwards LED on a breadboard scaled to debugging a five-file voice-AI system.

The hardest part was not the AI. It was audio configuration on a Linux single-board computer. Getting the speaker and microphone routed correctly took more debugging than the language model, the prompt engineering, and the breathing animations combined. Anyone telling you edge AI is “just deploy a model” has never been hands on hardware. 

Scope the AI to what it is actually good at. The model does one thing: interpret a natural-language request into one of five known options. It does not generate breathing patterns, give health advice, or free-associate. Everything downstream (the timing, the colors, the coaching words) is fixed in code, correct by construction. Using AI for what it is good at and not trusting it with what it is not is the most important design decision in this whole project.

Privacy is an architecture, not a policy page. Offline mode is not “we promise not to look at your data.” It is “the data physically cannot leave the device because there is no network call.” That is a different and much stronger statement, and it is the real argument for edge computing in health and wellness.

Appendix: Technical Reference

Github Link

The five techniques

All techniques run 3 rounds per session. Each has a distinct color and exact timing.

TechniqueColorTimingFor
DiaphragmaticBluein 3, out 3physical tension, belly breathing
BoxGreenin 4, hold 4, out 4, hold 4stress, fast calm, focus
4-7-8Magentain 4, hold 6, out 7winding down, anxiety, sleep
Lion’s breathOrangein 4, forceful out 2sluggishness, mental fog, energy
Breath countingCyanin 4, out 4, x3 roundsracing thoughts, presence

Lion’s breath uses a fast forceful light drop instead of a gentle fade. Breath counting speaks a running number on each inhale. Techniques adapted from 10 types of breathing exercises (and how to practice them) — Calm Blog 

Key Components

  • Five Python files on a Raspberry Pi 4 with a SunFounder Fusion HAT+. 
  • Piper for text-to-speech
  • Vosk for speech-to-text
  • Google Gemini (free tier) for online language understanding
  • An RGB LED on three PWM (pulse-width modulation) channels for the breathing light pacer 

Hardware Stack

The SunFounder Fusion HAT+ is an expansion board that sits on top of a Raspberry Pi and turns it into something that can sense, move, listen, speak, and interact with the physical world.

A bare Pi has no analog inputs, almost no hardware PWM, no microphone, and no speaker. The HAT adds all of those: Four 12-bit analog channels for reading sensors and knobs. Twelve PWM channels for controlling LED brightness and motor speed. Four motor driver ports. A built-in MEMS microphone and speaker over I2S digital audio.

Two processors work together. The Pi handles the heavy computing: Python, language models, speech recognition. A separate microcontroller on the HAT handles the real-time physical I/O that the Pi is not built for. They talk over I2C. When you write Pin(17), you are talking to the Pi directly. When you write PWM(5) or ADC(0), you are talking to the HAT’s microcontroller. Two chips, two numbering systems, one board.

The “fusion” in the name is the combination of AI computing with physical actuation in one platform. This breathing coach is a concrete example. The Pi runs voice recognition and a language model. The HAT’s PWM channels drive the LED. The HAT’s mic and speaker handle voice.

Built as a companion project to the AI on the Edge Course at toptechboy.com

Architecture flow

Spoken request, then microphone, then speech-to-text (Vosk, local), then crisis pre-check (hard-coded, before any model), then classifier (Gemini online or keyword offline), then the device announces the technique, then the LED breathes in the technique’s color on exact timing while the speaker coaches each phase, then asks if the user wants another session, then ends gracefully.

The crisis pre-check runs before the model is called, so safety holds regardless of mode, model behavior, or network state. After a session completes, the device asks whether the user wants another round. On a crisis detection, the device stops entirely.

The five files

FileJob
config.pyEvery setting you might change
techniques.pyFive techniques as data, LED animation with cosine-eased breathing
speech.pyVoice in (Vosk) and voice out (Piper), via fusion_hat library
classify.pyGemini online or keyword offline, crisis guardrail, fallback chain
main.pyStartup mode choice, session loop, graceful termination

Privacy architecture

Offline: nothing leaves the device. 

Online: single anonymous sentence to Gemini, spoken disclosure at startup, nothing stored. 

No logging: no session history, no transcripts, no user profile. 

Crisis guardrail: does not log or report the event.

Build summary

mkdir -p ~/breathe && cd ~/breathe
python3 -m venv --system-site-packages venv
source venv/bin/activate
pip install requests

Put the five Python files into ~/breathe/. Test bottom-up:

python techniques.py    # light cycles five colors
python speech.py        # speaks, then captures your voice
python classify.py      # prints keyword matches
python main.py          # the whole thing, choose offline first

Online mode: get a free key at aistudio.google.com (do not enable billing), then export GEMINI_API_KEY="..." in ~/.bashrc

If audio does not work: sudo /opt/setup_fusion_hat_audio.sh then reboot. If colors are wrong: edit channel numbers in config.py

Troubleshooting

SymptomFix
fusion_hat import errorRecreate venv with –system-site-packages
Wrong LED colorsEdit RED_CH/GREEN_CH/BLUE_CH in config.py
No soundsudo /opt/setup_fusion_hat_audio.sh then reboot
Mic captures nothingCheck SunFounder audio setup
Classifier always asksCheck GEMINI_API_KEY; try offline

Full Code

All files go in ~/breathe/.

config.py
 """Central settings for the breathing coach."""

RED_CH = 5; GREEN_CH = 6; BLUE_CH = 7; PWM_FREQ = 200

TTS_MODEL = "en_US-amy-low"; STT_LANGUAGE = "en-us"

GEMINI_MODEL = "gemini-2.5-flash"

CRISIS_FALLBACK = (

    "This sounds like more than a breathing exercise can help with. "

    "Please reach out to someone you trust, or a crisis line. "

    "In the U S you can call or text 9 8 8.")

techniques.py

"""The breathing techniques as data, plus the RGB LED animation."""
from time import sleep
import math
from fusion_hat.pwm import PWM
from config import RED_CH, GREEN_CH, BLUE_CH, PWM_FREQ
red = PWM(RED_CH); red.freq(PWM_FREQ)
green = PWM(GREEN_CH); green.freq(PWM_FREQ)
blue = PWM(BLUE_CH); blue.freq(PWM_FREQ)
COLORS = {"blue":(0,0,1),"green":(0,1,0),"magenta":(1,0,1),"orange":(1,0.4,0),"cyan":(0,1,1)}
CUES = {"in":"breathe in","out":"breathe out","hold":"hold"}
TECHNIQUES = {
"diaphragmatic": {"label":"diaphragmatic breathing","color":"blue","rounds":3,
"phases":[("in",3,"rise"),("out",3,"fall")]},
"box": {"label":"box breathing","color":"green","rounds":3,
"phases":[("in",4,"rise"),("hold",4,"hold_high"),("out",4,"fall"),("hold",4,"hold_low")]},
"478": {"label":"4 7 8 breathing","color":"magenta","rounds":3,
"phases":[("in",4,"rise"),("hold",6,"hold_high"),("out",7,"fall")]},
"lion": {"label":"lion's breath","color":"orange","rounds":3,
"cues":{"in":"breathe in","out":"ha"},
"phases":[("in",4,"rise"),("out",2,"drop")]},
"counting": {"label":"breath counting","color":"cyan","rounds":3,"count":True,
"phases":[("in",4,"rise"),("out",4,"fall")]},
}
def set_level(color, level):
level = max(0, min(100, level)); r,g,b = COLORS[color]
red.pulse_width_percent(level*r); green.pulse_width_percent(level*g); blue.pulse_width_percent(level*b)
def all_off():
red.pulse_width_percent(0); green.pulse_width_percent(0); blue.pulse_width_percent(0)
def run_phase(color, seconds, shape):
steps = max(1, int(seconds * 20))
for i in range(steps):
frac = i / steps
if shape=="rise": level=(1-math.cos(frac*math.pi))/2*100
elif shape=="fall": level=(1+math.cos(frac*math.pi))/2*100
elif shape=="drop": level=100*(1-frac)**3
elif shape=="hold_high": level=100
else: level=0
set_level(color, level); sleep(seconds/steps)
def run_technique(name, on_phase=None):
tech = TECHNIQUES[name]; color = tech["color"]
for ri in range(tech["rounds"]):
for pn, s, sh in tech["phases"]:
if on_phase: on_phase(pn, ri)
run_phase(color, s, sh)
all_off()
if __name__ == "__main__":
try:
for t in TECHNIQUES: print("Running:", t); run_technique(t)
finally: all_off()
speech.py
"""Voice in and voice out, using the fusion_hat library."""
from fusion_hat.tts import Piper
from fusion_hat.stt import Vosk
from config import TTS_MODEL, STT_LANGUAGE
# Uncomment on first run if no sound:
# import os; os.system("sudo /opt/setup_fusion_hat_audio.sh 2>/dev/null || true")
_tts = Piper(); _tts.set_model(TTS_MODEL)
_stt = Vosk(language=STT_LANGUAGE)
def speak(text):
if text: _tts.say(text)
def listen():
text = ""
for result in _stt.listen(stream=True):
if result.get("done"): text = result.get("final","").strip(); break
else: print(" ...", result.get("partial",""), end="\r", flush=True)
print(); return text
if __name__ == "__main__":
speak("Voice check. Say something after enter.")
input("Press Enter..."); heard = listen(); print("Heard:", repr(heard))
speak("I heard " + heard if heard else "I did not catch that.")
classify.py
"""Classifier: Gemini online or keyword offline, with crisis guardrail."""
import json, os, requests
from config import GEMINI_MODEL
VALID = {"diaphragmatic","box","478","lion","counting"}
SYSTEM = """You are a warm, calm breathing coach. Choose ONE technique from:
diaphragmatic - gentle belly breathing, eases physical tension
box - four equal counts, fast calm under stress
478 - long hold and exhale, winding down and sleep
lion - energizing forceful exhale, sluggishness and fog
counting - mindful counting, racing thoughts and presence
Return ONLY JSON:
{"technique":"...","intro":"<one sentence>","cues":{"in":"...","out":"...","hold":"..."},"reflection":"<one sentence>"}
SAFETY: If panic, chest pain, self-harm, or crisis, return:
{"crisis":true,"message":"<brief warm line pointing to real support>"}"""
def classify(transcript, mode="offline"):
if not transcript: return {"ask": True}
t_lower = transcript.lower()
crisis_words = ["panic","panicking","chest pain","self-harm","hurt myself",
"kill myself","suicide","can't breathe","heart attack","emergency"]
if any(w in t_lower for w in crisis_words): return {"crisis":True,"message":""}
if mode == "online":
result = _gemini(transcript)
if result is not None: return result
return _keyword(transcript)
def _gemini(transcript):
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key: return None
url = "https://generativelanguage.googleapis.com/v1beta/models/"+GEMINI_MODEL+":generateContent?key="+api_key
try:
r = requests.post(url, json={"system_instruction":{"parts":[{"text":SYSTEM}]},
"contents":[{"parts":[{"text":transcript}]}],
"generationConfig":{"responseMimeType":"application/json","temperature":0}}, timeout=20)
r.raise_for_status(); data = json.loads(r.json()["candidates"][0]["content"]["parts"][0]["text"].strip())
except Exception: return None
if data.get("crisis"): return {"crisis":True,"message":data.get("message","")}
if data.get("technique") in VALID:
return {"technique":data["technique"],"intro":data.get("intro",""),
"cues":data.get("cues"),"reflection":data.get("reflection","")}
return None
def _keyword(t):
t = t.lower()
crisis_words = ["panic","panicking","chest pain","self-harm","hurt myself",
"kill myself","suicide","can't breathe","heart attack","emergency"]
if any(w in t for w in crisis_words): return {"crisis":True,"message":""}
technique = None
if any(w in t for w in ["box","square","reset","stress","focus"]): technique="box"
elif any(w in t for w in ["sleep","bed","wind down","four seven eight","4 7 8","478","anxious","anxiety"]): technique="478"
elif any(w in t for w in ["energy","energize","sluggish","tired","foggy","fog","wake","lion","mood"]): technique="lion"
elif any(w in t for w in ["count","counting","present","racing","mindful","scattered"]): technique="counting"
elif any(w in t for w in ["belly","diaphragm","tension","relax","calm"]): technique="diaphragmatic"
if technique is None: return {"ask":True}
labels = {"diaphragmatic":"diaphragmatic breathing","box":"box breathing",
"478":"4 7 8 breathing","lion":"lion's breath","counting":"breath counting"}
return {"technique":technique,"intro":"Let's do "+labels[technique]+". Follow the light.",
"cues":None,"reflection":"Nicely done. Take a moment to notice how you feel."}
main.py
"""The breathing coach. Run this."""
import os
from time import sleep
from speech import listen, speak
from classify import classify
from techniques import run_technique, TECHNIQUES, CUES, all_off
from config import CRISIS_FALLBACK
def choose_mode():
has_key = bool(os.environ.get("GEMINI_API_KEY"))
print("\nBreathing coach")
print(" 1) Online - Gemini understands natural language"+("" if has_key else " (no key found)"))
print(" 2) Offline - keyword matching, no network")
choice = input("Choose 1 or 2 [2]: ").strip()
mode = "online" if choice == "1" else "offline"
if mode == "online":
speak("Online mode. Your words will be sent to Google for processing. Nothing is stored on this device.")
else: speak("Offline mode. Everything stays on this device.")
return mode
def make_on_phase(tech, cues):
counting = tech.get("count", False)
def on_phase(phase_name, round_index):
if counting:
if phase_name == "in": speak(str((round_index % 10) + 1))
else: speak(cues.get(phase_name, ""))
return on_phase
def one_session(mode):
speak("How can I help you breathe today?")
input("\nPress Enter, then speak..."); print("Listening...")
text = listen(); print("Heard:", repr(text))
result = classify(text, mode=mode)
if result.get("crisis"):
speak(result.get("message") or CRISIS_FALLBACK); return "crisis"
if result.get("ask"):
speak("I can guide diaphragmatic, box, 4 7 8, lion's breath, or breath counting. Which would you like?")
return "continue"
name = result["technique"]; tech = TECHNIQUES[name]
cues = result.get("cues") or tech.get("cues") or CUES
speak(result.get("intro") or ("Let's do " + tech["label"] + ". Follow the light."))
run_technique(name, on_phase=make_on_phase(tech, cues))
speak(result.get("reflection") or "Nicely done. Take a moment to notice how you feel.")
speak("Would you like another session? Press Enter and say yes or no.")
input(); answer = listen(); print("Heard:", repr(answer))
if any(w in answer.lower() for w in ["yes","yeah","sure","another","again"]): return "continue"
speak("Take care. Goodbye."); return "done"
def main():
mode = choose_mode(); speak("Breathing coach ready.")
try:
while True:
status = one_session(mode)
if status == "crisis": print("Session ended, crisis detected."); break
elif status == "done": break
sleep(1)
except KeyboardInterrupt: print("\nStopping.")
finally: all_off()
if __name__ == "__main__": main()

Posted in , , , , , , ,

One response to “Building Breathwork Pacer: an Edge AI Wellness Experiment”

  1. Day 136 of 180 Days of Learning and Applying AI #jfdi – Thoughts on learning and work Avatar

    […] Building Breathwork Pacer: an Edge AI Wellness Experiment […]

    Like

Leave a Reply