Complete projects with wiring diagrams, full source code, and step-by-step assembly guides. From beginner to advanced.
Monitor temperature, humidity, and soil moisture. LED indicates watering status, OLED shows live readings.
| Component | Qty | Cost |
|---|---|---|
| Arduino Uno R3 | 1 | $5 |
| DHT22 Temperature/Humidity Sensor | 1 | $3 |
| Soil Moisture Sensor (Capacitive) | 1 | $2 |
| 0.96" OLED Display (I2C SSD1306) | 1 | $3 |
| NeoPixel LED (WS2812B) | 1 | $1 |
| Breadboard + Jumper Wires | 1 set | $1 |
(defproject smart-plant-monitor
:board "arduino-uno"
:packages [hilos-sensors hilos-displays hilos-core])
;; Pin definitions
(def dht-pin 2)
(def soil-pin A0)
(def neo-pin 6)
(def dry-threshold 600)
;; Initialize peripherals
(defn setup []
(dht-begin dht-pin DHT22)
(oled-begin 128 64)
(neo-begin neo-pin 1)
(pin-mode soil-pin INPUT)
(serial-begin 9600))
;; Read soil moisture percentage (0-100)
(defn read-soil []
(let [raw (analog-read soil-pin)]
;; Sensor returns high value when dry, low when wet
(constrain (map-range raw 800 300 0 100) 0 100)))
;; Set NeoPixel color based on soil status
(defn update-led [soil-pct]
(if (< soil-pct 30)
;; Dry - red pulse
(neo-set-color 0 255 0 0)
;; Watered - solid green
(neo-set-color 0 0 255 0))
(neo-show))
;; Update OLED display
(defn update-display [temp humid soil]
(oled-clear)
(oled-set-font 1)
(oled-set-cursor 0 0)
(oled-print "SMART PLANT")
(oled-set-font 0)
(oled-set-cursor 0 18)
(oled-print (str "Temp: " temp " C"))
(oled-set-cursor 0 30)
(oled-print (str "Humid: " humid " %"))
(oled-set-cursor 0 42)
(oled-print (str "Soil: " soil " %"))
;; Status bar at bottom
(oled-set-cursor 0 55)
(if (< soil 30)
(oled-print ">> NEEDS WATER")
(oled-print ">> OK"))
(oled-show))
;; Main loop
(defn loop []
(let [temp (dht-read-temp dht-pin)
humid (dht-read-humid dht-pin)
soil (read-soil)]
(serial-print (str "T:" temp " H:" humid " S:" soil))
(update-display temp humid soil)
(update-led soil)
(delay 2000)))
Every 2 seconds the board reads the DHT22 for temperature and humidity, and the capacitive soil sensor for moisture level. The raw ADC value from the soil sensor is mapped to a 0-100 percentage.
If soil moisture drops below 30%, the NeoPixel turns red and the OLED displays "NEEDS WATER". Once the plant is watered and moisture rises, the LED turns green.
All readings are also sent over serial at 9600 baud for debugging.
Solar-powered ESP32 weather station. Publishes sensor data to the HIL IoT network for other devices to subscribe.
| Component | Qty | Cost |
|---|---|---|
| ESP32 DevKit V1 | 1 | $6 |
| BMP280 Barometric Pressure Sensor | 1 | $2 |
| DHT22 Temperature/Humidity Sensor | 1 | $3 |
| Rain Sensor Module | 1 | $1 |
| 6V 1W Solar Panel | 1 | $3 |
| TP4056 LiPo Charger Module | 1 | $1 |
| 18650 Battery + Holder | 1 | $4 |
| Breadboard + Jumper Wires | 1 set | $5 |
(defproject iot-weather-station
:board "esp32"
:packages [hilos-sensors hilos-iot hilos-core])
;; Pin definitions
(def dht-pin 4)
(def rain-pin 34)
(def bmp-sda 21)
(def bmp-scl 22)
;; WiFi credentials (set via hilp config or here)
(def wifi-ssid "YOUR_WIFI_SSID")
(def wifi-pass "YOUR_WIFI_PASS")
(def publish-interval 30000) ;; 30 seconds
(defn setup []
;; Initialize WiFi
(wifi-begin wifi-ssid wifi-pass)
(serial-begin 115200)
;; Initialize sensors
(dht-begin dht-pin DHT22)
(bmp280-begin bmp-sda bmp-scl)
(pin-mode rain-pin INPUT)
(serial-println "Weather station online"))
(defn read-rain []
(let [raw (analog-read rain-pin)]
;; Higher value = drier
(map-range raw 0 4095 100 0)))
(defn publish-weather [temp humid pressure rain]
;; Publish each reading to HIL IoT topics
(iot-connect)
(iot-publish "weather/temperature" (str temp))
(iot-publish "weather/humidity" (str humid))
(iot-publish "weather/pressure" (str pressure))
(iot-publish "weather/rain" (str rain))
;; Publish combined JSON payload
(iot-publish "weather/all"
(str "{\"temp\":" temp
",\"humidity\":" humid
",\"pressure\":" pressure
",\"rain\":" rain "}"))
(iot-disconnect)
(serial-println "Published weather data"))
(defn loop []
(when (wifi-connected?)
(let [temp (dht-read-temp dht-pin)
humid (dht-read-humid dht-pin)
pressure (bmp280-read-pressure)
rain (read-rain)]
(serial-print (str "T:" temp " H:" humid
" P:" pressure " R:" rain))
(publish-weather temp humid pressure rain)))
(deep-sleep (/ publish-interval 1000)))
The ESP32 connects to WiFi, reads all sensors, then publishes data to four separate HIL IoT topics plus a combined JSON payload. Other devices on the network can subscribe to weather/temperature etc. to receive live data.
After publishing, the ESP32 enters deep sleep for 30 seconds to conserve battery. The solar panel continuously charges the 18650 via the TP4056 module, giving indefinite runtime in sunny conditions.
Subscribe from any HIL device with: (iot-subscribe "weather/temperature" callback-fn)
Ultrasonic proximity detection, buzzer chime pattern, servo gate latch, and network alert on button press.
| Component | Qty | Cost |
|---|---|---|
| Arduino Nano | 1 | $3 |
| HC-SR04 Ultrasonic Sensor | 1 | $1 |
| Active Buzzer | 1 | $1 |
| Push Button (Momentary) | 1 | $0.50 |
| SG90 Micro Servo | 1 | $2 |
| Breadboard + Jumper Wires | 1 set | $4.50 |
(defproject smart-doorbell
:board "arduino-nano"
:packages [hilos-sensors hilos-motors hilos-iot hilos-core])
;; Pin definitions
(def trig-pin 9)
(def echo-pin 10)
(def buzzer-pin 11)
(def button-pin 2)
(def servo-pin 3)
;; State
(def door-open false)
(def last-ring-time 0)
(def cooldown 5000) ;; 5 seconds between rings
(defn setup []
(pin-mode trig-pin OUTPUT)
(pin-mode echo-pin INPUT)
(pin-mode buzzer-pin OUTPUT)
(pin-mode button-pin INPUT_PULLUP)
(servo-attach servo-pin)
(servo-write servo-pin 0) ;; Gate closed
(serial-begin 9600)
(iot-begin "smart-doorbell"))
;; Measure distance in cm using ultrasonic sensor
(defn measure-distance []
(digital-write trig-pin LOW)
(delay-us 2)
(digital-write trig-pin HIGH)
(delay-us 10)
(digital-write trig-pin LOW)
(let [duration (pulse-in echo-pin HIGH)]
(/ (* duration 0.034) 2)))
;; Doorbell chime pattern: ding-dong-ding
(defn ring-chime []
(tone buzzer-pin 1000 200)
(delay 250)
(tone buzzer-pin 800 200)
(delay 250)
(tone buzzer-pin 1000 200)
(delay 250)
(no-tone buzzer-pin))
;; Open gate servo
(defn open-gate []
(servo-write servo-pin 90)
(delay 3000)
(servo-write servo-pin 0))
;; Check if enough time has passed since last ring
(defn can-ring []
(let [now (millis)]
(or (= last-ring-time 0)
(> (- now last-ring-time) cooldown))))
(defn loop []
;; Check for person within 50cm
(let [distance (measure-distance)]
(when (and (< distance 50) (can-ring))
(serial-println "Person detected!")
(ring-chime)
(open-gate)
(set last-ring-time (millis))
;; Send network alert
(iot-connect)
(iot-publish "doorbell/alert" "visitor")
(iot-disconnect)))
;; Manual button press
(when (= (digital-read button-pin) LOW)
(serial-println "Button pressed!")
(ring-chime)
(open-gate)
(set last-ring-time (millis))
(iot-connect)
(iot-publish "doorbell/alert" "manual")
(iot-disconnect)
(delay 500))) ;; debounce
The ultrasonic sensor continuously measures distance. When someone comes within 50cm of the sensor, the system plays a three-tone chime, then opens the servo gate latch for 3 seconds before closing it.
A 5-second cooldown prevents rapid re-triggering. The push button provides manual override to ring the chime and open the gate regardless of distance.
Every trigger publishes an alert to the HIL IoT network on doorbell/alert with the trigger source ("visitor" or "manual").
Real-time audio visualization on a 60-LED NeoPixel strip using a microphone module. Color and pattern react to sound amplitude.
| Component | Qty | Cost |
|---|---|---|
| Arduino Uno R3 | 1 | $5 |
| NeoPixel Strip (WS2812B, 60 LEDs) | 1 | $8 |
| MAX4466 Electret Microphone Module | 1 | $3 |
| 5V 3A Power Supply + Jumper Wires | 1 set | $4 |
(defproject led-music-visualizer
:board "arduino-uno"
:packages [hilos-displays hilos-core])
;; Configuration
(def mic-pin A0)
(def neo-pin 6)
(def num-leds 60)
(def sample-window 50) ;; ms to sample audio
(def smoothing 0.7) ;; decay factor for peak hold
;; State
(def peak-amplitude 0)
(def smoothed 0)
(def hue-offset 0)
(defn setup []
(neo-begin neo-pin num-leds)
(pin-mode mic-pin INPUT)
(serial-begin 115200)
(neo-clear)
(neo-show))
;; Convert HSV to RGB (hue 0-255, sat 100, val 100)
(defn wheel [pos]
(let [p (mod pos 255)]
(cond
(< p 85) (list (- 255 (* p 3)) 0 (* p 3)) ;; green -> red
(< p 170) (set p (- p 85)) ;; red -> blue
:else (list (* (- p 170) 3) (- 255 (* (- p 170) 3)) 0)))) ;; blue -> green
;; Sample peak amplitude from microphone
(defn sample-amplitude []
(let [start-time (millis)
signal-max 0]
(while (< (- (millis) start-time) sample-window)
(let [sample (abs (- (analog-read mic-pin) 512)))]
(when (> sample signal-max)
(set signal-max sample))))
signal-max))
(defn loop []
(let [raw-amp (sample-amplitude)
amplitude (map-range raw-amp 0 512 0 255)]
;; Smooth the amplitude
(set smoothed (+ (* smoothed smoothing)
(* amplitude (- 1 smoothing))))
;; Track peak with decay
(when (> smoothed peak-amplitude)
(set peak-amplitude smoothed))
(set peak-amplitude (* peak-amplitude 0.95))
;; Slowly rotate hue offset
(set hue-offset (mod (+ hue-offset 1) 255))
;; Map amplitude to how many LEDs light up
(let [lit-count (map-range smoothed 0 255 1 num-leds)]
;; Clear all
(neo-clear)
;; Light up LEDs up to the amplitude level
(for (i 0 lit-count)
(let [hue (mod (+ hue-offset (* i 4)) 255)
brightness (map-range i 0 lit-count 50 255)
rgb (wheel hue)]
(neo-set-pixel i
(* (first rgb) (/ brightness 255))
(* (second rgb) (/ brightness 255))
(* (third rgb) (/ brightness 255)))))
(neo-show))
;; Debug output
(serial-print (str "Amp:" (round smoothed) " Peak:" (round peak-amplitude)))
(delay 10)))
The microphone samples the audio signal for 50ms windows and captures the peak amplitude. This value is smoothed with an exponential moving average to reduce jitter.
The smoothed amplitude maps to how many of the 60 LEDs light up. Colors cycle through a rainbow using a HSV color wheel, with each LED offset slightly in hue for a gradient effect. Brightness increases from the base to the peak LED.
A peak-hold value decays at 5% per frame, creating a "peak hold" visual effect. The hue slowly rotates over time for a dynamic color shift even during quiet moments.
Dual ultrasonic sensors for entry/exit detection, servo gate, LCD spot counter, NeoPixel status indicator, and full state machine.
| Component | Qty | Cost |
|---|---|---|
| Arduino Mega 2560 | 1 | $7 |
| HC-SR04 Ultrasonic Sensor (Entry) | 1 | $1 |
| HC-SR04 Ultrasonic Sensor (Exit) | 1 | $1 |
| SG90 Micro Servo (Gate) | 1 | $2 |
| NeoPixel LED (WS2812B) | 1 | $1 |
| Active Buzzer | 1 | $1 |
| 16x2 LCD (I2C PCF8574) | 1 | $3 |
| Breadboard + Jumper Wires | 1 set | $2 |
(defproject smart-parking-gate
:board "arduino-mega"
:packages [hilos-sensors hilos-motors hilos-displays hilos-core])
;; Pin definitions
(def entry-trig 2)
(def entry-echo 3)
(def exit-trig 4)
(def exit-echo 5)
(def servo-pin 6)
(def neo-pin 7)
(def buzzer-pin 8)
;; LCD I2C address
(def lcd-addr 0x27)
;; Parking configuration
(def max-spots 20)
(def detect-distance 30) ;; cm threshold for car detection
(def gate-open-time 5000) ;; ms to keep gate open
;; State machine
(def state :idle) ;; :idle :entry :exit :gate-open
(def available-spots 20)
(def gate-timer 0)
(def entry-passed false)
(def exit-passed false)
(defn setup []
;; Ultrasonic pins
(pin-mode entry-trig OUTPUT)
(pin-mode entry-echo INPUT)
(pin-mode exit-trig OUTPUT)
(pin-mode exit-echo INPUT)
;; Servo
(servo-attach servo-pin)
(servo-write servo-pin 90) ;; gate closed
;; NeoPixel
(neo-begin neo-pin 1)
;; Buzzer
(pin-mode buzzer-pin OUTPUT)
;; LCD
(lcd-begin lcd-addr 16 2)
(lcd-clear)
;; Serial
(serial-begin 9600)
(update-display)
(update-neo))
;; Measure distance from HC-SR04
(defn measure [trig echo]
(digital-write trig LOW)
(delay-us 2)
(digital-write trig HIGH)
(delay-us 10)
(digital-write trig LOW)
(let [duration (pulse-in echo HIGH)]
(/ (* duration 0.034) 2)))
;; Update LCD with available spots
(defn update-display []
(lcd-set-cursor 0 0)
(lcd-print "Parking System ")
(lcd-set-cursor 0 1)
(lcd-print (str "Spots: " available-spots "/" max-spots " ")))
;; Update NeoPixel color based on availability
(defn update-neo []
(cond
(>= available-spots 1)
(neo-set-color 0 0 255 0) ;; Green - spots available
(= available-spots 0)
(neo-set-color 0 255 0 0))) ;; Red - full
(neo-show))
;; Alert buzzer
(defn buzzer-alert []
(tone buzzer-pin 1500 100)
(delay 150)
(tone buzzer-pin 1000 100)
(delay 150)
(no-tone buzzer-pin))
;; Open the gate
(defn open-gate []
(servo-write servo-pin 0) ;; gate open
(set gate-timer (millis)))
;; Close the gate
(defn close-gate []
(servo-write servo-pin 90) ;; gate closed
(set gate-timer 0))
;; State machine transitions
(defn handle-entry []
(let [dist (measure entry-trig entry-echo)]
(when (and (< dist detect-distance) (not entry-passed))
(set entry-passed true)
(when (> available-spots 0)
(serial-println "Car entering")
(buzzer-alert)
(open-gate)
(set state :gate-open)))))
(defn handle-exit []
(let [dist (measure exit-trig exit-echo)]
(when (and (< dist detect-distance) (not exit-passed))
(set exit-passed true)
(when (< available-spots max-spots)
(serial-println "Car exiting")
(buzzer-alert)
(open-gate)
(set state :gate-open)))))
(defn handle-gate-open []
(when (> (- (millis) gate-timer) gate-open-time)
;; Gate timer expired - determine if entering or exiting
(when entry-passed
(set available-spots (- available-spots 1))
(set entry-passed false))
(when exit-passed
(set available-spots (+ available-spots 1))
(set exit-passed false))
(close-gate)
(update-display)
(update-neo)
(serial-print (str "Available: " available-spots))
(set state :idle)))
;; Check if car has cleared the sensor
(defn check-clearance []
(when (and (= state :idle)
(>= (measure entry-trig entry-echo) detect-distance))
(set entry-passed false))
(when (and (= state :idle)
(>= (measure exit-trig exit-echo) detect-distance))
(set exit-passed false)))
(defn loop []
(case state
:idle (do (handle-entry) (handle-exit) (check-clearance))
:gate-open (handle-gate-open)
nil)
(delay 50))
The system runs a three-state machine: idle, entry/exit detection, and gate-open. Two ultrasonic sensors monitor the entry and exit lanes independently.
When a car is detected within 30cm at the entry sensor and spots are available, the gate opens for 5 seconds, the buzzer sounds, and the spot count decrements. The same logic applies to the exit sensor, but increments the count.
The I2C LCD shows the current spot count at the entrance. The NeoPixel is green when spots are available and red when full. The system prevents re-triggering while a car is in the detection zone.
The display and NeoPixel update automatically after each gate cycle.
Scheduled feeding at 8am and 6pm using RTC clock, servo-driven food dispenser, manual override button, and NeoPixel countdown indicator.
| Component | Qty | Cost |
|---|---|---|
| Arduino Uno R3 | 1 | $5 |
| DS1307 RTC Module (with battery) | 1 | $2 |
| SG90 Micro Servo (Dispenser) | 1 | $2 |
| Push Button (Manual Feed) | 1 | $0.50 |
| NeoPixel LED (WS2812B) | 1 | $1 |
| Breadboard + Jumper Wires | 1 set | $4.50 |
(defproject automated-pet-feeder
:board "arduino-uno"
:packages [hilos-motors hilos-displays hilos-core])
;; Pin definitions
(def servo-pin 9)
(def button-pin 2)
(def neo-pin 6)
;; Schedule: feed at 8:00 and 18:00
(def feed-hours [8 18])
(def feed-duration 1500) ;; servo open time in ms
(def servo-open-angle 90)
(def servo-closed-angle 0)
;; State
(def last-fed-hour -1)
(def feeding false)
(def feed-timer 0)
(def next-feed-led 0)
(defn setup []
(rtc-begin)
;; Uncomment and set time on first run:
;; (rtc-set-datetime 2026 8 18 12 0 0)
(servo-attach servo-pin)
(servo-write servo-pin servo-closed-angle)
(pin-mode button-pin INPUT_PULLUP)
(neo-begin neo-pin 1)
(serial-begin 9600)
(serial-println "Pet feeder online"))
;; Get current hour from RTC
(defn get-hour []
(second (rtc-now))) ;; rtc-now returns (year month day hour minute second)
;; Get current minute
(defn get-minute []
(third (rtc-now)))
;; Update NeoPixel to indicate next feed countdown
(defn update-indicator [current-hour]
(let [next-hour (find-next-feed current-hour)]
(cond
;; Feeding in progress - bright white
feeding
(neo-set-color 0 255 255 255)
;; Less than 1 hour to next feed - pulse yellow
(<= (- next-hour current-hour) 1)
(neo-set-color 0 255 180 0)
;; More than 1 hour - dim blue
:else
(neo-set-color 0 0 0 40)))
(neo-show))
;; Find the next scheduled feed hour
(defn find-next-feed [current-hour]
(let [sorted (sort feed-hours)]
;; Find the first feed hour that's greater than current
(loop [hours sorted]
(cond
(empty? hours) (first sorted) ;; wrap around to tomorrow
(> (first hours) current-hour) (first hours)
:else (recur (rest hours))))))
;; Open the dispenser
(defn start-feeding []
(serial-println "FEEDING!")
(servo-write servo-pin servo-open-angle)
(set feeding true)
(set feed-timer (millis))
(set last-fed-hour (get-hour)))
;; Close the dispenser
(defn stop-feeding []
(servo-write servo-pin servo-closed-angle)
(set feeding false)
(serial-println "Feed complete"))
(defn loop []
(let [hour (get-hour)
minute (get-minute)]
;; Check if it's feeding time
(when (and (not feeding)
(includes? feed-hours hour)
(= minute 0)
(not= hour last-fed-hour))
(serial-print (str "Scheduled feed at " hour ":" minute))
(start-feeding))
;; Manual button override
(when (and (= (digital-read button-pin) LOW) (not feeding))
(serial-println "Manual feed triggered")
(start-feeding))
;; Handle feeding timer
(when (and feeding (> (- (millis) feed-timer) feed-duration))
(stop-feeding))
;; Update the NeoPixel indicator
(update-indicator hour)
;; Debug output every 30 seconds
(when (= (mod (millis) 30000) 0)
(serial-print (str "Time: " hour ":" minute
" | Next feed: " (find-next-feed hour) ":00")))
(delay 1000)))
The DS1307 RTC maintains the current time even when the Arduino is powered off. Every second, the main loop checks if the current hour matches a scheduled feed time (8:00 and 18:00) and the minute is 0.
When it's time to feed, the servo opens a food dispenser flap for 1.5 seconds, releasing one portion. The last-fed-hour variable prevents double-feeding in the same hour window.
The push button provides manual override at any time. The NeoPixel indicates status: white while feeding, yellow when less than 1 hour to next feed, dim blue otherwise.
The servo flap mechanism works by attaching the servo arm to a sliding door at the bottom of a food hopper. Open = slide door retracts, releasing food. Closed = door blocks the opening.
Install the HIL toolchain first with hilp toolchain. Run hilp doctor to verify everything is working.
Each project declares its dependencies. Install them with hilp install hilos-sensors etc. The compiler resolves dependencies automatically.
Never power servos or NeoPixel strips from the Arduino's 5V pin. Use an external supply with a common ground. Most servos need 5V 2A+. NeoPixels need ~60mA per LED at full brightness.
Use hil monitor to view serial output from your board in real time. All projects include serial debug output.
Physical control surface with 8 motorized faders, 16 buttons, encoder, and OLED display. Controls OBS scenes, sources, audio levels, and transitions via MIDI.
| Component | Qty | Cost |
|---|---|---|
| Teensy 4.0 (USB-MIDI) | 1 | $25 |
| 10K Slide Pot (linear) | 8 | $8 |
| Tactile Button (6x6mm) | 16 | $3 |
| EC11 Rotary Encoder | 1 | $3 |
| 0.96" OLED (I2C SSD1306) | 1 | $3 |
| WS2812B LEDs (for strips) | 8 | $2 |
| Breadboard + Jumper Wires | 1 set | $5 |
| 0.1µF Caps, 10K Resistors | assortment | $2 |
| Enclosure (project box) | 1 | $4 |
(defproject obs-companion
:board "teensy40"
:packages [hilos-midi hilos-displays hilos-core])
;; MIDI note mappings (configurable in OBS)
(def scene-notes [
0 ; Scene 1
1 ; Scene 2
2 ; Scene 3
3 ; Scene 4
4 ; Transition: Cut
5 ; Transition: Fade
6 ; Record
7 ; Stream
])
(def button-notes [
8 ; Mute Mic
9 ; Mute Desktop
10 ; Push to Talk
11 ; Studio Mode
12 ; Replay Buffer
13 ; Screenshot
14 ; Mute All
15 ; Unmute All
16 ; Next Transition
17 ; Previous Transition
18 ; Fullscreen
19 ; Settings
20 ; Audio Settings
21 ; Start Virtual Cam
22 ; Stop Virtual Cam
23 ; Hotkey Override
])
;; State
(def current-scene 0)
(def last-button-states 0)
(def fader-values [0 0 0 0 0 0 0 0])
;; Analog mux addresses for 8 slide pots
(def mux-address-pins [2 3 4])
(def button-data-pin 5)
(def button-latch-pin 6)
(def button-clock-pin 7)
(def encoder-pin 9)
(def encoder-btn 11)
(defn setup ()
(midi-begin 0)
(serial-begin 115200)
;; Button shift register pins
(pin-mode button-clock-pin OUTPUT)
(pin-mode button-latch-pin OUTPUT)
;; Encoder
(pin-mode encoder-pin INPUT_PULLUP)
(pin-mode encoder-btn INPUT_PULLUP)
;; OLED
(oled-init)
(oled-clear)
(oled-text "OBS Companion Ready" 0 0)
(oled-display)
(serial-println "=== OBS Companion Controller v1.0 ===")
;; Initialize fader tracking
(dotimes (i 8)
(midi-send-cc i 0)))
(defn read-faders ()
"Read all 8 slide pots via analog multiplexer"
(dotimes (i 8)
;; Set mux address
(digital-write (bit-check i 0) (nth mux-address-pins 0))
(digital-write (bit-check i 1) (nth mux-address-pins 1))
(digital-write (bit-check i 2) (nth mux-address-pins 2))
(wait 1)
(let ((val (analog-read 0)))
(setf (nth i fader-values) val)
(when (not (= val (midi-get-cc i)))
(midi-send-cc i val)))))
;; Read buttons via shift register
(digital-write button-latch-pin LOW)
(wait 1)
(digital-write button-latch-pin HIGH)
(let ((button-states 0))
(dotimes (i 16)
(let ((bit (digital-read button-data-pin)))
(when (= bit HIGH)
(setf button-states (bit-set button-states i))
(let ((note-num (nth i button-notes)))
(midi-send-note-on note-num 127)))
(digital-write button-clock-pin HIGH)
(wait 1)
(digital-write button-clock-pin LOW)
(wait 1)))
button-states)
;; Encoder for scene switching
(let ((enc-pos (pulse-in encoder-pin 5000)))
(when (> enc-pos 0)
(setf current-scene (mod (+ current-scene 1) 8))
(midi-send-note-on (nth current-scene scene-notes) 127)
(midi-send-program-change current-scene)
(oled-clear)
(oled-text (str "Scene: " current-scene) 0 0)
(oled-display)))
;; Encoder button
(when (= (digital-read encoder-btn) LOW)
(wait 200) ;; debounce
(midi-send-note-on (nth scene-notes 4) 127) ;; Transition Cut
(oled-text "CUT!" 0 20)
(oled-display)))
;; Send volume fader changes as MIDI CC
(read-faders)
;; Update OLED with current scene
(oled-clear)
(oled-text (str "Scene: " current-scene) 0 0)
(dotimes (i 8)
(oled-text (str "F" i ":" (nth i fader-values)) 0 (+ 20 (* i 10))))
(oled-display)
(wait 50)))
Deploy: hilp compile obs-companion.hil --board teensy40 && hilp upload
Master sync generator producing MIDI clock, DMX, composite video sync, and timecode. Synchronizes LED strips, projection mapping, and audio-reactive visuals to a master tempo.
| Component | Qty | Cost |
|---|---|---|
| Teensy 4.0 + Audio Board | 1 | $40 |
| W5500 Ethernet Module | 1 | $5 |
| MIDI Opto-isolator (6N137) | 2 | $2 |
| DMX Transceiver (MAX3060) | 1 | $8 |
| LM1881 Video Sync Separator | 1 | $3 |
| 16x2 LCD Display | 1 | $4 |
| Rotary Encoder + Button | 1 | $3 |
| TRS Jack (MIDI Out) | 2 | $3 |
| Breadboard + Enclosure | 1 set | $5 |
(defproject vj-syncbox
:board "teensy40-audio"
:packages [hilos-midi hilos-dmx hilos-video hilos-ethernet hilos-core])
;; Sync sources
(def sync-source :midi) ;; :midi, :dmx, :video, :internal
(def master-bpm 120)
(def master-24ppqn 24)
;; Output ports
(def midi-out-1 0)
(def midi-out-2 0)
(def dmx-universe 0)
(def video-sync-port 0)
;; State
(def current-bpm 120)
(def last-clock 0)
(def clock-counter 0)
(def quarter-note-counter 0)
(defn setup ()
(midi-begin 0)
(dmx-begin 1)
(video-sync-begin)
(serial-begin 115200)
(lcd-init)
(lcd-clear)
(lcd-print "VJ Sync Box v1.0" 0 0)
(lcd-print "BPM:" current-bpm 0 1)
(lcd-display)
(serial-println "=== VJ Sync Box Ready ===")
;; Send initial MIDI clock if internal mode
(when (= sync-source :internal)
(midi-send-realtime midi-out-1 0xF8) ;; Timing clock
(midi-send-song-select midi-out-1 0)
(midi-send-start midi-out-1))
;; Send DMX master dimmer sweep
(dmx-set-channel dmx-universe 0 255)
(dmx-send dmx-universe))
;; Encoder for BPM adjustment
(let ((enc-pos (pulse-in 10 5000)))
(when (> enc-pos 0)
(setf current-bpm (+ current-bpm 1))
(lcd-print (str "BPM:" current-bpm) 0 1)
(lcd-display)))
(when (= (digital-read 12) LOW)
(wait 200) ;; debounce
(setf current-bpm (max 60 (min 240 current-bpm)))))
;; Generate MIDI clock (24ppqn)
(when (= sync-source :internal)
(let ((now (millis)))
(let ((clock-period (/ 60000 (* current-bpm master-24ppqn))))
(when (>= (- now last-clock) clock-period)
(setf last-clock now)
;; Send MIDI clock to both outputs
(midi-send-realtime midi-out-1 0xF8)
(midi-send-realtime midi-out-2 0xF8)
;; Send quarter note on beats 1-4
(when (= (mod clock-counter master-24ppqn) 0)
(midi-send-note-on midi-out-1 60 127 quarter-note-counter)
(midi-send-note-on midi-out-2 60 127 quarter-note-counter)
(dmx-set-channel dmx-universe 1 (/ (* quarter-note-counter 63) 3)
(dmx-set-channel dmx-universe 2 (/ (* (- 4 quarter-note-counter) 63) 3)
(dmx-send dmx-universe))
(incf clock-counter)
(when (>= clock-counter (* master-24ppqn 4))
(setf clock-counter 0)
(incf quarter-note-counter)
(when (>= quarter-note-counter 4)
(setf quarter-note-counter 0)))))))
;; Video sync passthrough
(when (= sync-source :video)
(let ((video-sync (video-sync-read)))
(when video-sync
;; Convert video sync to MIDI clock
(midi-send-realtime midi-out-1 0xF8)
(midi-send-realtime midi-out-2 0xF8))))
(wait 5)))))
Deploy: hilp compile vj-syncbox.hil --board teensy40-audio && hilp upload
4-channel hardware mixer with motorized faders, analog VU meters, parametric EQ, and MIDI control. Perfect for live streaming, podcasting, and music production.
| Component | Qty | Cost |
|---|---|---|
| Teensy 4.0 + Audio Adapter | 1 | $40 |
| Motorized Fader (100mm) | 4 | $20 |
| VU Meter (analog panel meter) | 4 | $8 |
| Rotary Encoder (EQ knob) | 8 | $4 |
| Tactile Button (Mute/Solo) | 12 | $3 |
| 0.96" OLED Display (I2C) | 1 | $3 |
| Op-Amp (LM358 for VU drive) | 4 | $2 |
| Breadboard + Enclosure | 1 set | $5 |
(defproject sound-mixer
:board "teensy40-audio"
:packages [hilos-midi hilos-audio hilos-displays hilos-core])
;; 4-channel mixer
(def num-channels 4)
(def master-volume 0)
;; MIDI CC assignments (for DAW control surface)
(def fader-ccs [10 11 12 13])
(def eq-ccs [
[20 28] ;; Ch1 low/high
[21 29] ;; Ch2 low/high
[22 30]
[23 31]
])
;; State
(def channel-volumes [70 70 70 70])
(def channel-mute [false false false false])
(def channel-solo [false false false false])
(def fader-targets [70 70 70 70])
(def motor-fader-pins [3 5 6 9])
(def vu-analog-chans [0 1 2 3])
(defn setup ()
(midi-begin 0)
(audio-begin)
(serial-begin 115200)
(oled-init)
(oled-clear)
(oled-text "Live Sound Mixer" 0 0)
(oled-text "Ch: Vol Mute/Solo" 0 2)
(oled-display)
(dotimes (i 4)
(pin-mode (nth i motor-fader-pins PWM))
(midi-send-cc (nth i fader-ccs) (nth i channel-volumes)))
(serial-println "=== Live Sound Mixer Ready ==="))
(dotimes (i num-channels)
;; Read analog VU level
(let ((raw (analog-read (nth i vu-analog-chans)))
(level (/ raw 4))) ;; 0-255
;; Motor fader feedback: read physical fader position
(let ((fader-val (analog-read (+ i 4)))
(target-val (nth i channel-volumes)))
;; Move motor fader to target
(when (> (abs (- fader-val target-val)) 5)
(let ((direction (if (> target-val fader-val) HIGH LOW)))
(digital-write (nth i motor-fader-pins) direction))
(wait 10)
(digital-write (nth i motor-fader-pins) LOW)))
;; Read mute/solo buttons
(let ((btn-states (read-shift-buttons)))
(when (bit-check btn-states i) ;; Mute button
(setf channel-mute i (not (nth i channel-mute)))
(midi-send-cc (nth i fader-ccs) (if (nth i channel-mute) 0 (nth i channel-volumes))))
(when (bit-check btn-states (+ i 4)) ;; Solo button
(setf channel-solo i (not (nth i channel-solo)))))
;; Send volume as MIDI CC
(midi-send-cc (nth i fader-ccs) (nth i channel-volumes))
;; VU meter display on OLED (visual bars)
(oled-clear)
(dotimes (j num-channels)
(let ((vol (nth j channel-volumes))
(bar-len (/ (* vol 16) 127))))
(oled-rect-fill 0 (* j 10) 0 bar-len 8))
(oled-display))
(wait 20)))))
Deploy: hilp compile sound-mixer.hil --board teensy40-audio && hilp upload
32 RGB+W buttons with 4.3" TFT touchscreen, rotary encoder, built-in audio interface, HDMI auto-detection, and USB-C passthrough. Runs HIL LISP to define dynamic button layouts, AI overlay logic, and stream status integration.
This isn't just another button box. The StreamDeck Pro MAX is an AI-powered control surface that:
The entire logic — button layouts, color schemes, AI overlay behavior, profile switching, and stream metrics — is written in HIL LISP and recompiled at runtime.
| Component | Qty | Cost |
|---|---|---|
| Teensy 4.1 (with flash) | 1 | $35 |
| 4.3" TFT Touch (ILI9488, 480x320) | 1 | $18 |
| RGB+W NeoPixel Strip (144 LED/m) | 32 (for buttons) | $15 |
| Tactile Button (16mm dome) | 32 | $16 |
| EC11 Rotary Encoder | 1 | $5 |
| PCM5102A DAC + Headphone Amp | 1 | $8 |
| MAX9814 Microphone Preamp | 1 | $4 |
| HDMI EDID Reader (TCA9548A) | 1 | $3 |
| USB-C Hub IC (TY7201) | 1 | $12 |
| 74HC4067 Analog Mux | 2 | $4 |
| 74HC165 Shift Reg (8-bit) | 4 | $4 |
| Enclosure, buttons, cables, etc. | 1 set | $20 |
(defproject streamdeck-pro
:board "teensy41"
:packages [hilos-display hilos-midi hilos-network hilos-audio hilos-core])
;; ── Hardware layout ──
(def btn-rows 4)
(def btn-cols 8)
(def total-buttons 32)
(def neo-strip-1 6)
(def neo-strip-2 7)
(def tft-cs 30)
(def encoder-dt 4)
(def encoder-clk 5)
(def encoder-sw 2)
;; ── Profiles ──
(def profiles [
{:name "PC Streaming"
:buttons [{:label "START" :color [255 0 0] :action obs-start}
{:label "STOP" :color [0 255 0] :action obs-stop}
{:label "SCENE 1" :color [0 100 255] :action obs-scene-1}
{:label "SCENE 2" :color [0 100 255] :action obs-scene-2}
{:label "MIC" :color [0 255 0] :action toggle-mic}
{:label "MUTE" :color [255 0 0] :action mute-all}
{:label "REC" :color [255 255 0] :action obs-record}
{:label "ALERTS" :color [100 255 100] :action toggle-alerts}]}
:layout (grid-layout btn-rows btn-cols)}
{:name "PS5"
:buttons [{:label "CAPTURE" :color [0 255 0] :action start-capture}
{:label "MUTE" :color [255 0 0] :action mute-ps5}
{:label "V/MUTE" :color [255 100 0] :action voice-mute}
{:label "REC" :color [255 255 0] :action obs-record}
{:label "SHOT" :color [255 255 255] :action screenshot}
{:label "CHAT" :color [0 255 255] :action toggle-chat}
{:label "DECK" :color [100 100 255] :action toggle-source}
{:label "END" :color [255 0 0] :action stop-all}]}
:layout (grid-layout btn-rows btn-cols)}
{:name "Nintendo Switch"
:buttons [{:label "START" :color [255 200 0] :action start-capture}
{:label "STOP" :color [255 0 0] :action stop-all}
{:label "SCENE" :color [255 255 0] :action obs-scene-2}
{:label "MIC" :color [0 255 0] :action toggle-mic}
{:label "REC" :color [255 255 0] :action obs-record}
{:label "SHOT" :color [255 255 255] :action screenshot}
{:label "CHAT" :color [0 255 255] :action toggle-chat}
{:label "END" :color [255 0 0] :action stop-all}
;; ... filled to 32
]})
{}}]) ;; last profile
;; ── State ──
(def current-profile 0)
(def button-states [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0])
(def stream-active false)
(def obs-connected false)
(def mic-muted false)
(def encoder-pos 0)
(def last-encoder-pos 0)
;; ── AI Overlay State ──
(def stream-metrics {:viewers 0 :followers 0 :bitrate 0 :fps 0 :scene "" :sources []})
(def ai-overlay-active false)
(def overlay-suggestions [])
(defn setup ()
(usb-host-begin)
(serial-begin 115200)
;; Display init
(tft-init tft-cs)
(tft-fill-screen COLOR_BLACK)
(tft-set-rotation 1)
;; NeoPixel strips
(neopixel-setup neo-strip-1 16)
(neopixel-setup neo-strip-2 16)
(neopixel-clear)
(neopixel-show)
;; Buttons via shift register
(pin-mode 10 OUTPUT) ;; STCP
(pin-mode 12 OUTPUT) ;; SHCP
(digital-write 10 LOW)
;; Encoder
(pin-mode encoder-dt INPUT_PULLUP)
(pin-mode encoder-clk INPUT_PULLUP)
(pin-mode encoder-sw INPUT_PULLUP)
;; HDMI EDID detection
(wire-begin)
(edid-init)
;; Audio
(audio-init)
(audio-set-gain 0.5)
;; Connect to websocket (OBS/OBS WS plugin)
(ws-connect "ws://192.168.1.100:27345")
;; Load saved profile
(load-eeprom-profile)
;; Draw initial UI
(draw-profile-ui)
(update-button-labels)
(neopixel-set-all (profile-color current-profile))
(serial-println "=== StreamDeck Pro MAX v2.0 ===")
(serial-println "Profiles: PC / PS5 / Switch")
(serial-println "Awaiting OBS connection..."))
;; Load button states
(load-button-states)
;; Check HDMI for auto-switch
(when (> (millis) 5000)
(let ((new-profile (detect-hdmi-device)))
(when (not (= new-profile current-profile))
(switch-profile new-profile)
(save-eeprom-profile))))
;; Update NeoPixel feedback
(update-leds)
;; Process encoder
(let ((enc-val (read-encoder)))
(when (not (= enc-val last-encoder-pos))
(set encoder-pos enc-val)
(set last-encoder-pos enc-val)
(let ((diff (- encoder-pos last-encoder-pos)))
(when (> diff 0)
(switch-profile (mod (+ current-profile 1) (len profiles))))
(when (< diff 0)
(switch-profile (mod (- current-profile 1) (len profiles))))))
;; Encoder button = toggle AI overlay
(when (= (digital-read encoder-sw) LOW)
(wait 200) ;; debounce
(setf ai-overlay-active (not ai-overlay-active))
(toggle-ai-overlay))))
;; Update TFT with stream metrics
(update-tft-display)
;; Handle button presses
(let ((pressed (read-buttons)))
(dotimes (i 32)
(when (and (bit-check pressed i)
(not (nth i button-states)))
(button-press i)
(setf (nth i button-states) true))
(when (and (not (bit-check pressed i))
(nth i button-states))
(setf (nth i button-states) false)))))
(wait 10)))
(defn draw-profile-ui ()
(tft-fill-screen COLOR_BLACK)
(let ((profile (nth current-profile profiles)))
(tft-set-cursor 20 30)
(tft-set-text-color COLOR_WHITE)
(tft-set-text-size 2)
(tft-print (str "Profile: " (get profile :name)))
(tft-set-text-size 1)
(tft-set-text-color COLOR_GRAY)
(tft-print (str "Scene: " (get stream-metrics :scene)))
(tft-set-cursor 20 60)
(tft-print (str "Viewers: " (get stream-metrics :viewers)))
(tft-print (str "Bitrate: " (get stream-metrics :bitrate) "kbps"))
(tft-print (str "FPS: " (get stream-metrics :fps)))))
(tft-update))
;; AI overlay suggestions on screen
(when ai-overlay-active
(tft-set-cursor 20 100)
(tft-set-text-color COLOR_CYAN)
(tft-print "AI Suggestions:")
(dotimes (i (min 3 (len overlay-suggestions)))
(let ((suggestion (nth i overlay-suggestions)))
(tft-set-text-color (if (= (get suggestion :action) "scene") COLOR_GREEN COLOR_YELLOW))
(tft-print (str " " (get suggestion :text)))))))
(read-button-states)))
(defn update-leds ()
(let ((profile (nth current-profile profiles)))
(dotimes (i 16)
(let ((btn (nth i (get profile :buttons))))
(when btn
(let ((color (get btn :color)))
(neopixel-set i (first color) (second color) (third color)))))
(neopixel-show))
(dotimes (i 16)
(let ((btn (nth (+ i 16) (get profile :buttons))))
(when btn
(let ((color (get btn :color)))
(neopixel-set (+ i 16) (first color) (second color) (third color)))))
(neopixel-show))))
(defun update-tft-display ()
(draw-profile-ui)
;; Overlay AI suggestion if active
(when (and ai-overlay-active (> (len overlay-suggestions) 0))
(let ((suggestion (first overlay-suggestions)))
(tft-set-cursor 20 140)
(tft-set-text-color (if (= (get suggestion :action) "scene") COLOR_GREEN COLOR_YELLOW))
(tft-print (str "> " (get suggestion :text)))
(tft-update)))))
(defun button-press (idx)
(let ((profile (nth current-profile profiles))
(btn (nth idx (get profile :buttons))))
(when btn
(let ((label (get btn :label))
(color (get btn :color)))
;; Flash white on press
(neopixel-set idx 255 255 255)
(neopixel-show)
(wait 100)
(neopixel-set idx (first color) (second color) (third color))
(neopixel-show)
;; Execute action
(execute-action (get btn :action))
;; Serial log
(serial-print "Button ")
(serial-print idx)
(serial-print ": ")
(serial-println label)))))
(defun execute-action (action)
(case action
(:obs-start (ws-send "{\"request-type\":\"StartStreaming\"}"))
(:obs-stop (ws-send "{\"request-type\":\"StopStreaming\"}"))
(:obs-record (ws-send "{\"request-type\":\"StartRecording\"}"))
(:obs-scene-1 (ws-send "{\"request-type\":\"SetCurrentScene\",\"message-id\":\"1\",\"scene-name\":\"Main\"}"))
(:obs-scene-2 (ws-send "{\"request-type\":\"SetCurrentScene\",\"message-id\":\"2\",\"scene-name\":\"Gameplay\"}"))
(:toggle-mic (setf mic-muted (not mic-muted))
(ws-send (str "{\"request-type\":\"SetVolume\",\"sourceName\":\"Mic\",\"volume\":" (if mic-muted 0.0 1.0) "}")))
(:mute-all (ws-send "{\"request-type\":\"SetVolume\",\"sourceName\":\"Desktop\",\"volume\":0.0}"))
(:toggle-alerts (ws-send "{\"request-type\":\"SetSourceRender\",\"sourceName\":\"Alert\",\"render\":" (if (not stream-active) "true" "false") "}"))
(:start-capture (ws-send "{\"request-type\":\"StartRecording\"}"))
(:stop-all (do (ws-send "{\"request-type\":\"StopStreaming\"}") (ws-send "{\"request-type\":\"StopRecording\"}") ))
(:screenshot (ws-send "{\"request-type\":\"TakeScreenshot\"}"))
(:toggle-chat (ws-send "{\"request-type\":\"SetSourceRender\",\"sourceName\":\"Chat\",\"render\":true}")))
(_ (serial-print "Unknown action: ") (serial-println action)))
;; Handle websocket messages from OBS
(defn ws-message (msg)
;; Parse json message to update stream metrics
(let ((data (json-parse msg)))
(when (type= (get data "update-type") "StreamMetrics")
(setf stream-metrics
{:viewers (get data "viewers")
:followers (get data "followers")
:bitrate (get data "bitrate")
:fps (get data "fps")
:scene (get data "current-scene")})
(update-tft-display))
;; AI overlay suggestion
(when (string-contains (str data) "suggestion")
(setf overlay-suggestions (append overlay-suggestions [(get data "suggestion")]))
(when (> (len overlay-suggestions) 5)
(setf overlay-suggestions (drop-last overlay-suggestions))))))
(defn read-buttons ()
;; Read 4 daisy-chained 74HC165 registers = 32 bits
(digital-write 10 LOW)
(wait 1)
(digital-write 10 HIGH)
(let ((state 0))
(dotimes (i 32)
(let ((bit (digital-read 11)))
(when (= bit HIGH)
(setf state (bit-set state i)))
(digital-write 12 HIGH)
(wait 1)
(digital-write 12 LOW)))
state))
(defn switch-profile (new-profile)
(setf current-profile new-profile)
(update-leds)
(draw-profile-ui)
(neopixel-set-all (profile-color new-profile))
(neopixel-show)
(serial-print "Switched to profile: ")
(serial-println (get (nth new-profile profiles) :name)))
(defn profile-color (idx)
"Color per profile"
(case idx
(0 [80 227 196]) ;; teal for PC
(1 [120 100 255]) ;; purple for PS5
(2 [255 165 0]) ;; orange for Switch
(_ [255 255 255])))
(defn detect-hdmi-device ()
;; Read HDMI EDID to determine device type
(let ((edid (edid-read 0x50)))
(cond
(string-contains edid "Sony" 1) 1) ;; PS5
(string-contains edid "Nintendo" 1) 2) ;; Switch
(_ 0)))) ;; Default PC
(defn toggle-ai-overlay ()
(setf ai-overlay-active (not ai-overlay-active))
(draw-profile-ui)
(tft-update)
(serial-println (str "AI overlay: " (if ai-overlay-active "ON" "OFF"))))
(defn load-button-states ()
;; Load saved button states from EEPROM
(dotimes (i 32)
(setf (nth i button-states) (= (eeprom-read (+ i 100)) 1))))
(defn save-button-states ()
(dotimes (i 32)
(eeprom-write (+ i 100) (if (nth i button-states) 1 0))))
(defn load-eeprom-profile ()
(let ((saved (eeprom-read 0)))
(when (< saved (len profiles))
(setf current-profile saved)))))
Deploy: hilp compile streamdeck-pro.hil --board teensy41 --usb-host-mode && hilp upload
A pattern engine for LED strips that demonstrates the full power of LISP's lambda functions and higher-order programming. Define animations as lambdas that are composed, mapped, and reduced across your hardware.
This project showcases why HIL is a real LISP — not a C-derived language with LISP syntax bolted on. You write animations as first-class lambda functions that can be:
(MAP leds (LAMBDA (i) (* i brightness)))(SET pulse (make-pulse-function :freq 2 :color red))The entire project is written in pure HIL LISP — no C, no preprocessor macros, just S-expressions all the way to the Arduino.
| Component | Qty | Cost |
|---|---|---|
| Arduino Nano | 1 | $5 |
| WS2812B LED Strip (144 LED/m, 1m) | 1 | $8 |
| Rotary Encoder | 1 | $3 |
| Tactile Buttons (mode/ FX) | 2 | $0.50 |
| 0.96" OLED Display (I2C) | 1 | $3 |
| Breadboard + Jumper Wires | 1 set | $3 |
hil monitor to interactively redefine lambdas at runtime!(defproject lambda-animator
:board "nano"
:packages [hilos-neopixel hilos-displays hilos-core])
;; === Lambda Foundation ===
;; A "pattern" is a lambda: (pattern led-index time-ms) -> [r g b]
;; This is the core abstraction — animations are functions.
;; Basic color lambdas
(def red (lambda (i t) [255 0 0]))
(def green (lambda (i t) [0 255 0]))
(def blue (lambda (i t) [0 0 255]))
(def off (lambda (i t) [0 0 0]))
;; Gradient lambda — creates a rainbow across LEDs
(def rainbow (lambda (i t)
(let ((pos (mod (+ i (/ t 10)) 255)))
(cond
((< pos 85) [(* pos 3) (- 255 (* pos 3)) 0])
((< pos 170) [(- 255 (* (- pos 85) 3)) 0 (* (- pos 85) 3)])
(t [0 255 (- 255 (* (- pos 170) 3))])))))
;; Wave lambda — sine wave traveling along the strip
(def wave (lambda (i t)
(let ((brightness (+ 128 (* 127 (sin (/ (+ (* i 10) t) 20)))))
[brightness brightness 255])))
;; Pulse lambda — fades in/out based on time
(def pulse (lambda (i t)
(let ((b (+ 128 (* 127 (sin (/ t 200))))))
[b b (/ b 2)])))
;; === Higher-Order Pattern Combinators ===
;; Apply a modifier to any pattern
(def make-dimmer (lambda (pattern amount)
(lambda (i t)
(let ((base (pattern i t)))
[(/ (* (first base) amount) 100)
(/ (* (second base) amount) 100)
(/ (* (third base) amount) 100)]))))
;; Compose two patterns by adding their colors
(def compose (lambda (pat1 pat2)
(lambda (i t)
(let ((c1 (pat1 i t))
(c2 (pat2 i t)))
[(min 255 (+ (first c1) (first c2)))
(min 255 (+ (second c1) (second c2)))
(min 255 (+ (third c1) (third c2))])))))
;; Apply a pattern only to a range of LEDs
(def sub-pattern (lambda (pattern start end)
(lambda (i t)
(if (and (>= i start) (< i end))
(pattern i t)
[0 0 0]))))
;; Rotate a pattern's index mapping
(def rot (lambda (pattern offset)
(lambda (i t)
(pattern (mod (+ i offset) 144) t))))
;; === Pattern Library: Curated compositions ===
;; A "chillwave" — dimmed rainbow
(def chillwave (make-dimmer rainbow 40))
;; Rainbow + wave overlaid
(def rainbow-wave (compose rainbow wave))
;; Two counter-rotating rainbows
(def dual-spin (compose
(rot rainbow 0)
(rot rainbow 72)))
;; Pulsing rainbow
(def pulse-rainbow (compose rainbow
(make-dimmer pulse 60)))
;; === MAP and REDUCE ===
;; Apply a pattern to all LEDs at time t
(def render (lambda (pattern t)
(map (range 144)
(lambda (i) (pattern i t)))))
;; Layer a list of patterns using REDUCE (functional composition!)
(def layer-patterns (lambda (patterns)
(reduce
(lambda (acc pat) (compose acc pat))
patterns)))
;; === Main state ===
(def patterns [chillwave wave pulse-rainbow rainbow-wave dual-spin
(rot rainbow 36) (rot rainbow 108)])
(def current-pattern 0)
(def current-bpm 60)
(def led-count 144)
(def encoder-pos 0)
(def last-encoder 0)
(defn setup ()
(serial-begin 115200)
(neopixel-setup 6 144)
(oled-init)
(oled-clear)
(oled-text "Lambda Animator" 0 0)
(oled-text (str "Patterns: " (len patterns)) 0 1)
(oled-display)
(pin-mode 2 INPUT_PULLUP) ;; encoder DT
(pin-mode 3 INPUT_PULLUP) ;; encoder CLK
(pin-mode 4 INPUT_PULLUP) ;; mode button
(pin-mode 5 INPUT_PULLUP) ;; FX button
(serial-println "=== Lambda Animator ===")
(serial-println "Use encoder to change pattern and speed"))
;; Read encoder
(let ((enc (read-quadrature 2 3)))
(when (not (= enc encoder-pos))
(set encoder-pos enc)
(set current-pattern (mod enc (len patterns)))
(update-display)))
;; Mode button toggles pattern direction
(when (= (digital-read 4) LOW)
(wait 200)
(set patterns (reverse patterns)))
;; FX button applies dimmer effect
(when (= (digital-read 5) LOW)
(wait 200)
(set current-pattern (mod (+ current-pattern 1) (len patterns))))
;; Render using higher-order function: MAP
(let ((t (millis))
(pattern (nth current-pattern patterns))
(colors (render pattern t)))
(dotimes (i led-count)
(let ((rgb (nth i colors)))
(neopixel-set i
(first rgb)
(second rgb)
(third rgb))))
(neopixel-show)))
(update-display)
(wait 30)))
(defn update-display ()
(oled-clear)
(oled-text "Pattern:" 0 0)
(oled-text (str current-pattern "/" (- (len patterns) 1)) 0 1)
(oled-text (str "BPM:" current-bpm) 0 2)
(oled-display))
;; Live coding: redefine lambdas at runtime via serial!
;; > (set wave (lambda (i t) [(mod t 255) 0 0]))
;; The animation changes immediately!