Code
Getting the Program Files
To use the application, you need to obtain code.py with the program, and the other project files to place on the Fruit Jam CIRCUITPY drive.
Thankfully, this can be done in one go. In the example below, click the Download Project Bundle button below to download the necessary libraries, the code.py file, and other project files in a zip file.
Connect your board to your computer via a known good data+power USB cable. The board should show up in your File Explorer/Finder (depending on your operating system) as a flash drive named CIRCUITPY.
Extract the contents of the zip file, copy the lib directory files to CIRCUITPY/lib. Copy the code.py file and other project files to your CIRCUITPY drive. The program should self start.
# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""Direct RTL-SDR AM/FM/weather reception on Fruit Jam, audio on the 3.5 mm jack."""
import time
import supervisor
from am_fm_radio import run
from radio_ui_am_fm import RadioUI
# pylint: disable=broad-except
supervisor.runtime.autoreload = False
while True:
try:
run()
except Exception as error:
print("RADIO_ERROR", type(error).__name__, str(error))
try:
RadioUI().draw(
"RECONNECTING", 0, "receiver stopped; retrying shortly", str(error)[:48]
)
except Exception:
pass
time.sleep(3)
Drive Structure
After copying the files, your drive should look like the listing below. It can contain other files as well, but must contain these at a minimum.
In this project code.py contains only very high level imports and functionality. It defers to the other files included in the project for implementing all of the details of the functionality.
am_fm_radio.py
This file contains a high level run() function that can accept several arguments to start the radio tuner running with a specific configuration. A few of the most useful are:
-
band- Which band the radio will begin playing AM, FM, or WX. -
fm_frequency,am_frequency, andwx_frequency- for setting the initial station tuning for each of the different band types. -
volume- To set the volume level of playback from the 3.5mm jack.
Change the value of the arguments passed to this function inside of code.py if you want to alter the startup behavior of the radio.
# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""RTL-SDR AM/FM/NOAA weather receiver with audio on the 3.5 mm jack.
FM (88-108 MHz) and NOAA Weather Radio (162.400-162.550 MHz) work with any
supported dongle. AM (530-1700 kHz) uses the RTL2832U's direct sampling input,
which the Nooelec NESDR SMArt v5 wires and FC0013 dongles do not. AM may also
require longer or outdoor antenna.
"""
# The USB bulk ring and the audio DMA buffers can only use internal SRAM, but
# CircuitPython also grows its Python heap there, in areas as large as the
# heap already is, whenever such an area still fits. Holding a block bigger
# than all of SRAM puts it in PSRAM and makes every later area at least that
# big, so the heap stops taking SRAM. Keep this before the other imports.
# pylint: disable=wrong-import-position
_heap_ballast = bytearray(1024 * 1024)
import time
import gc
import sys
import json
import math
import board
import keypad
import supervisor
import usb.core
import usb_host_bulk
import _fm_turbo95 as _fm_turbo
import _ham_dsp
from ham_tuner import open_ham_receiver
from radio_ui_am_fm import RadioUI, format_frequency
from radio_presets import Presets, SAVE_PATH
from jack_audio import JackAudio
# pylint: disable=too-many-locals, too-many-branches, too-many-statements
# pylint: disable=too-many-arguments
# Built-in presets, in Hz. Stations saved on the radio (hold B2, or s and x)
# go in /saves/am_fm_radio.json, which can also take these out.
FM_PRESETS = (93900000, 93100000, 97100000, 101100000, 104300000, 107500000, 88500000)
# Add your local AM stations here, in Hz.
AM_PRESETS = (610000,)
# FM dial: B1/B2 and the arrow keys step 200 kHz and wrap at the band edges.
FM_STEP, FM_MIN, FM_MAX = 200000, 88100000, 107900000
# AM dial for the Americas: 10 kHz channels, 530-1700 kHz. For Europe, Africa,
# Asia and Australia use 9 kHz channels instead:
# AM_STEP, AM_MIN, AM_MAX = 9000, 531000, 1602000
AM_STEP, AM_MIN, AM_MAX = 10000, 530000, 1700000
# NOAA Weather Radio (US and Canada): seven narrowband FM channels 25 kHz
# apart, listed here as WX1..WX7, the usual channel numbering.
WX_CHANNELS = (
162550000,
162400000,
162475000,
162425000,
162450000,
162500000,
162525000,
)
WX_STEP, WX_MIN, WX_MAX = 25000, 162400000, 162550000
# Typed frequencies are accepted over these slightly wider ranges. Typed
# weather frequencies snap to the nearest channel.
FM_LIMITS = (87500000, 108000000)
AM_LIMITS = (520000, 1710000)
WX_LIMITS = (162387500, 162562500)
# Signal bar range in dB for each band. FM shows the wideband I/Q power, AM
# and weather the power in the channel filter. Indoors, on a NESDR SMArt v5,
# empty AM channels read about -40 dB, empty weather channels about -32 dB
# and a local weather station about -15 dB.
FM_LEVEL_DB = (-30, 0)
AM_LEVEL_DB = (-45, -10)
WX_LEVEL_DB = (-35, -10)
# Added to the headphone volume on AM and weather, so switching bands does
# not jump in loudness (the AM demodulator has its own AGC; weather voice
# measured about 6 dB louder than FM music).
AM_VOLUME_OFFSET = 0.0
WX_VOLUME_OFFSET = -6.0
# The AM demodulator has no DC removal, so the hardware centre sits above the
# dial frequency, away from the receiver's DC offset. Tuning inside the window
# only moves the DSP oscillator, which is instant and gapless; leaving it
# retunes the hardware.
AM_CENTRE_OFFSET = 56000 # centre - dial after a hardware retune
AM_WINDOW = (12000, 100000) # allowed centre - dial
# Weather uses the same demodulator in NFM mode. With the hardware centre
# between the channels, all seven are 12.5-87.5 kHz from it, so changing
# channel never retunes the hardware.
WX_CENTRE = 162487500
HAM_NFM, HAM_AM = 0, 1 # _ham_dsp mode numbers
HOLD_MS = 650 # a button held this long is a hold, not a press
# Serial console escape sequences (after ESC) for the up and down arrow keys,
# in normal and application cursor mode, and the tuning action they map to.
ARROW_KEYS = {"[A": "+", "OA": "+", "[B": "-", "OB": "-"}
NO_AM = "AM needs a direct-sampling dongle (NESDR SMArt v5)"
def wx_channel(hz):
"""Return the NOAA weather channel nearest to hz."""
hz = (hz - WX_MIN + WX_STEP // 2) // WX_STEP * WX_STEP + WX_MIN
return min(WX_MAX, max(WX_MIN, hz))
def parse_frequency(text):
"""Return (band, Hz) for a typed frequency, without single-precision floats.
'101.1', '101.1mhz', '88.5' -> FM; '610', '610khz', '1190' (whole numbers
in AM_LIMITS are kHz) and '0.61' (MHz below 2) -> AM; '162.55', '162.4'
-> WX (snapped to a channel). A number with no unit and no point is
otherwise MHz below 2000 and Hz above.
"""
text = text.strip().lower().replace(" ", "")
scale = None
for unit, factor in (("mhz", 1000000), ("khz", 1000), ("hz", 1)):
if text.endswith(unit):
text = text[: -len(unit)]
scale = factor
break
whole, frac = text.split(".", 1) if "." in text else (text, "")
if not (whole + frac).isdigit():
raise ValueError(text)
value = int(whole or "0")
if scale is None:
if frac:
scale = 1000000
elif AM_LIMITS[0] // 1000 <= value <= AM_LIMITS[1] // 1000:
scale = 1000
elif value < 2000:
scale = 1000000
else:
scale = 1
digits = len(str(scale)) - 1
hz = value * scale
if frac and digits:
hz += int((frac + "000000")[:digits])
if FM_LIMITS[0] <= hz <= FM_LIMITS[1]:
return "FM", hz
if AM_LIMITS[0] <= hz <= AM_LIMITS[1]:
return "AM", hz
if WX_LIMITS[0] <= hz <= WX_LIMITS[1]:
return "WX", wx_channel(hz)
raise ValueError(text)
def fm_level_db(iq):
# Power of the whole 256 kHz I/Q block with its DC offset removed, in dB
# relative to a full-scale 8-bit sine. The demodulator's digital AGC is off
# and the tuner gain is fixed, so this follows the antenna signal.
n, sum_i, sum_q, sumsq = _fm_turbo.signal_stats(iq)[:4]
power = (n * sumsq - sum_i * sum_i - sum_q * sum_q) / (n * n)
return 4.342944819 * math.log(power / 16256.25 + 1e-12)
def ham_level_db(power_q16):
# Mean AM or weather channel power (Q16, from _ham_dsp.status), in dB
# relative to a full-scale 8-bit sine.
return 4.342944819 * math.log(power_q16 / 65536 / 16256.25 + 1e-12)
def start_stream(d, audio):
# The audio DMA buffers and the bulk ring must both be in internal SRAM.
# Start the audio first (its FIFO is allocated later, on first write),
# then take the largest ring that fits: 64 ms of USB buffering, or 32 ms.
audio.start()
for size in (32768, 16384):
try:
return usb_host_bulk.InStream(d, 0x81, buffer_size=size), size
except MemoryError:
pass
audio.stop()
raise MemoryError("no SRAM for the USB bulk ring")
def run(
seconds=0,
band="FM",
fm_frequency=93900000,
am_frequency=AM_PRESETS[0],
wx_frequency=WX_CHANNELS[0],
gain=400,
controls=True,
volume=-10.0,
display=True,
direct_input="Q",
commands=(),
log_every=5,
presets_file=SAVE_PATH,
):
"""Run the receiver. seconds=0 runs forever.
band ('FM', 'AM' or 'WX' for NOAA weather) picks the starting band; each
band starts on its own frequency (Hz). commands is a list of (seconds,
command) pairs, such as (5, 'b') or (8, 'f610'), fed to the command
handler for unattended tests. Presets are saved in presets_file (None
keeps them in memory only).
"""
supervisor.runtime.autoreload = False
# Free the garbage left by compiling ham_tuner.py first, so where the
# display bitmaps land (and so how long a redraw takes) is repeatable.
gc.collect()
ui = RadioUI() if display else None
freq = {"FM": fm_frequency, "AM": am_frequency, "WX": wx_channel(wx_frequency)}
presets = Presets(
{"FM": FM_PRESETS, "AM": AM_PRESETS, "WX": WX_CHANNELS},
parse_frequency,
presets_file,
)
muted = False
notice = None
commands = sorted(commands)
def draw():
if not ui:
return 0
t = time.monotonic_ns()
status = "LIVE %s / 3.5MM JACK" % band
if muted:
status += " / MUTED"
if band == "AM":
line1 = "AM, direct sampling, %d kHz steps" % (AM_STEP // 1000)
footer = "AM needs an outdoor antenna"
elif band == "WX":
line1 = "NOAA weather channel WX%d, narrowband FM" % (
WX_CHANNELS.index(freq["WX"]) + 1
)
footer = "NOAA WEATHER RADIO (US / CANADA)"
else:
line1 = "256 ksample/s -> 32 kHz mono"
footer = "RTL-SDR RECEIVER"
ui.draw(
notice or status,
freq[band],
line1,
"receiving directly from the antenna",
footer,
)
return time.monotonic_ns() - t
audio = None
keys = None
d = None
stream = None
if ui:
ui.draw("CONNECTING", freq[band], "looking for the USB receiver", "")
for _ in range(20):
d = usb.core.find(idVendor=0x0BDA, idProduct=0x2838)
if d:
break
time.sleep(0.1)
if not d:
raise RuntimeError("No RTL-SDR receiver found on Fruit Jam USB")
# Let USB enumeration and receiver power settle after a full MCU reset.
time.sleep(0.5)
d.set_configuration()
radio = open_ham_receiver(d, direct_input=direct_input)
# Only a dongle with direct sampling (R82xx here) tunes below 25 MHz.
has_am = radio.min_frequency <= AM_LIMITS[0]
if band == "AM" and not has_am:
band = "FM"
notice = NO_AM
def centre_for(b, hz):
# Hardware centre frequency for station hz on band b.
if b == "AM":
return hz + AM_CENTRE_OFFSET
return WX_CENTRE if b == "WX" else hz
def band_volume():
return volume + {"AM": AM_VOLUME_OFFSET, "WX": WX_VOLUME_OFFSET}.get(band, 0)
centre = centre_for(band, freq[band])
radio.initialize(frequency=centre, sample_rate=256000, gain=gain)
radio.hold_buffer()
fm_state = bytearray(512)
ham_state = bytearray(8192) # AM and weather
def configure_ham():
_ham_dsp.configure(
ham_state,
HAM_AM if band == "AM" else HAM_NFM,
freq[band] - centre,
0,
1 if radio.conjugate else 0,
)
try:
audio = JackAudio(volume=band_volume())
if band != "FM":
configure_ham()
total = output = 0
lost_before = 0 # packets lost by streams already stopped
retunes = 0
max_dsp = 0
dsp_total = 0
dsp_calls = 0
max_loop = 0
max_draw = 0 # redraws while the stream runs
max_redraw = 0 # full redraws while it is stopped
pressed_at = [None, None, None]
line = None
esc = None # partial escape sequence from the serial console
keys = keypad.Keys(
(board.BUTTON1, board.BUTTON2, board.BUTTON3),
value_when_pressed=False,
pull=True,
)
draw()
gc.collect()
radio.reset_buffer()
stream, ring = start_stream(d, audio)
iq = bytearray(8192)
iqv = memoryview(iq)
filled = 0
start = time.monotonic()
last_log = start
last_level = start
level = None
last_ns = time.monotonic_ns()
print(
"LIVE_START",
json.dumps(
{
"ring_size": ring,
"band": band,
"frequency": freq[band],
"centre": centre,
"sample_rate": radio.sample_rate,
"gain": gain,
"tuner": radio.tuner_name,
"direct": radio.direct,
"presets": {b: presets.stations(b) for b in freq},
}
),
)
def stop_stream():
nonlocal lost_before
lost_before += stream.lost_packets
stream.deinit()
audio.stop()
audio.clear()
radio.hold_buffer()
def restart_stream():
nonlocal stream, ring, filled, last_ns
radio.reset_buffer()
filled = 0
# pylint: disable=unused-variable
stream, ring = start_stream(d, audio)
# loop_max_ms tracks stalls while receiving, not this stop.
last_ns = time.monotonic_ns()
def tune(new_band, hz):
# Tune to hz, switching band if needed. Returns the redraw time.
nonlocal band, centre, fm_state, ham_state, notice, retunes, level
if new_band == "AM" and not has_am:
notice = NO_AM
print("NO_AM", radio.tuner_name)
return 0
notice = None
switching = new_band != band
if switching:
level = None # the other band's reading means nothing here
band = new_band
freq[band] = hz
if not switching and (
band == "WX" # every channel is within reach of WX_CENTRE
or (band == "AM" and AM_WINDOW[0] <= centre - hz <= AM_WINDOW[1])
):
configure_ham()
return 0
# Stop, retune and restart without pausing in between: in testing,
# a retune after the FIFO was held for several seconds failed with
# a USB pipe error. Leaving AM fully re-initializes the tuner
# (gain included) inside radio.tune().
stop_stream()
centre = centre_for(band, hz)
radio.tune(centre)
radio.hold_buffer()
retunes += 1
if band == "FM":
fm_state = bytearray(512)
else:
if switching:
ham_state = bytearray(8192)
configure_ham()
if switching:
audio.dac.dac_volume = band_volume()
# A full redraw outlasts the USB ring, so do it while stopped.
dt = draw()
restart_stream()
return dt
def store(add):
# Save (add=True) or remove the station on the dial as a preset.
# Returns the redraw time.
nonlocal notice
hz = freq[band]
name = "%s %s" % (band, format_frequency(hz))
if not presets.add(band, hz) if add else presets.remove(band, hz):
notice = "%s IS %s A PRESET" % (name, "ALREADY" if add else "NOT")
return 0
notice = "%s PRESET %s" % ("SAVED" if add else "REMOVED", name)
if not presets_file:
return 0
# Writing flash stalls the chip for longer than the USB ring
# lasts, so stop the stream around it, as for a retune.
stop_stream()
try:
presets.save()
except OSError as error:
# The change still holds until the radio restarts.
print("PRESETS_NOT_SAVED", error)
notice = "NOT SAVED: %s" % error
dt = draw()
restart_stream()
return dt
while not seconds or time.monotonic() - start < seconds:
now = time.monotonic()
t = time.monotonic_ns()
max_loop = max(max_loop, t - last_ns)
last_ns = t
audio.service()
n = stream.readinto(iqv[filled:])
if n == 0:
raise RuntimeError("USB stream ended")
n = n or 0
filled += n
total += n
if filled == len(iq):
# One block of 4096 I/Q samples gives 512 PCM samples.
out = audio.write_view_bytes(512)
t = time.monotonic_ns()
if band == "FM":
count = _fm_turbo.process(iq, out, fm_state) // 2
else:
count = _ham_dsp.process(iq, out, ham_state) // 2
dt = time.monotonic_ns() - t
dsp_total += dt
dsp_calls += 1
max_dsp = max(max_dsp, dt)
if not muted:
audio.commit(count)
output += count
if now - last_level >= 0.25:
if band == "FM":
level = fm_level_db(iq)
low, high = FM_LEVEL_DB
else:
level = ham_level_db(_ham_dsp.status(ham_state)[0])
low, high = AM_LEVEL_DB if band == "AM" else WX_LEVEL_DB
if ui:
ui.level((level - low) / (high - low))
last_level = now
filled = 0
audio.service()
elif not n:
time.sleep(0.0005)
# Buttons act on release, so a hold can be told from a press:
# B1 lower / hold: next band, B2 higher / hold: save or remove
# this preset, B3 mute / hold: next preset.
action = None
event = keys.events.get()
if event:
k = event.key_number
if event.pressed:
pressed_at[k] = event.timestamp
elif pressed_at[k] is not None:
held = ((event.timestamp - pressed_at[k]) & 0x1FFFFFFF) >= HOLD_MS
pressed_at[k] = None
action = (
("b" if held else "-"),
("t" if held else "+"),
("p" if held else "m"),
)[k]
if supervisor.runtime.serial_bytes_available:
# 'f 101.1' or 'f610' + Enter tunes directly; other characters
# are single-key commands. Backspace edits the entry, and
# cancels it once it is empty.
ch = sys.stdin.read(1)
if ch == "\x1b":
esc, ch = "", ""
elif esc is not None:
# Inside an escape sequence: up/down arrows tune like
# + and -. Swallow any other sequence up to its final byte.
esc += ch
if (
len(esc) > 1
and "@" <= ch <= "~"
or esc[0] not in "[O"
or len(esc) > 8
):
if line is None:
action = ARROW_KEYS.get(esc, action)
esc = None
ch = ""
if not ch: # consumed by an escape sequence
pass
elif line is not None:
if ch in "\r\n":
action = "f" + line
line = None
elif ch in "\x08\x7f":
# pylint: disable=unsubscriptable-object
line = line[:-1] if line else None
else:
line += ch
if not action and controls and ui:
t = time.monotonic_ns()
ui.entry(None if line is None else "f" + line)
max_draw = max(max_draw, time.monotonic_ns() - t)
elif ch in "fF":
line = ""
if controls and ui:
t = time.monotonic_ns()
ui.entry("f")
max_draw = max(max_draw, time.monotonic_ns() - t)
else:
action = ch.lower()
if commands and now - start >= commands[0][0]:
action = commands.pop(0)[1]
if not controls:
action = None
if action:
dt = 0
if action in ("+", "-"):
f = freq[band]
if band == "FM":
f += FM_STEP if action == "+" else -FM_STEP
low, high = FM_MIN, FM_MAX
elif band == "WX":
f += WX_STEP if action == "+" else -WX_STEP
low, high = WX_MIN, WX_MAX
else:
# Step to the next channel on the AM_STEP grid.
if action == "+":
f = (f // AM_STEP + 1) * AM_STEP
else:
f = (f - 1) // AM_STEP * AM_STEP
low, high = AM_MIN, AM_MAX
if f > high:
f = low
if f < low:
f = high
dt = tune(band, f)
elif action == "p":
stations = presets.stations(band)
f = freq[band]
if stations:
idx = stations.index(f) if f in stations else -1
dt = tune(band, stations[(idx + 1) % len(stations)])
else:
notice = "NO %s PRESETS: HOLD B2 OR PRESS s TO SAVE" % band
elif action in ("s", "x", "t"):
# s save, x remove, t (B2 hold) whichever applies.
if action == "t":
action = "x" if freq[band] in presets.stations(band) else "s"
dt = store(action == "s")
elif action in ("b", "a", "n", "w"):
if action == "b":
# FM -> AM -> weather -> FM, without AM if not possible.
order = ("FM", "AM", "WX") if has_am else ("FM", "WX")
new_band = order[(order.index(band) + 1) % len(order)]
else:
new_band = {"a": "AM", "n": "FM", "w": "WX"}[action]
if new_band != band:
dt = tune(new_band, freq[new_band])
elif action == "m":
muted = not muted
notice = None
audio.clear()
print("MUTE", muted)
elif action[0] == "f":
try:
dt = tune(*parse_frequency(action[1:]))
except ValueError:
print("BAD_FREQUENCY", action[1:].strip())
if ui:
ui.entry(None)
action = None
else:
action = None
if action:
max_redraw = max(max_redraw, dt)
max_draw = max(max_draw, draw())
print(
"TUNED",
json.dumps(
{
"band": band,
"frequency": freq[band],
"centre": centre,
"muted": muted,
"notice": notice,
"retunes": retunes,
"presets": presets.stations(band),
}
),
)
if now - last_log >= log_every:
# Lost packets are a short audio gap, not a reason to stop.
lost = lost_before + stream.lost_packets
print(
"LIVE",
json.dumps(
{
"band": band,
"frequency": freq[band],
"muted": muted,
"level_db": level,
"seconds": now - start,
"bytes": total,
"pcm_samples": output,
"ring_size": ring,
"retunes": retunes,
"dsp_max_ms": max_dsp / 1000000,
"loop_max_ms": max_loop / 1000000,
"draw_max_ms": max_draw / 1000000,
"redraw_max_ms": max_redraw / 1000000,
"audio": audio.stats(),
"lost_packets": lost,
}
),
)
last_log = now
lost = lost_before + stream.lost_packets
print(
"RESULT",
json.dumps(
{
"band": band,
"fm_frequency": freq["FM"],
"am_frequency": freq["AM"],
"wx_frequency": freq["WX"],
"seconds": time.monotonic() - start,
"bytes": total,
"pcm_samples": output,
"level_db": level,
"retunes": retunes,
"dsp_max_ms": max_dsp / 1000000,
"dsp_mean_ms": dsp_total / max(1, dsp_calls) / 1000000,
"loop_max_ms": max_loop / 1000000,
"draw_max_ms": max_draw / 1000000,
"redraw_max_ms": max_redraw / 1000000,
"demod_read_retries": radio.demod_read_retries,
"audio": audio.stats(),
"lost_packets": lost,
}
),
)
finally:
try:
if stream is not None:
stream.deinit()
finally:
try:
if audio is not None:
audio.deinit()
finally:
if keys is not None:
keys.deinit()
print("~~END~~")
ham_tuner.py
This contains RTL2832U receiver drivers for the R82xx (Nooelec NESDR SMArt v5) and FC0013 (Fitipower) SDR devices.
# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# R82xx Derived from works:
# Original copyright (C) 2012-2014 Steve Markgraf; 2012 Dimitri Stolnikov;
# (C) 2013 Mauro Carvalho Chehab and Steve Markgraf (R82xx).
#
# FC0013 Derived from works:
# Original copyright (C) 2012 Hans-Frieder Vogt;
# partially based on driver code from Fitipower,
# (C) 2010 Fitipower Integrated Technology Inc;
# modified for use in librtlsdr (C) 2012 Steve Markgraf.
"""RTL2832U receiver drivers for the ham radio example.
* R82xx (NESDR SMArt v5): 25.6 MHz - 1.76 GHz through the tuner, using the
full librtlsdr frequency-range table (tracking filter, RF mux, open drain).
Below that, the RTL2832U samples the antenna directly ("direct sampling",
0.1 - 25 MHz on the SMArt v5) and the tuner is put in standby.
* FC0013: 22 MHz - 1.1 GHz. No HF.
open_ham_receiver() probes the dongle and returns the matching driver.
tune() takes the hardware centre frequency. The demodulator is told
`conjugate` because some paths deliver an inverted spectrum.
No USB discovery or configuration is performed automatically. Pass an already
configured usb.core.Device. All reads use caller provided buffers as required
by CircuitPython. No claim of lossless capture is made: transport must
separately sustain 2 * sample_rate bytes/second.
"""
# pylint: disable=too-many-lines, import-outside-toplevel, unused-variable, too-many-locals, too-many-branches,
# pylint: disable=too-many-statements, protected-access
import time
CRYSTAL = 28800000
# RTL2832U baseband FIR filter coefficients.
_FIR = (-54, -36, -41, -40, -32, -14, 14, 53, 101, 156, 215, 273, 327, 372, 404, 421)
# -- R82xx tables ----------------------------------------------------------
_R82XX_INIT = bytes(
(
0x83,
0x32,
0x75,
0xC0,
0x40,
0xD6,
0x6C,
0xF5,
0x63,
0x75,
0x68,
0x6C,
0x83,
0x80,
0x00,
0x0F,
0x00,
0xC0,
0x30,
0x48,
0xCC,
0x60,
0x00,
0x54,
0xAE,
0x4A,
0xC0,
0x00,
0x00,
0x00,
)
)
_R82XX_LNA = (0, 9, 13, 40, 38, 13, 31, 22, 26, 31, 26, 14, 19, 5, 35, 13)
_R82XX_MIX = (0, 5, 10, 10, 19, 9, 10, 25, 17, 10, 8, 16, 13, 6, 3, -8)
# tuner_r82xx.c freq_ranges: (start MHz, open_d, rf_mux_ploy, tf_c). The
# xtal_cap columns are not needed: this driver runs the crystal at 0 pF.
_R82XX_RANGES = (
(0, 0x08, 0x02, 0xDF),
(50, 0x08, 0x02, 0xBE),
(55, 0x08, 0x02, 0x8B),
(60, 0x08, 0x02, 0x7B),
(65, 0x08, 0x02, 0x69),
(70, 0x08, 0x02, 0x58),
(75, 0x00, 0x02, 0x44),
(80, 0x00, 0x02, 0x44),
(90, 0x00, 0x02, 0x34),
(100, 0x00, 0x02, 0x34),
(110, 0x00, 0x02, 0x24),
(120, 0x00, 0x02, 0x24),
(140, 0x00, 0x02, 0x14),
(180, 0x00, 0x02, 0x13),
(220, 0x00, 0x02, 0x13),
(250, 0x00, 0x02, 0x11),
(280, 0x00, 0x02, 0x00),
(310, 0x00, 0x41, 0x00),
(450, 0x00, 0x41, 0x00),
(588, 0x00, 0x40, 0x00),
(650, 0x00, 0x40, 0x00),
)
# r82xx_standby register writes, in order.
_R82XX_STANDBY = (
(0x06, 0xB1),
(0x05, 0xA0),
(0x07, 0x3A),
(0x08, 0x40),
(0x09, 0xC0),
(0x0A, 0x36),
(0x0C, 0x35),
(0x0F, 0x68),
(0x11, 0x03),
(0x17, 0xF4),
(0x19, 0x0C),
)
# -- FC0013 tables ---------------------------------------------------------
_FC0013_INIT = (
0x00, # 0x00: dummy
0x09, # 0x01
0x16, # 0x02
0x00, # 0x03
0x00, # 0x04
0x17, # 0x05
0x02, # 0x06: LPF bandwidth
0x0A, # 0x07: CHECK, |= 0x20 for a 27 or 28.8 MHz crystal
0xFF, # 0x08: AGC clock /256, AGC gain 1/256, loop bw 1/8
0x6E, # 0x09: disable LoopThrough
0xB8, # 0x0a: disable LO test buffer
0x82, # 0x0b: CHECK
0xFC, # 0x0c: |= 0x02 for dual master
0x01, # 0x0d: AGC not forcing, LNA forcing
0x00, # 0x0e
0x00, # 0x0f
0x00, # 0x10
0x00, # 0x11
0x00, # 0x12
0x00, # 0x13
0x50, # 0x14: DVB-T high gain, UHF
0x01,
) # 0x15
# tuner_fc0013.c fc0013_lna_gains, tenths of a dB paired with register value.
_FC0013_LNA_GAINS = (
(-99, 0x02),
(-73, 0x03),
(-65, 0x05),
(-63, 0x04),
(-63, 0x00),
(-60, 0x07),
(-58, 0x01),
(-54, 0x06),
(58, 0x0F),
(61, 0x0E),
(63, 0x0D),
(65, 0x0C),
(67, 0x0B),
(68, 0x0A),
(70, 0x09),
(71, 0x08),
(179, 0x17),
(181, 0x16),
(182, 0x15),
(184, 0x14),
(186, 0x13),
(188, 0x12),
(191, 0x11),
(197, 0x10),
)
# Frequency divider selection from fc0013_set_params, ordered by upper bound.
# Each entry is (exclusive upper bound in Hz, multiplier, reg5, reg6).
_FC0013_DIVIDERS = (
(37084000, 96, 0x82, 0x00),
(55625000, 64, 0x02, 0x02),
(74167000, 48, 0x42, 0x00),
(111250000, 32, 0x82, 0x02),
(148334000, 24, 0x22, 0x00),
(222500000, 16, 0x42, 0x02),
(296667000, 12, 0x12, 0x00),
(445000000, 8, 0x22, 0x02),
(593334000, 6, 0x0A, 0x00),
(950000000, 4, 0x12, 0x02),
(None, 2, 0x0A, 0x02),
)
# VHF track selection from fc0013_set_vhf_track, ordered by inclusive upper
# bound. Upstream's last VHF case is a strict < 300 MHz and is handled in code.
_FC0013_VHF_TRACK = (
(177500000, 0x1C),
(184500000, 0x18),
(191500000, 0x14),
(198500000, 0x10),
(205500000, 0x0C),
(219500000, 0x08),
)
# -- tuner identification and frequency limits -----------------------------
FC0013_I2C_ADDR = 0xC6
FC0013_CHECK_ADDR = 0x00
FC0013_CHECK_VAL = 0xA3
R82XX_I2C_ADDR = 0x34
R82XX_CHECK_VAL = 0x69
# Lowest centre the R82xx PLL reaches: LO = RF + 2.125 MHz IF must be at
# least 1.77 GHz / 64.
R82XX_MIN = 25600000
R82XX_MAX = 1760000000
DIRECT_MIN = 100000
FC0013_MIN = 22000000
FC0013_MAX = 1100000000
def reverse8(n):
n = ((n & 0x55) << 1) | ((n >> 1) & 0x55)
n = ((n & 0x33) << 2) | ((n >> 2) & 0x33)
return ((n & 15) << 4) | (n >> 4)
def sample_ratio(rate, crystal=CRYSTAL):
if rate <= 225000 or rate > 3200000 or 300000 < rate <= 900000:
raise ValueError("unsupported RTL2832 sample rate")
ratio = ((crystal << 22) // rate) & 0x0FFFFFFC
real_ratio = ratio | ((ratio & 0x08000000) << 1)
return ratio, (crystal << 22) / real_ratio
def pll_values(freq, fine=2, crystal=CRYSTAL):
khz = (freq + 500) // 1000
divider = 2
div_num = 0
while divider <= 64:
if 1770000 <= khz * divider < 3540000:
break
divider *= 2
div_num += 1
if divider > 64:
raise ValueError("frequency outside R82xx PLL range")
if fine > 2:
div_num -= 1
elif fine < 2:
div_num += 1
vco_div = (crystal + 65536 * freq * divider) // (2 * crystal)
nint, sdm = vco_div // 65536, vco_div % 65536
if not 13 <= nint <= 63 or not 0 <= div_num <= 7:
raise ValueError("invalid R82xx PLL values")
ni = (nint - 13) // 4
si = nint - 4 * ni - 13
return divider, div_num, ni + (si << 6), sdm
class RTL2832:
"""RTL2832U USB transport and demodulator, shared by both tuner drivers.
On its own it has no tuner layer; detect_tuner() uses it to probe.
"""
def __init__(self, device, timeout=1000, log=print, max_packet=64):
if max_packet not in (64, 512):
raise ValueError("max_packet must match 64-byte FS or 512-byte HS endpoint")
self.max_packet = max_packet
self.dev = device
self.timeout = timeout
self.log = log
self.shadow = bytearray(35)
self.if_freq = 3570000
self.frequency = 0
self.sample_rate = 0
self.locked = False
self.calibration = None
self.tuner_id = None
self.control_stalls = 0
self.control_retries = 0
self.demod_read_stalls = 0
self.demod_read_retries = 0
def _control(self, direction, value, index, data):
# Only absolute register operations used by this driver are supported.
# Retry one STALLed transfer, never its successful neighboring transfer.
is_dummy = direction == 0xC0 and value == 0x0120 and index == 0x0A
for attempt in range(3):
try:
n = self.dev.ctrl_transfer(
direction, 0, value, index, data, self.timeout
)
except OSError as error:
# CircuitPython USBError subclasses OSError. Do not replay
# timeouts, short transfers, or unspecified transport failures.
if str(error) != "Pipe error":
raise
self.control_stalls += 1
# I2C reads may have advanced the tuner register pointer.
if direction == 0xC0 and index == 0x600:
raise
if is_dummy:
self.demod_read_stalls += 1
if attempt == 2:
raise
self.control_retries += 1
if is_dummy:
self.demod_read_retries += 1
if self.log:
self.log(
"RTL control retry",
attempt + 1,
"type",
direction,
"value",
value,
"index",
index,
"total",
self.control_retries,
)
time.sleep(0.002)
continue
if n != len(data):
raise OSError("short RTL control transfer %d/%d" % (n, len(data)))
return data
def write_reg(self, block, address, value, length=1):
data = (
bytes((value & 255,))
if length == 1
else bytes(((value >> 8) & 255, value & 255))
)
self._control(0x40, address, (block << 8) | 0x10, data)
def read_reg(self, block, address, length=1):
data = self._control(0xC0, address, block << 8, bytearray(length))
return data[0] if length == 1 else data[0] | (data[1] << 8)
def demod(self, page, address, value, length=1):
data = (
bytes((value & 255,))
if length == 1
else bytes(((value >> 8) & 255, value & 255))
)
self._control(0x40, (address << 8) | 0x20, 0x10 | page, data)
self._control(0xC0, 0x0120, 0x0A, bytearray(1))
def repeater(self, enabled):
self.demod(1, 1, 0x18 if enabled else 0x10)
def _init_baseband(self):
"""rtlsdr_init_baseband plus the USB endpoint setup."""
self.write_reg(1, 0x2000, 9)
# EPA register is little endian, while write_reg emits big endian.
self.write_reg(
1, 0x2158, ((self.max_packet & 255) << 8) | (self.max_packet >> 8), 2
)
self.write_reg(1, 0x2148, 0x1002, 2)
self.write_reg(2, 0x300B, 0x22)
self.write_reg(2, 0x3000, 0xE8)
for args in ((1, 1, 0x14), (1, 1, 0x10), (1, 0x15, 0), (1, 0x16, 0, 2)):
self.demod(*args)
for i in range(6):
self.demod(1, 0x16 + i, 0)
fir = bytearray(x & 255 for x in _FIR[:8])
for i in range(8, 16, 2):
a, b = _FIR[i], _FIR[i + 1]
fir.extend(((a >> 4) & 255, ((a << 4) | ((b >> 8) & 15)) & 255, b & 255))
for i, value in enumerate(fir):
self.demod(1, 0x1C + i, value)
for args in (
(0, 0x19, 5),
(1, 0x93, 0xF0),
(1, 0x94, 15),
(1, 0x11, 0),
(1, 4, 0),
(0, 0x61, 0x60),
(0, 6, 0x80),
(1, 0xB1, 0x1B),
(0, 0x0D, 0x83),
):
self.demod(*args)
def _if(self, frequency):
value = -((frequency << 22) // CRYSTAL)
for reg, val in (
(0x19, (value >> 16) & 0x3F),
(0x1A, (value >> 8) & 255),
(0x1B, value & 255),
):
self.demod(1, reg, val)
def _set_bandwidth(self):
"""Set the tuner's analog bandwidth and self.if_freq to match."""
raise NotImplementedError
def set_sample_rate(self, rate):
# The narrow-band analog filter paths are deliberately limited to low rates.
if not 225000 < rate <= 300000:
raise ValueError("sample rate must be 225001..300000 samples/s")
ratio, exact = sample_ratio(rate)
self._set_bandwidth()
self._if(self.if_freq)
self.demod(1, 0x9F, ratio >> 16, 2)
self.demod(1, 0xA1, ratio & 65535, 2)
self.demod(1, 0x3F, 0)
self.demod(1, 0x3E, 0)
self.demod(1, 1, 0x14)
self.demod(1, 1, 0x10)
self.sample_rate = exact
if self.frequency:
self.tune(self.frequency)
def hold_buffer(self):
"""Hold EPA FIFO reset while host capture is stopped for reconfiguration.
This receiver stalls tuner controls if its running sample FIFO fills
after the host stops reading. Release using reset_buffer before reads.
"""
self.write_reg(1, 0x2148, 0x1002, 2)
def reset_buffer(self):
self.write_reg(1, 0x2148, 0x1002, 2)
self.write_reg(1, 0x2148, 0, 2)
def set_test_mode(self, enabled):
"""RTL counter pattern for measuring missing bytes, not RF capture."""
self.demod(0, 0x19, 3 if enabled else 5)
def readinto(self, buffer, timeout=1000):
if len(buffer) % 64:
raise ValueError("read buffer length must be a multiple of 64")
return self.dev.read(0x81, buffer, timeout)
def open_stream(self, buffer_size=32768):
"""Start continuous capture and return a usb_host_bulk.InStream.
Reads never block: readinto() returns None while nothing is waiting
and 0 once the stream has ended (STALL or unplug). deinit() it, or
use it in a with block, before calling hold_buffer() or retuning.
"""
import usb_host_bulk
self.reset_buffer()
return usb_host_bulk.InStream(self.dev, 0x81, buffer_size=buffer_size)
def stream(self, chunk, buffer_size=32768):
"""Async iterator over full chunks of I/Q bytes, like pyrtlsdr's
RtlSdrAio.stream(). Every item is `chunk` itself, refilled:
with radio.stream(bytearray(8192)) as chunks:
async for iq in chunks:
process(iq)
Iteration ends when the stream does (STALL or unplug). Leaving the
with block, or stop(), ends the capture. Needs asyncio.
"""
return _ChunkStream(self, chunk, buffer_size)
class _ChunkStream:
def __init__(self, radio, chunk, buffer_size):
# asyncio loads its stream module on first use. Do it before the
# capture starts: loading it later can overflow the ring.
from asyncio import StreamReader
self._reader_type = StreamReader
self._radio = radio
self._chunk = chunk
self._view = memoryview(chunk)
self._buffer_size = buffer_size
self._stream = None
self._reader = None
self._stopped = False
self._stream_ended = False
def __enter__(self):
return self
def __exit__(self, *exc):
self.stop()
def __aiter__(self):
if self._stream is None:
self._stream = self._radio.open_stream(self._buffer_size)
self._reader = self._reader_type(self._stream)
return self
async def __anext__(self):
filled = 0
while filled < len(self._chunk):
n = await self._reader.readinto(self._view[filled:])
if not n:
# Unplugged or stalled: the device may not answer control
# transfers any more, so stop() skips hold_buffer().
self._stream_ended = True
self.stop()
raise StopAsyncIteration
filled += n
return self._chunk
@property
def lost_packets(self):
return self._stream.lost_packets if self._stream is not None else 0
def stop(self):
if self._stream is None or self._stopped:
return
self._stopped = True
self._stream.deinit()
if not self._stream_ended:
self._radio.hold_buffer()
class R82xxHam(RTL2832):
"""RTL2832U with an R820T(2)/R860 tuner: wide-range tuning and HF direct
sampling.
direct_input selects the ADC used for direct sampling: 'Q' (the
RTL-SDR convention, librtlsdr direct_sampling=2) or 'I'.
"""
tuner_name = "R82xx"
min_frequency = DIRECT_MIN
max_frequency = R82XX_MAX
def __init__(self, device, direct_input="Q", **kwargs):
super().__init__(device, **kwargs)
self.direct = False
self.direct_input = direct_input
self.conjugate = False
self._gain = None
self._rate = 256000
# -- tuner I2C -------------------------------------------------------
def _i2c_write(self, data):
self._control(0x40, R82XX_I2C_ADDR, 0x610, data)
def _tread(self, length, reverse=True):
self._i2c_write(bytes((0,)))
data = self._control(0xC0, R82XX_I2C_ADDR, 0x600, bytearray(length))
if reverse:
for i in range(length):
data[i] = reverse8(data[i])
return data
def _twrite(self, register, data):
for start in range(0, len(data), 7):
part = data[start : start + 7]
self._i2c_write(bytes((register + start,)) + bytes(part))
self.shadow[register + start : register + start + len(part)] = part
def _tmask(self, register, value, mask=255):
value = (self.shadow[register] & ~mask) | (value & mask)
self._twrite(register, bytes((value,)))
# -- tuner bring-up --------------------------------------------------
def _pll(self, freq):
self._tmask(0x1A, 0, 0x0C)
fine = (self._tread(5)[4] & 0x30) >> 4
_, div_num, ni_si, sdm = pll_values(freq, fine)
regs = bytearray(self.shadow[0x10:0x17])
regs[0] = (regs[0] & ~0xF0) | (div_num << 5)
regs[2] = (regs[2] & ~0xE8) | 0x80 | (0x08 if sdm == 0 else 0)
regs[4], regs[5], regs[6] = ni_si, sdm & 255, sdm >> 8
self._twrite(0x10, regs)
self.locked = False
for attempt in range(2):
time.sleep(0.01)
if self._tread(3)[2] & 0x40:
self.locked = True
break
if attempt == 0:
self._tmask(0x12, 0x60, 0xE0)
if not self.locked:
raise RuntimeError("R82xx PLL unlocked at %d Hz" % freq)
self._tmask(0x1A, 8, 8)
def _tuner_init(self):
self._twrite(5, _R82XX_INIT)
for reg, val, mask in ((0x0C, 0, 15), (0x13, 49, 0x3F), (0x1D, 0, 0x38)):
self._tmask(reg, val, mask)
cal = 0
for attempt in range(2):
self._tmask(0x0B, 0x6B, 0x60)
self._tmask(0x0F, 4, 4)
self._tmask(0x10, 0, 3)
self._pll(56000000)
self._tmask(0x0B, 0x10, 0x10)
time.sleep(0.002)
self._tmask(0x0B, 0, 0x10)
self._tmask(0x0F, 0, 4)
cal = self._tread(5)[4] & 15
if cal and cal != 15:
break
if cal == 15:
cal = 0
self.calibration = cal
for reg, val, mask in (
(0x0A, 0x10 | cal, 0x1F),
(0x0B, 0x6B, 0xEF),
(7, 0, 0x80),
(6, 0x10, 0x30),
(0x1E, 0x60, 0x60),
(5, 1, 0x80),
(0x1F, 0, 0x80),
(0x0F, 0, 0x80),
(0x19, 0x60, 0x60),
(0x1D, 0xE5, 0xC7),
(0x1C, 0x24, 0xF8),
(0x0D, 0x53, 255),
(0x0E, 0x75, 255),
(5, 0, 0x60),
(6, 0, 8),
(0x11, 0x38, 0x38),
(0x17, 0x30, 0x30),
(0x0A, 0x40, 0x60),
(0x1D, 0, 0x38),
(0x1C, 0, 4),
(6, 0, 0x40),
(0x1A, 0x30, 0x30),
(0x1D, 0x18, 0x38),
(0x1C, 0x24, 4),
(0x1E, 14, 0x1F),
(0x1A, 0x20, 0x30),
):
self._tmask(reg, val, mask)
def _set_bandwidth(self):
self.repeater(True)
try:
self._tmask(0x0A, 0, 0x10)
self._tmask(0x0B, 0xE6, 0xEF) # 350 kHz minimum analog bandwidth.
self.if_freq = 2125000
finally:
self.repeater(False)
def _enter_direct(self):
# rtlsdr_set_direct_sampling(dev, on)
self.repeater(True)
try:
for register, value in _R82XX_STANDBY:
self._twrite(register, bytes((value,)))
finally:
self.repeater(False)
self.demod(1, 0xB1, 0x1A) # disable zero-IF mode
self.demod(1, 0x15, 0x00) # no spectrum inversion
self.demod(0, 0x08, 0x4D) # one ADC input only
self.demod(0, 0x06, 0x90 if self.direct_input == "Q" else 0x80)
# The RTL2832U's own AGC helps the 8-bit ADC with weak HF signals.
self.demod(0, 0x19, 0x25)
self.direct = True
# -- public interface ------------------------------------------------
def initialize(self, frequency, sample_rate=256000, gain=280):
"""Initialize already-configured device. Gain is tenths of a dB or None for AGC."""
# A full bring-up also leaves direct sampling: it restores the I-only
# low-IF demodulator settings and re-initializes the tuner.
self.direct = False
self.frequency = 0
self._gain = gain
self._rate = sample_rate # the int request; self.sample_rate is the exact float
# The tuner is brought up within its own range; HF switches to direct
# sampling afterwards.
start = frequency if frequency >= R82XX_MIN else 100000000
self._init_baseband()
self.repeater(True)
try:
self.tuner_id = self._tread(1, False)[0]
if self.tuner_id != R82XX_CHECK_VAL:
raise RuntimeError(
"R82xx tuner probe got 0x%02x, expected 0x%02x"
% (self.tuner_id, R82XX_CHECK_VAL)
)
self.demod(1, 0xB1, 0x1A)
self.demod(0, 8, 0x4D)
self._if(3570000)
self.demod(1, 0x15, 1)
self._tuner_init()
finally:
self.repeater(False)
self.set_sample_rate(sample_rate)
self.set_gain(gain)
self.tune(start)
self.reset_buffer()
if self.log:
self.log(
"R82xx ready",
self.frequency,
self.sample_rate,
"cal",
self.calibration,
"lock",
self.locked,
)
if frequency != start:
self.tune(frequency)
def set_gain(self, gain=None):
"""Gain is tenths of a dB, or None for tuner AGC. Remembered, but not
applied, while direct sampling bypasses the tuner."""
self._gain = gain
if self.direct:
return
self.repeater(True)
try:
if gain is None:
for r, v, m in ((5, 0, 0x10), (7, 0x10, 0x10), (0x0C, 0x0B, 0x9F)):
self._tmask(r, v, m)
else:
for r, v, m in ((5, 0x10, 0x10), (7, 0, 0x10), (0x0C, 8, 0x9F)):
self._tmask(r, v, m)
total = lna = mix = 0
for i in range(15):
if total >= gain:
break
lna += 1
total += _R82XX_LNA[lna]
if total >= gain:
break
mix += 1
total += _R82XX_MIX[mix]
self._tmask(5, lna, 15)
self._tmask(7, mix, 15)
finally:
self.repeater(False)
def tune(self, frequency):
if not self.min_frequency <= frequency <= self.max_frequency:
raise ValueError("R82xx receiver tunes 0.1 MHz - 1760 MHz")
if frequency < R82XX_MIN:
if not self.direct:
self._enter_direct()
# The ADC samples at 28.8 MHz. Above 14.4 MHz the signal is in the
# second Nyquist zone and arrives mirrored at 28.8 MHz - f.
if frequency <= CRYSTAL // 2:
self._if(frequency)
self.conjugate = False
else:
self._if(CRYSTAL - frequency)
self.conjugate = True
self.frequency = frequency
return
if self.direct:
# Leaving HF: full re-initialization, as librtlsdr does.
self.initialize(frequency, self._rate, self._gain)
return
lo = frequency + self.if_freq
mhz = lo // 1000000
entry = _R82XX_RANGES[0]
for candidate in _R82XX_RANGES:
if mhz < candidate[0]:
break
entry = candidate
_, open_d, rf_mux, tf_c = entry
self.repeater(True)
try:
# r82xx_set_mux, then r82xx_set_pll.
for r, v, m in (
(0x17, open_d, 0x08),
(0x1A, rf_mux, 0xC3),
(0x1B, tf_c, 255),
(0x10, 0, 0x0B),
(8, 0, 0x3F),
(9, 0, 0x3F),
):
self._tmask(r, v, m)
self._pll(lo)
finally:
self.repeater(False)
self.conjugate = False
self.frequency = frequency
class FC0013Ham(RTL2832):
"""RTL2832U with a Fitipower FC0013 tuner, zero-IF, 22 MHz - 1.1 GHz.
Direct sampling is not wired on FC0013 dongles, so there is no HF. The
FC0013 differs from the R82xx in three independent ways:
* it answers at I2C address 0xc6, not 0x34, and register reads are not
bit-reversed;
* it is a zero-IF tuner, so the RTL2832U keeps its baseband defaults
(en_bbin set, no spectrum inversion, IF frequency 0) and takes I+Q ADC
input instead of I-only at a low IF;
* it has no tunable narrow IF filter and no PLL lock flag.
"""
tuner_name = "FC0013"
min_frequency = FC0013_MIN
max_frequency = FC0013_MAX
direct = False
conjugate = False
def __init__(
self, device, timeout=1000, log=print, max_packet=64, bandwidth=6000000
):
super().__init__(device, timeout=timeout, log=log, max_packet=max_packet)
self.bandwidth = bandwidth
self.vco_calibration = None
# The FC0013 exposes no PLL lock flag through this register interface.
self.locked = None
# -- tuner I2C -------------------------------------------------------
# Plain register-address-then-data access, no bit reversal.
def _i2c_write(self, data):
self._control(0x40, FC0013_I2C_ADDR, 0x610, data)
def _treg_read(self, register):
self._i2c_write(bytes((register,)))
return self._control(0xC0, FC0013_I2C_ADDR, 0x600, bytearray(1))[0]
def _treg_write(self, register, value):
value &= 255
self._i2c_write(bytes((register, value)))
self.shadow[register] = value
# -- tuner bring-up --------------------------------------------------
def _tuner_init(self):
registers = list(_FC0013_INIT)
registers[0x07] |= 0x20 # 27 MHz or 28.8 MHz crystal
registers[0x0C] |= 0x02 # dual master
for register in range(1, len(registers)):
self._treg_write(register, registers[register])
def _set_vhf_track(self, frequency):
value = self._treg_read(0x1D) & 0xE3
bits = 0x1C # UHF and GPS, and the >= 300 MHz fallback
for bound, candidate in _FC0013_VHF_TRACK:
if frequency <= bound:
bits = candidate
break
else:
if frequency < 300000000:
bits = 0x04
self._treg_write(0x1D, value | bits)
def _set_params(self, frequency, bandwidth):
"""Port of fc0013_set_params. C integer widths are reproduced exactly."""
half_crystal = CRYSTAL // 2
self._set_vhf_track(frequency)
if frequency < 300000000:
self._treg_write(0x07, self._treg_read(0x07) | 0x10) # enable VHF filter
self._treg_write(0x14, self._treg_read(0x14) & 0x1F) # disable UHF and GPS
else:
self._treg_write(0x07, self._treg_read(0x07) & 0xEF) # disable VHF filter
self._treg_write(0x14, (self._treg_read(0x14) & 0x1F) | 0x40)
reg = [0] * 7
for bound, multi, reg5, reg6 in _FC0013_DIVIDERS:
if bound is None or frequency < bound:
break
reg[5], reg[6] = reg5, reg6
vco = frequency * multi
vco_select = 0
if vco >= 3060000000:
reg[6] |= 0x08
vco_select = 1
quotient = vco // half_crystal
xdiv = quotient & 0xFFFF
if (vco - xdiv * half_crystal) >= (half_crystal // 2):
xdiv = (xdiv + 1) & 0xFFFF
pm = (xdiv // 8) & 255
am = (xdiv - 8 * pm) & 255
if am < 2:
am += 8
pm -= 1
if pm > 31:
reg[1] = (am + 8 * (pm - 31)) & 255
reg[2] = 31
else:
reg[1] = am
reg[2] = pm
if reg[1] > 15 or reg[2] < 0x0B:
raise ValueError("no valid FC0013 PLL combination for %d Hz" % frequency)
reg[6] |= 0x20 # fix clock out
# Fractional part of the delta-sigma PLL. Upstream reuses one uint16_t.
xin = ((vco - quotient * half_crystal) // 1000) & 0xFFFF
xin = ((xin << 15) // (half_crystal // 1000)) & 0xFFFF
if xin >= 16384:
xin = (xin + 32768) & 0xFFFF
reg[3] = xin >> 8
reg[4] = xin & 0xFF
reg[6] &= 0x3F # bits 6 and 7 select the analog bandwidth
if bandwidth == 6000000:
reg[6] |= 0x80
elif bandwidth == 7000000:
reg[6] |= 0x40
reg[5] |= 0x07 # modified for the Realtek demodulator
for register in range(1, 7):
self._treg_write(register, reg[register])
value = self._treg_read(0x11)
self._treg_write(0x11, value | 0x04 if multi == 64 else value & 0xFB)
self._treg_write(0x0E, 0x80) # VCO calibration
self._treg_write(0x0E, 0x00)
self._treg_write(0x0E, 0x00) # re-calibrate if needed
# Upstream leaves its 10 ms settling delay commented out. Real hardware
# needs it; it changes timing only, never register state.
time.sleep(0.01)
calibration = self._treg_read(0x0E) & 0x3F
self.vco_calibration = calibration
# Retry once on the far side of the selected VCO range.
if vco_select:
retry = calibration > 0x3C
reg[6] &= ~0x08 & 0xFF
else:
retry = calibration < 0x02
reg[6] |= 0x08
if retry:
self._treg_write(0x06, reg[6])
self._treg_write(0x0E, 0x80)
self._treg_write(0x0E, 0x00)
def _set_bandwidth(self):
# The FC0013 analog filter does not narrow below a DVB-T channel, so
# adjacent-channel rejection relies on the RTL2832U decimation chain.
self.if_freq = 0
# -- public interface ------------------------------------------------
def initialize(self, frequency, sample_rate=256000, gain=280):
"""Initialize already-configured device. Gain is tenths of a dB or None for AGC."""
self._init_baseband()
self.repeater(True)
try:
self.tuner_id = self._treg_read(FC0013_CHECK_ADDR)
if self.tuner_id != FC0013_CHECK_VAL:
raise RuntimeError(
"FC0013 tuner probe got 0x%02x, expected 0x%02x"
% (self.tuner_id, FC0013_CHECK_VAL)
)
# Zero-IF tuner: keep the baseband defaults and take both ADC
# inputs. These are written explicitly because the R82xx path
# leaves I-only mode and a 3.57 MHz IF behind in the same chip.
self.if_freq = 0
self._if(0)
self.demod(0, 8, 0xCD) # in-phase + quadrature ADC input
self.demod(1, 0xB1, 0x1B) # zero-IF mode
self.demod(1, 0x15, 0) # no spectrum inversion
self._tuner_init()
finally:
self.repeater(False)
self.set_sample_rate(sample_rate)
self.set_gain(gain)
self.tune(frequency)
self.reset_buffer()
if self.log:
self.log(
"FC0013 ready",
self.frequency,
self.sample_rate,
"vco_cal",
self.vco_calibration,
)
def set_gain(self, gain=None):
"""Gain is tenths of a dB, or None for tuner AGC.
The FC0013 tops out at 19.7 dB, far below the R82xx. A larger request
selects maximum gain rather than failing.
"""
self.repeater(True)
try:
value = self._treg_read(0x0D)
value = value | 0x08 if gain is not None else value & ~0x08 & 0xFF
self._treg_write(0x0D, value)
self._treg_write(0x13, 0x0A) # fixed IF gain
if gain is not None:
value = self._treg_read(0x14) & 0xE0
for index, (step, bits) in enumerate(_FC0013_LNA_GAINS):
if step >= gain or index + 1 == len(_FC0013_LNA_GAINS):
value |= bits
break
self._treg_write(0x14, value)
finally:
self.repeater(False)
def tune(self, frequency):
if not self.min_frequency <= frequency <= self.max_frequency:
raise ValueError("FC0013 receiver tunes 22 MHz - 1100 MHz")
# Zero-IF: the tuner is driven to the carrier, with no IF offset.
self.repeater(True)
try:
self._set_params(frequency, self.bandwidth)
finally:
self.repeater(False)
self.frequency = frequency
def detect_tuner(device, log=None, max_packet=64, timeout=1000):
"""Bring up the RTL2832U and report which supported tuner is fitted.
Returns "FC0013", "R82xx", or None. Probe order follows librtlsdr.
"""
probe = RTL2832(device, timeout=timeout, log=None, max_packet=max_packet)
probe._init_baseband()
def identify(address, register):
probe._control(0x40, address, 0x610, bytes((register,)))
return probe._control(0xC0, address, 0x600, bytearray(1))[0]
probe.repeater(True)
try:
for address, register, expected, name in (
(FC0013_I2C_ADDR, FC0013_CHECK_ADDR, FC0013_CHECK_VAL, "FC0013"),
(R82XX_I2C_ADDR, 0, R82XX_CHECK_VAL, "R82xx"),
):
try:
# A missing tuner STALLs rather than answering; that is not fatal
# here, it only means this address is not the one fitted.
if identify(address, register) == expected:
return name
except OSError:
continue
finally:
probe.repeater(False)
if log:
log("tuner probe complete")
return None
def open_ham_receiver(device, log=print, max_packet=64, timeout=1000, direct_input="Q"):
"""Return a driver instance for the tuner actually fitted."""
found = detect_tuner(device, log=None, max_packet=max_packet, timeout=timeout)
if log:
log("tuner detected", found)
if found == "FC0013":
return FC0013Ham(device, timeout=timeout, log=log, max_packet=max_packet)
if found == "R82xx":
return R82xxHam(
device,
direct_input=direct_input,
timeout=timeout,
log=log,
max_packet=max_packet,
)
raise RuntimeError("no supported tuner found (expected FC0013 or R82xx)")
jack_audio.py
This is responsible for audio output. It initializes and manages the on-board TLV320 DAC. The PCM audio data gets stored in a looped double-buffered audiocore.RawSample which has the empty half refilled on a schedule by calling the service() function.
# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""32 kHz mono PCM streaming to the Fruit Jam's 3.5 mm jack (TLV320DAC3100).
CircuitPython has no queue-style audio sample, so this plays a looped,
double-buffered audiocore.RawSample and refills its halves on a schedule. The
audio DMA copies one half every HALF samples, alternately half 0 then half 1:
at play() both are loaded, then half 0 again after 1 * HALF, half 1 after
2 * HALF, and so on. Half (j % 2) is therefore free to rewrite between
j * HALF and (j + 1) * HALF samples after play(), and what is written there
plays from (j + 2) * HALF. service() does that refill from a FIFO.
The schedule is kept with time.monotonic_ns(), which runs from the same crystal
as the I2S clock. At 150 MHz both the I2S rate (32000 * 192 Hz) and the 15 MHz
MCLK divide exactly, so the DAC runs at exactly the I2S rate. This needs an
adafruit_tlv320 version that supports 32 kHz with a 15 MHz MCLK.
The radio's rate comes from the dongle's crystal instead, so the FIFO level
drifts slowly. service() drops or repeats a few samples to keep it near the
target; the counters report how often.
"""
import array
import time
import audiobusio
import audiocore
import board
import digitalio
import microcontroller
import pwmio
import adafruit_tlv320
# pylint: disable=too-many-branches, attribute-defined-outside-init
RATE = 32000
MCLK = 15_000_000
class JackAudio:
"""Stream mono 16-bit PCM at 32 kHz to the headphone jack.
write() queues samples, service() must be called often (every few ms,
at least once per half = 64 ms). Latency is about 3 halves plus the FIFO.
"""
def __init__(self, half=2048, fifo=16384, target=4096, volume=-10.0):
if microcontroller.cpu.frequency != 150_000_000:
# Other clocks give an inexact I2S divider and the DAC would slip.
raise RuntimeError("jack audio timing assumes a 150 MHz CPU clock")
self.half = half
self.half_ns = half * 1_000_000_000 // RATE
self.target = target
self._reset_pin = digitalio.DigitalInOut(board.PERIPH_RESET)
self._reset_pin.switch_to_output(False)
time.sleep(0.1)
self._reset_pin.value = True
time.sleep(0.01)
self._mclk = pwmio.PWMOut(board.I2S_MCLK, frequency=MCLK, duty_cycle=2**15)
self.dac = adafruit_tlv320.TLV320DAC3100(board.I2C())
self.dac.configure_clocks(sample_rate=RATE, mclk_freq=MCLK)
self.dac.headphone_output = True
self.dac.dac_volume = volume
self._i2s = audiobusio.I2SOut(board.I2S_BCLK, board.I2S_WS, board.I2S_DIN)
self._fifo_len = fifo
self._play = None
self.fifo = None
self.rd = self.wr = 0
self._t0 = None
self._next = 2
self._primed = False
self.late = self.underruns = self.dropped = self.repeated = 0
self.max_lateness_ns = 0
def _allocate(self):
# Python objects go to internal SRAM first, then PSRAM. The play
# buffer is allocated before play() so its DMA buffers still fit in
# SRAM; the large FIFO afterwards, where it may land in PSRAM.
half = self.half
self._play = array.array("h", bytes(4 * half))
self._playv = memoryview(self._play)
self._sample = audiocore.RawSample(
self._play, sample_rate=RATE, single_buffer=False
)
self._zeros = memoryview(array.array("h", bytes(2 * half)))
# FIFO: samples live in fifo[rd:wr]. The producer writes at wr directly
# (write_view) so the demodulator can output straight into it.
def queued(self):
return self.wr - self.rd
def _reserve(self, count):
if self.fifo is None:
# Allocated on first use, so that SRAM-only buffers allocated
# after start() (such as a USB bulk ring) get the SRAM first.
self.fifo = array.array("h", bytes(2 * self._fifo_len))
self._fifov = memoryview(self.fifo)
self._fifob = self._fifov.cast("B")
if self.wr + count > len(self.fifo):
left = self.wr - self.rd
self._fifov[:left] = self._fifov[self.rd : self.wr]
self.rd = 0
self.wr = left
if self.wr + count > len(self.fifo):
# Consumer stalled: keep the newest data.
self.dropped += self.wr
self.rd = self.wr = 0
def write_view(self, count):
"""Return a writable view of count samples at the FIFO tail."""
self._reserve(count)
return self._fifov[self.wr : self.wr + count]
def write_view_bytes(self, count):
"""write_view() as a byte view, for code that requires byte buffers."""
self._reserve(count)
return self._fifob[2 * self.wr : 2 * (self.wr + count)]
def commit(self, count):
self.wr += count
def write(self, samples):
n = len(samples)
self.write_view(n)[:] = samples
self.commit(n)
def clear(self):
"""Forget queued audio and silence the output within ~3 halves."""
self.rd = self.wr = 0
self._primed = False
def start(self):
"""Start playing silence. Raises if the DMA buffers do not fit."""
if self._play is None:
self._allocate()
self._playv[: self.half] = self._zeros
self._playv[self.half :] = self._zeros
self._i2s.play(self._sample, loop=True)
self._t0 = time.monotonic_ns()
self._next = 2
self._primed = False
def stop(self):
self._i2s.stop()
self._t0 = None
def service(self):
"""Refill the half that is free now. Returns True if it wrote one."""
if self._t0 is None:
return False
now = time.monotonic_ns() - self._t0
j = now // self.half_ns
if j < self._next:
return False
if j > self._next:
# Missed a whole window: that half already played stale audio.
self.late += j - self._next
self._next = j
lateness = now - j * self.half_ns
self.max_lateness_ns = max(self.max_lateness_ns, lateness)
h = self.half
dst = self._playv[(j & 1) * h : ((j & 1) + 1) * h]
q = self.wr - self.rd
if not self._primed:
if q >= self.target + h:
self._primed = True
else:
dst[:] = self._zeros
if self._primed:
if q < h:
# Underrun: play what there is, then silence, and re-prime.
dst[:q] = self._fifov[self.rd : self.wr]
dst[q:] = self._zeros[q:]
self.rd = self.wr = 0
self.underruns += 1
self._primed = False
else:
# Drift correction: take one sample more or less per half
# when the FIFO is well off target.
take = h
if q > self.target + h + h // 2:
take = h + 1
elif self.target - h // 2 > q > h:
take = h - 1
if take == h:
dst[:] = self._fifov[self.rd : self.rd + h]
elif take > h:
dst[:] = self._fifov[self.rd : self.rd + h]
self.dropped += 1
else:
dst[: h - 1] = self._fifov[self.rd : self.rd + h - 1]
dst[h - 1] = dst[h - 2]
self.repeated += 1
self.rd += take
self._next = j + 1
return True
def stats(self):
return {
"late_halves": self.late,
"underruns": self.underruns,
"dropped": self.dropped,
"repeated": self.repeated,
"max_lateness_ms": self.max_lateness_ns / 1e6,
"queued": self.wr - self.rd,
}
def deinit(self):
self.stop()
self._i2s.deinit()
self._mclk.deinit()
self._reset_pin.deinit()
radio_presets.py
This file is all about loading, parsing, and saving preset stations in a JSON file in the CPSAVES. It powers the ability for the user to save new presets and remove the ones that come hard-coded in the app.
# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""Station presets: the ones built into the code, changed by a JSON file.
The file lives in /saves, which CircuitPython code can write even while
CIRCUITPY is mounted on a computer. It looks like this (frequencies in Hz):
{"presets": {"FM": [99500000], "AM": [1190000], "WX": []},
"remove": [93100000, 162525000]}
"presets" holds the stations saved on each band, "remove" the built-in
presets taken out. Hand-written entries may also be typed frequencies such as
"99.5" or "1190"; they are stored in Hz the next time the radio saves.
"""
import json
import os
SAVE_PATH = "/saves/am_fm_radio.json"
def _list(value):
return value if isinstance(value, list) else ()
class Presets:
"""defaults maps each band to its built-in presets (Hz). band_of(value)
returns (band, Hz) for a saved value, or raises ValueError."""
def __init__(self, defaults, band_of, path=SAVE_PATH):
self.defaults = defaults
self.path = path
self.saved = {band: [] for band in defaults}
self.removed = []
if path:
self._load(band_of)
def _load(self, band_of):
try:
with open(self.path) as f:
data = json.load(f)
except OSError:
return # no file yet
except ValueError as error:
print("PRESETS_BAD_FILE", self.path, error)
return
if not isinstance(data, dict):
print("PRESETS_BAD_FILE", self.path)
return
saved = data.get("presets")
if not isinstance(saved, dict):
saved = {}
for key in self.defaults:
for value in _list(saved.get(key)):
station = self._check(band_of, value, key)
if station:
self.add(*station)
for value in _list(data.get("remove")):
station = self._check(band_of, value)
if station:
self.remove(*station)
def _check(self, band_of, value, band=None):
# (band, Hz) for a value read from the file, or None (and a warning)
# if it is not a frequency on one of the bands (or on band, if given).
try:
if isinstance(value, bool):
raise ValueError
station = band_of(str(value))
if station[0] == band or (band is None and station[0] in self.defaults):
return station
except ValueError:
pass
print("PRESETS_BAD_ENTRY", band or "remove", value)
return None
def stations(self, band):
"""The presets on band, built-in ones first, then the saved ones."""
removed = self.removed
stations = [hz for hz in self.defaults[band] if hz not in removed]
return stations + self.saved[band]
def add(self, band, hz):
"""Make hz a preset on band. Returns False if it already was."""
if hz in self.defaults[band]:
if hz not in self.removed:
return False
self.removed.remove(hz)
elif hz in self.saved[band]:
return False
else:
self.saved[band].append(hz)
return True
def remove(self, band, hz):
"""Take hz out of the presets on band. Returns False if it was not one."""
if hz in self.saved[band]:
self.saved[band].remove(hz)
elif hz in self.defaults[band] and hz not in self.removed:
self.removed.append(hz)
else:
return False
return True
def save(self):
"""Write the file. Raises OSError if /saves can't be written."""
# Write a new file and rename it over the old one, so a reset part
# way through leaves the old file intact. Then flush the flash cache
# now, while the caller has the radio stopped, rather than at the
# next background flush.
temp = self.path + ".tmp"
with open(temp, "w") as f:
json.dump({"presets": self.saved, "remove": self.removed}, f)
os.rename(temp, self.path)
os.sync()
radio_ui_am_fm.py
This contains all of the graphical and user interface elements for the project. Most of the UI is text that is drawn using terminalio.Terminal. Single lines of text are updated only when they actually change. This keeps the USB SDR data stream moving smoothly.
# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""AM/FM/weather radio tuner UI."""
import board
import displayio
import framebufferio
import picodvi
import terminalio
import bitmaptools
# pylint: disable=too-many-arguments
HELP = (
"B1 lower B2 higher hold B1: next band",
"B3 mute / hold: next preset hold B2: save/del",
"keys: - + tune b/a/n/w band p m f<freq> s x",
)
def format_frequency(hz):
# 101100000 -> '101.1 MHz', 162550000 -> '162.550 MHz', 610000 ->
# '610 kHz', from integers only. Above the FM band (weather) always show
# kHz, so 162.400 lines up with the other channels.
if not hz:
return "RADIO LAB"
if hz < 2000000:
return "%d kHz" % (hz // 1000)
if hz % 100000 or hz > 108000000:
return "%d.%03d MHz" % (hz // 1000000, hz // 1000 % 1000)
return "%d.%d MHz" % (hz // 1000000, hz // 100000 % 10)
class RadioUI:
def __init__(self):
displayio.release_displays()
self.fb = picodvi.Framebuffer(
320,
240,
clk_dp=board.CKP,
clk_dn=board.CKN,
red_dp=board.D0P,
red_dn=board.D0N,
green_dp=board.D1P,
green_dn=board.D1N,
blue_dp=board.D2P,
blue_dn=board.D2N,
color_depth=8,
)
self.display = framebufferio.FramebufferDisplay(self.fb, auto_refresh=False)
self.group = displayio.Group()
self.palette = displayio.Palette(5)
for i, c in enumerate((0x07111D, 0xFFC44D, 0xEAF1FA, 0x41DBAC, 0x294257)):
self.palette[i] = c
self.bg = displayio.Bitmap(320, 240, 5)
self.group.append(displayio.TileGrid(self.bg, pixel_shader=self.palette))
self.term = []
self._text(0, 8, 50, 2, 1)
self._text(8, 44, 25, 2, 2)
self._text(8, 114, 50, 8, 1)
self.display.root_group = self.group
self._shown = {}
self._level = -1
self.status = ""
self.frequency = 0
self.draw("STARTING", 0, "initializing receiver", "")
def _text(self, x, y, columns, rows, scale):
pal = displayio.Palette(2)
pal[0] = 0x07111D
pal[1] = 0xFFC44D if scale == 2 else 0xEAF1FA
fw, fh = terminalio.FONT.get_bounding_box()[:2]
grid = displayio.TileGrid(
terminalio.FONT.bitmap,
pixel_shader=pal,
width=columns,
height=rows,
tile_width=fw,
tile_height=fh,
)
g = displayio.Group(x=x, y=y, scale=scale)
g.append(grid)
self.group.append(g)
self.term.append(terminalio.Terminal(grid, terminalio.FONT))
def _line(self, term, row, text, width):
# Rewrite one text row, only if it changed. A full redraw takes longer
# than the USB ring lasts, so updates while the stream runs (mute,
# typing, an AM step inside the tuning window) must touch few rows.
text = ("%-*s" % (width, text))[:width]
key = (term, row)
if self._shown.get(key) == text:
return False
self._shown[key] = text
self.term[term].write("\x1b[%d;1H%s" % (row + 1, text))
return True
def draw(self, status, frequency, line1, line2, footer="RTL-SDR RECEIVER"):
# Only the rows that changed are rewritten, so this is cheap when, for
# example, only the status row differs from the last call.
self.status = status
self.frequency = frequency
changed = self._line(0, 0, "FRUIT JAM / DIRECT USB AM/FM/WEATHER", 49)
changed |= self._line(0, 1, status, 49)
changed |= self._line(1, 0, format_frequency(frequency), 24)
lines = (line1, line2, "") + HELP + (footer, "MONO / 3.5MM HEADPHONE JACK")
for row, text in enumerate(lines):
changed |= self._line(2, row, text, 49)
if changed:
self.display.refresh(minimum_frames_per_second=0)
return changed
def level(self, fraction):
# Signal bar, 0..1. Like entry() this runs while the stream is live, so
# it only redraws the bar, and only when its length changes.
n = min(304, max(0, int(fraction * 304))) & ~3
if n == self._level:
return
self._level = n
bitmaptools.fill_region(self.bg, 8, 98, 312, 105, 4)
if n:
bitmaptools.fill_region(self.bg, 8, 98, 8 + n, 105, 3)
self.display.refresh(minimum_frames_per_second=0)
def entry(self, text):
# Show a frequency being typed in place of the dial (None puts the
# dial and status back).
if text is None:
changed = self._line(0, 1, self.status, 49)
changed |= self._line(1, 0, format_frequency(self.frequency), 24)
else:
changed = self._line(0, 1, "TYPE A FREQUENCY, ENTER TO TUNE", 49)
changed |= self._line(1, 0, text[-23:] + "_", 24)
if changed:
self.display.refresh(minimum_frames_per_second=0)
Turbo Modules
There are two Turbo modules that are responsible for demodulating the AM/FM/WX broadcast signals, and processing the audio. This requires a lot of CPU power to pull off while keeping up with data coming in from the SDR, so the hard work is implemented in C modules that are compiled into the _fm_turbo95.mpy and _ham_dsp.mpy files. The source and build scripts for these turbo modules are available in the project repository on GitHub.
Page last edited October 09, 2026