feat(ir-pico): learn and send IR codes from a Pico on USB

CircuitPython on a Pico H drives an IR transceiver: it prints the code
for any remote button it hears, and sends a code it's given, NEC,
Samsung, or raw pulses for the rest. pico_tty.py drives it over USB
serial. wiring.md says how to put it together.

The flake starts here: a dev shell (nix develop --command make test)
and a check that runs the doctests.

Tested: make install, then make send turned on a Vizio TV.

Generated-by: Claude Opus 5.5
This commit is contained in:
dckc committed 2026-12-02 15:01:57 -06:00
1 parent a06364e041
commit 147bfdc55e
12 files changed
+796

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
# ir-pico: a Raspberry Pi Pico H that drives an IR transceiver, so a computer on USB
# can learn a remote's codes and send them. Wiring: wiring.md.
# Tools come from the flake: nix develop --command make test
#
# flash and install copy files to the Pico's drives, which a desktop automounts
# under /run/media/$USER (or set MEDIA=). console, listen, send, and pulses talk
# to it over USB serial: TTY=/dev/serial/by-id/usb-Raspberry_Pi_Pico_... names one
# Pico for good; the default, /dev/ttyACM0, is whichever came first.
#
# hold BOOTSEL, plug in the Pico, then:
# make flash install
CP_VERSION = 10.3.2
BOARD = raspberry_pi_pico
UF2 = adafruit-circuitpython-$(BOARD)-en_US-$(CP_VERSION).uf2
UF2_URL = https://downloads.circuitpython.org/bin/$(BOARD)/en_US/$(UF2)
MEDIA = /run/media/$(USER)
BOOT = $(MEDIA)/RPI-RP2
CIRCUITPY = $(MEDIA)/CIRCUITPY
IRREMOTE_VERSION = 5.0.8
IRREMOTE_URL = https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_IRRemote/$(IRREMOTE_VERSION)/adafruit_irremote.py
TTY = /dev/ttyACM0
SECONDS = 20
CODE = 20 DF 10 EF
.PHONY: help flash check install console listen send pulses test
.DELETE_ON_ERROR:
## list targets
help:
@awk -f ../make-help.awk $(MAKEFILE_LIST)
## download the CircuitPython firmware (once; kept in cache/)
cache/$(UF2):
mkdir -p cache
curl -fsSL -o $@ $(UF2_URL)
sha256sum $@
## copy CircuitPython onto the Pico in BOOTSEL mode; it reboots as CIRCUITPY
flash: cache/$(UF2)
test -f $(BOOT)/INFO_UF2.TXT || { echo "no $(BOOT): hold BOOTSEL and plug in the Pico" >&2; exit 1; }
cp $< $(BOOT)/ && sync
## the Pico as CircuitPython: its drive, version, and serial port
check:
cat $(CIRCUITPY)/boot_out.txt
ls -l /dev/serial/by-id/ | grep -i pico
## download the IR remote library (once; kept in cache/)
cache/adafruit_irremote-$(IRREMOTE_VERSION).py:
mkdir -p cache
curl -fsSL -o $@ $(IRREMOTE_URL)
sha256sum $@
## copy code.py and its library onto CIRCUITPY; the Pico restarts it
install: code.py ir_commands.py cache/adafruit_irremote-$(IRREMOTE_VERSION).py
test -d $(CIRCUITPY) || { echo "no $(CIRCUITPY)" >&2; exit 1; }
mkdir -p $(CIRCUITPY)/lib
cp cache/adafruit_irremote-$(IRREMOTE_VERSION).py $(CIRCUITPY)/lib/adafruit_irremote.py
cp ir_commands.py $(CIRCUITPY)/ir_commands.py
cp code.py $(CIRCUITPY)/code.py && sync
## talk to code.py over USB serial (needs the dialout group); quit: C-a C-x
console:
picocom -b 115200 $(TTY)
## print the codes code.py hears for SECONDS (default 20)
listen:
python3 -I pico_tty.py $(TTY) listen $(SECONDS)
## send CODE once (default: a Vizio TV's Power, which toggles it)
send:
python3 -I pico_tty.py $(TTY) send $(CODE)
## count raw IR pulses on GP16 for SECONDS, decoder bypassed: is the receiver wired?
pulses:
python3 -I pico_tty.py $(TTY) pulses $(SECONDS)
## doctests for the plain-Python parts; no Pico needed
test:
python3 -I -m doctest ir_commands.py pico_tty.py && echo doctests pass
+98
View File
@@ -0,0 +1,98 @@
"""IR remote on a Pico: learn codes from a remote, and send them.
Runs under CircuitPython (make install copies it to CIRCUITPY). Talks over
the USB serial console (make console):
- Point a remote at the receiver and press a button: it prints the code,
e.g. ``got 20 DF 10 EF``.
- Type ``send 20 DF 10 EF`` and Enter: the emitter sends that code (NEC timing).
Samsung codes carry their name: ``got samsung E0 E0 40 BF``, ``send samsung E0 E0 40 BF``.
- Any other remote (Sony's, ...) comes back raw, mark and space lengths in us:
``got raw 2400 600 1200 ...``; ``send raw 2400 600 1200 ...`` plays it back,
three frames 45 ms apart, as a short press of the button does.
The carrier is 38 kHz for all; Sony's 40 kHz receivers take it, a bit less keenly.
Wiring, IR board (STEMMA JST PH) to Pico, as wiring.md lays it out:
VIN -> 3V3(OUT) (pin 36) GND -> GND (pin 38)
IR In (send) -> GP15 (pin 20) IR Out (receive) -> GP16 (pin 21)
"""
import array
import time
import board
import pulseio
import supervisor
import adafruit_irremote
from ir_commands import RAW_FRAMES, RAW_PERIOD_S, code_text, parse_send, protocol_of, raw_pulses
SEND_PIN = board.GP15
RECEIVE_PIN = board.GP16
# NEC: 9 ms header mark, 4.5 ms space; 560 us marks; 1 = 1690 us space.
NEC = adafruit_irremote.GenericTransmit(
header=[9000, 4500], one=[560, 1690], zero=[560, 560], trail=560
)
# Samsung32: NEC's bits behind a 4.5 ms mark, 4.5 ms space header.
SAMSUNG = adafruit_irremote.GenericTransmit(
header=[4500, 4500], one=[560, 1690], zero=[560, 560], trail=560
)
SENDERS = {"nec": NEC, "samsung": SAMSUNG}
def heard(message):
"""What to print for a burst: its code, raw pulses, or None (noise, NEC repeats)."""
if isinstance(message, adafruit_irremote.NECRepeatIRMessage):
return None
if isinstance(message, adafruit_irremote.IRMessage):
protocol = protocol_of(message.pulses)
if protocol != "raw":
return "got " + code_text(protocol, message.code)
elif len(message.pulses) < 10:
return "unparsed: " + message.reason + " " + str(len(message.pulses)) + " pulses"
return "got " + code_text("raw", raw_pulses(message.pulses))
def send_raw(pulseout, pulses):
durations = array.array("H", pulses)
gap = max(RAW_PERIOD_S - sum(pulses) / 1e6, 0.01)
for i in range(RAW_FRAMES):
if i:
time.sleep(gap)
pulseout.send(durations)
def main():
pulsein = pulseio.PulseIn(RECEIVE_PIN, maxlen=200, idle_state=True)
pulseout = pulseio.PulseOut(SEND_PIN, frequency=38000, duty_cycle=2**15)
decoder = adafruit_irremote.NonblockingGenericDecode(pulsein)
print("ir-pico ready: press a remote button, or type: send 20 DF 10 EF")
while True:
for message in decoder.read():
line = heard(message)
if line:
print(line)
if supervisor.runtime.serial_bytes_available:
line = input()
try:
data = parse_send(line)
except ValueError as err:
print("bad code:", err)
continue
if data is None:
print("say: send [samsung] XX XX ..., or send raw MARK SPACE MARK ...")
continue
protocol, data = data
pulsein.pause() # don't hear our own echo
if protocol == "raw":
send_raw(pulseout, data)
else:
SENDERS[protocol].transmit(pulseout, data)
pulsein.clear()
pulsein.resume()
print("sent", code_text(protocol, data))
main()
+116
View File
@@ -0,0 +1,116 @@
"""Plain-Python parts of the IR remote: no hardware, so they test anywhere.
A code carries its protocol, in the same form both ways (what ``got`` prints,
``send`` takes): NEC bare (``20 DF 10 EF``), the rest by name
(``samsung E0 E0 40 BF``, ``raw 2400 600 1200 ...``).
"""
PROTOCOLS = ("nec", "samsung", "raw")
MAX_RAW = 199 # PulseIn keeps 200
# Sony's devices want 3 frames per press, and other protocols take repeats as a held
# button, so one raw send is 3 frames: one short press.
RAW_FRAMES = 3
RAW_PERIOD_S = 0.045 # frame to frame, as Sony's remotes do
def protocol_of(pulses):
"""Tell NEC from Samsung by the header mark and space, in microseconds; anything else is raw.
The two share bit timing: NEC's header mark is 9 ms; Samsung's is 4.5 ms, then
a 4.5 ms space.
>>> protocol_of([9050, 4480, 560])
'nec'
>>> protocol_of([4520, 4470, 560])
'samsung'
Sony's 2.4 ms header used to pass for Samsung's:
>>> protocol_of([2390, 610, 1200])
'raw'
"""
if pulses[0] > 6750:
return "nec"
if pulses[0] > 3500 and pulses[1] > 3500:
return "samsung"
return "raw"
def raw_pulses(pulses):
"""A burst as a raw code sends it: to the nearest 10 us, ending on a mark.
A raw code is the burst's mark and space lengths in microseconds, mark first.
Sent back, it needs no protocol.
>>> raw_pulses([2394, 606, 1203, 597, 598, 12])
[2390, 610, 1200, 600, 600]
"""
out = [max(10, int(round(p / 10)) * 10) for p in pulses[:MAX_RAW]]
return out if len(out) % 2 else out[:-1]
def parse_send(line):
"""Parse a ``send`` command into its protocol and the bytes (or, raw, pulses) to transmit.
>>> parse_send("send 20 DF 10 EF")
('nec', [32, 223, 16, 239])
>>> parse_send("send samsung E0 E0 40 BF")
('samsung', [224, 224, 64, 191])
>>> parse_send("send raw 2400 600 1200")
('raw', [2400, 600, 1200])
>>> parse_send("send samsung") is None
True
>>> parse_send("hello") is None
True
A raw burst starts and ends on a mark, and each length fits PulseOut's 16 bits:
>>> parse_send("send raw 2400 600")
Traceback (most recent call last):
...
ValueError: raw: an odd number of pulses, 1 to 199
>>> parse_send("send raw 70000")
Traceback (most recent call last):
...
ValueError: raw: each 1 to 65535 us
"""
words = line.split()
if len(words) < 2 or words[0] != "send":
return None
protocol = "nec"
if words[1] in PROTOCOLS:
protocol, words = words[1], words[1:]
if len(words) < 2:
return None
if protocol != "raw":
return protocol, [int(w, 16) for w in words[1:]]
pulses = [int(w) for w in words[1:]]
if len(pulses) % 2 == 0 or len(pulses) > MAX_RAW:
raise ValueError("raw: an odd number of pulses, 1 to %d" % MAX_RAW)
if not all(0 < p < 65536 for p in pulses):
raise ValueError("raw: each 1 to 65535 us")
return protocol, pulses
def hex_bytes(data):
"""Format bytes as the console shows them.
>>> hex_bytes((32, 223, 16, 239))
'20 DF 10 EF'
"""
return " ".join("%02X" % b for b in data)
def code_text(protocol, data):
"""A code as listen reports it and send takes it: NEC bare, others named.
>>> code_text("nec", (32, 223, 16, 239))
'20 DF 10 EF'
>>> code_text("samsung", (224, 224, 103, 152))
'samsung E0 E0 67 98'
>>> code_text("raw", [2400, 600, 1200])
'raw 2400 600 1200'
"""
if protocol == "raw":
return "raw " + " ".join(str(p) for p in data)
return hex_bytes(data) if protocol == "nec" else protocol + " " + hex_bytes(data)
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env python3
r"""Talk to the Pico's code.py over USB serial: listen for codes, send one, or count raw pulses.
Usage:
pico_tty.py TTY listen SECONDS print what code.py hears ("got 20 DF 10 EF")
pico_tty.py TTY send [samsung] HEX... send one code ("send 20 DF 10 EF"; NEC unless named)
pico_tty.py TTY send raw US... send pulses: mark, space, mark... in microseconds
pico_tty.py TTY repeat N GAP_MS CODE... send it N times, GAP_MS apart: N presses of a button
pico_tty.py TTY pulses SECONDS stop code.py, count raw pulses on GP16, restart it
>>> send_line(['20', 'df', '10', 'ef'])
b'send 20 DF 10 EF\r'
>>> send_line(['samsung', 'e0', 'e0', '40', 'bf'])
b'send samsung E0 E0 40 BF\r'
>>> send_line(['raw', '2400', '600', '1200'])
b'send raw 2400 600 1200\r'
>>> send_line(['20', 'DFX'])
Traceback (most recent call last):
...
SystemExit: not a byte: DFX
>>> send_line(['raw', '2400', '6e2'])
Traceback (most recent call last):
...
SystemExit: not microseconds: 6e2
Wait for the Pico's confirmations, not a fixed 2 s, so presses can come quickly:
>>> class Port:
... def __init__(self, lines): self.lines = lines
... def readline(self): return self.lines.pop(0) if self.lines else b''
>>> import io
>>> out = io.StringIO()
>>> tick = iter(range(100)).__next__
>>> confirmations(Port([b'sent 20 DF\r\n', b'got 20 DF\r\n', b'sent 20 DF\r\n']), 2, 5, tick, out)
2
>>> out.getvalue()
'sent 20 DF\ngot 20 DF\nsent 20 DF\n'
>>> confirmations(Port([b'bad code: x\r\n']), 1, 3, iter(range(100)).__next__, io.StringIO())
0
"""
import logging
GP16_PULSES = [
b'import board, pulseio, time\r',
b'pin = pulseio.PulseIn(board.GP16, maxlen=1000, idle_state=True)\r',
]
PROTOCOLS = ('nec', 'samsung', 'raw')
def send_line(words):
protocol = [words[0]] if words and words[0] in PROTOCOLS else []
octets = words[len(protocol):]
if protocol == ['raw']:
for us in octets:
if not us.isdigit() or len(us) > 5:
raise SystemExit(f'not microseconds: {us}')
return ('send ' + ' '.join(words) + '\r').encode()
for o in octets:
if len(o) != 2 or any(c not in '0123456789abcdefABCDEF' for c in o):
raise SystemExit(f'not a byte: {o}')
return ('send ' + ' '.join(protocol + [o.upper() for o in octets]) + '\r').encode()
def lines_for(port, seconds, now, stdout):
end = now() + seconds
while now() < end:
line = port.readline()
if line:
stdout.write(line.decode(errors='replace').rstrip() + '\n')
stdout.flush()
def confirmations(port, count, seconds, now, stdout):
"""Echo the Pico's lines until it has said "sent" count times, or seconds pass; return how many."""
end = now() + seconds
seen = 0
while seen < count and now() < end:
line = port.readline()
if line:
text = line.decode(errors='replace').rstrip()
stdout.write(text + '\n')
stdout.flush()
seen += text.startswith('sent ')
return seen
def repl(port, cmd, pause):
port.write(cmd)
pause(0.3)
return port.read(4096)
def pulses(port, seconds, pause, stdout):
for cmd in [b'\x03', b'\x03', b'\r'] + GP16_PULSES:
repl(port, cmd, pause)
logging.info('counting pulses for %ss: press a remote button now', seconds)
pause(seconds)
out = repl(port, b"print('n=', len(pin))\r", pause).decode(errors='replace')
counts = [ln for ln in out.splitlines() if ln.startswith('n=')]
stdout.write((counts[-1] if counts else repr(out)) + '\n')
repl(port, b'pin.deinit()\r', pause)
repl(port, b'\x04', pause) # soft reboot: code.py runs again
def main(argv, open_port, now, pause, stdout):
[_, tty, verb, *args] = argv
port = open_port(tty)
if verb == 'listen':
logging.info('listening for %ss', args[0])
lines_for(port, float(args[0]), now, stdout)
elif verb == 'send':
port.write(send_line(args))
confirmations(port, 1, 2, now, stdout)
elif verb == 'repeat':
[times, gap_ms, *octets] = args
line = send_line(octets)
for i in range(int(times)):
if i:
pause(int(gap_ms) / 1000)
port.write(line)
confirmations(port, int(times), 2, now, stdout)
elif verb == 'pulses':
pulses(port, float(args[0]), pause, stdout)
else:
raise SystemExit(__doc__)
if __name__ == '__main__':
def _script_io():
from sys import argv, stdout
from time import sleep, time
import serial
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%H:%M:%S')
main(list(argv), lambda tty: serial.Serial(tty, 115200, timeout=0.5), time, sleep, stdout)
_script_io()
+48
View File
@@ -0,0 +1,48 @@
# Wiring the IR emitter
A Raspberry Pi Pico H drives an Adafruit IR transceiver, so a computer on USB can learn a remote's codes and send them. The pins here must match [code.py](code.py)'s.
## Parts
- [Adafruit IR remote transceiver](https://www.adafruit.com/product/5990) (5990): a 940 nm emitter and a 38 kHz receiver, STEMMA JST PH 2 mm
- Raspberry Pi Pico H: the H has its headers soldered on
- a breakaway 0.1" header strip: 4 pins for the IR board
- a breadboard and 4 female-to-female jumpers, or short wires soldered direct, with heat shrink, for something more compact
- a micro-USB **data** cable: a charge-only cable gives power but no serial port
No soldering at all, by mail: Adafruit's [JST PH 2 mm 4-pin to female socket cable](https://www.adafruit.com/product/3950) (3950) in place of the header pins and jumpers. Not a STEMMA QT or Qwiic cable: that's JST SH, 1 mm, and won't fit.
## On a breadboard
The Pico H plugs straight in, straddling the center gap. The IR board needs 4 pins first: snap 4 off the breakaway header strip, plug their long ends into the breadboard, set the board on them, and solder.
Breadboard held long side horizontal: columns 1–30 across, rows a–j down, the gap between e and f. Each column's a–e is one strip, and f–j another.
```
1 2 3 4 5 ... 20 23 24 25 26
a . . . . . . o o o o <- IR board's 4 pins; board off the top edge
b . . G . P R . . . .
c # # # # # ... # . . . . <- Pico pins 40..21: c1 VBUS, c3 GND, c5 3V3(OUT), c20 GP16
d . . . . . . . . . .
e . . . . . . . . . .
------------------- center gap -------------------
f . . . . . .
g . . . . . .
h # # # # # ... # <- Pico pins 1..20: h20 GP15
i . . . . . S
j . . . . . .
^ Pico's USB end at column 1
```
Four jumpers, from the Pico's strips to the IR board's (read the board's labels for which pin is which):
| from | Pico pin | to IR board | |
|---|---|---|---|
| P: b5 | 36, 3V3(OUT) | VIN | power |
| G: b3 | 38, GND | GND | |
| R: b20 | 21, GP16 | IR Out | receive |
| S: i20 | 20, GP15 | IR In | send; crosses the gap |
Power is 3.3 V, not 5 V: the Pico's pins can't take 5 V, and the receiver's output may be pulled up to VIN. The emitter reaches less far at 3.3 V; across a room should be fine.
Then `make flash install` (see [the Makefile](Makefile)), and `make pulses` to see that the receiver is wired: press any remote button at it while it counts.