Overview
Gaining support for USB SDR devices unlocks the ability to receive all sorts of interesting radio signals on CircuitPython based hardware. One such fun signal is SSTV, which are signals that decode into images. Hams broadcast these images back and forth on agreed upon frequencies somewhat regularly. Occasionally even the ISS gets in on the action with ARISS SSTV events. This guide will cover what you need in order to get your Fruit Jam and SDR set up to receive and decode these transmissions.
Gallery
Here are a handful of the fun SSTV images that have been captured and decoded on the Fruit Jam.
Nooelec NESDR Smart V5
Available from Nooelc directly, or other online retailers.
You will also need a suitable antenna for 14.230 MHz. The Antenna Options page provides parts list and instructions for 2 different antennas.
Micro SD card
Micro SD card with fast write times. This Amazon basics 64gb one was used successfully.
The 512mb one from the shop was tested but I found that writing to it stalled the USB input from the SDR.
Display Options
The project code supports two different display options. An HDMI display to see larger colored images as they're received, or a smaller OLED for on-the-go use with less power and cables to manage.
Or
Page last edited October 19, 2026
Install CircuitPython
CircuitPython is a derivative of MicroPython designed to simplify experimentation and education on low-cost microcontrollers. It makes it easier than ever to get prototyping by requiring no upfront desktop software downloads. Simply copy and edit files on the CIRCUITPY drive to iterate.
CircuitPython Quickstart
Follow this step-by-step to quickly get CircuitPython running on your board.
Click the link above to download the latest CircuitPython UF2 file.
Save it wherever is convenient for you.
To enter the bootloader, hold down the BOOT/BOOTSEL button (highlighted in red above), and while continuing to hold it (don't let go!), press and release the reset button (highlighted in red or blue above). Continue to hold the BOOT/BOOTSEL button until the RP2350 drive appears!
If the drive does not appear, release all the buttons, and then repeat the process above.
You can also start with your board unplugged from USB, press and hold the BOOTSEL button (highlighted in red above), continue to hold it while plugging it into USB, and wait for the drive to appear before releasing the button.
A lot of people end up using charge-only USB cables and it is very frustrating! Make sure you have a USB cable you know is good for data sync.
You will see a new disk drive appear called RP2350.
Â
Drag the adafruit-circuitpython-boardname-language-version.uf2 file to RP2350.
The RP2350 drive will disappear and a new disk drive called CIRCUITPY will appear.
That's it, you're done! :)
Safe Mode
You want to edit your code.py or modify the files on your CIRCUITPY drive, but find that you can't. Perhaps your board has gotten into a state where CIRCUITPY is read-only. You may have turned off the CIRCUITPY drive altogether. Whatever the reason, safe mode can help.
Safe mode in CircuitPython does not run any user code on startup, and disables auto-reload. This means a few things. First, safe mode bypasses any code in boot.py (where you can set CIRCUITPY read-only or turn it off completely). Second, it does not run the code in code.py. And finally, it does not automatically soft-reload when data is written to the CIRCUITPY drive.
Therefore, whatever you may have done to put your board in a non-interactive state, safe mode gives you the opportunity to correct it without losing all of the data on the CIRCUITPY drive.
To enter safe mode when using CircuitPython, plug in your board or hit reset (highlighted in red above). Immediately after the board starts up or resets, it waits 1000ms. On some boards, the onboard status LED (highlighted in green above) will blink yellow during that time. If you press reset during that 1000ms, the board will start up in safe mode. It can be difficult to react to the yellow LED, so you may want to think of it simply as a slow double click of the reset button. (Remember, a fast double click of reset enters the bootloader.)
In Safe Mode
If you successfully enter safe mode on CircuitPython, the LED will intermittently blink yellow three times.
If you connect to the serial console, you'll find the following message.
Auto-reload is off. Running in safe mode! Not running saved code. CircuitPython is in safe mode because you pressed the reset button during boot. Press again to exit safe mode. Press any key to enter the REPL. Use CTRL-D to reload.
You can now edit the contents of the CIRCUITPY drive. Remember, your code will not run until you press the reset button, or unplug and plug in your board, to get out of safe mode.
Flash Resetting UF2
If your board ever gets into a really weird state and CIRCUITPY doesn't show up as a disk drive after installing CircuitPython, try loading this 'nuke' UF2 to RP2350. which will do a 'deep clean' on your Flash Memory. You will lose all the files on the board, but at least you'll be able to revive it! After loading this UF2, follow the steps above to re-install CircuitPython.
Page last edited October 19, 2026
Antenna Options
This guide documents two ways to make a suitable antenna for HF SSTV: a long wire antenna with a balun one nine, and an MLA-30 active loop antenna. I have successfully captured SSTV images with both types. Either will work fine, but there are some tradeoffs to consider.
Both require some assembly and cost is similar between them. The active loop requires a USB power source, needs much less space, and has a little more assembly work. The long wire antenna is very simple to build, it requires only stripping a small length of the wire insulation and tinning the end with solder. It needs more time and effort to set up and take down. It needs a lot of space to set up, and can get tangled if not handled carefully.
Nooelec Balun One Nine v2
This balun device lets you hook up the long wire antenna. The balun sits between the long wires and the SDR.
I used the version with aluminum enclosure, but there is a bare bones one available as well for a few bucks less. They are available from Nooelec directly, or Amazon and other online retailers.
Coax Cable (Optional)
The Balun One Nine with enclosure kit comes with a small male SMA to male SMA adapter. This could be used to connect it to the SDR. A 6-12 ft / 1.82-3.65 m cable, like this one, can extend the connection further and make the setup a little more flexible.
If you do opt for the cable, using ferrite choke clips on it can reduce interference from it.
Long Wire
You'll need two lengths of wire:
- 58 ft / 17.68 m length for the antenna
- 15-25 ft 4.57-7.62 m length for the GND wire
I got a 100ft / 30 m roll of 18/2 speaker wire from a hardware store. Any 18 or 20 gauge stranded wire should work.
This speaker wire comes with two wires connected together by their insulation. I cut a 60 ft / 18.28 m length of it off the retail spool, then pulled it apart at the insulation seam so that I ended up with two 60 ft / 18.28 m wires. Next I cut 2 ft / 0.6 m off of one of them and cut the other into a split of 41 ft / 12.49 m and 19 ft / 5.79 m.
A 41 ft / 12.49 m length of antenna will work instead of 58 ft / 17.67 m for frequency 14.230. I tested both, but recommend using the 58 ft / 17.67 m length for anyone following along, it's better at receiving 7.171 on 40m band, and I got overall cleaner images from the 58 ft / 17.67 m wire. Though I did also let the listener run longer on the 58 ft / 17.67 m, and conditions will vary with time and location.
If you have dual speaker wire like I did you can follow the same approach I used to test both 41 ft / 12.49 m and 58 ft / 17.67 m feet if you're interested in the difference.
Additional Tools
- Wire cutters and stripper
- Soldering iron
- Small flat head screw driver for the wire terminal connectors
MLA-30 Loop Antenna Kit
These kits are available from various online retailers. The antenna kit needs to be assembled, it's intended to mount to a piece of PVC tube or a wooden dowel. I opted for the PVC tube.
3/4" / 1.90 cm PVC Pipe & Cap
At least 3 ft / 1 m in length. I used a 5 ft / 1.52 m section that the hardware store had cheap pre-cut lengths of.
Get a 3/4" / 1.90 cm PVC cap as well to fit over the top end of the antenna. It will help keep water and debris out of the PVC pipe while it's outdoors.
Antenna Mount
You need some way to mount or hold the antenna. The antenna being made of 3/4" PVC makes for many possible options. Umbrella holders, backyard torch holders, and flag mounts to name a few. You could even fashion your own holder in a number of creative ways.
I used a 2 gallon bucket with a few inches of sand in it. The lid has a cross of slits cut into the center of it. The PVC antenna pole shoves down into the center and it's bottom is held steady by the sand. The sand also gives it enough weight to resist blowing around in casual winds.
Page last edited October 19, 2026
Assemble
Using a hacksaw carefully cut a slit in one end of the PVC pipe. The slit should be as close to the center of the tube as you can get. It can be tricky to get the cut started in the center. If it doesn't come out perfectly aligned, don't worry, mine wasn't and still receives SSTV photos just fine.
The slit should be at least one inch, another quarter, or half inch longer would not hurt either. Better too deep than too shallow. It must be at least deep enough to allow the PVC cap to be placed on top and still have part of the slit poking out of the bottom of the cap.
Use the utility knife or an exacto blade to clean up the cut. It needs to be clear of plastic chips and other debris. After some cleanup with a knife the cut should be wide enough that the metal loop wire can fit into it snugly.
Insert the metal wire loop into the slit in the PVC. Try to aim for the middle of the loop wire half way between the folded end bits with small loops for the wingnuts. Only insert it a little at first, so it will be easy to adjust left or right if the full loop ends up lopsided.
The loop wire is spring loaded and wants to be coiled a few times into it's smaller mailer package size. Extend it all the way to make the full loop, it should be a little over 2 ft / 0.60 m in diameter.
Attach both ends of the loop wire to the MLA-30 box using the wing nuts on either side of it. The wire has a small loop in the end that fits over the threaded rod, the wing nut then screws down to secure it. With both sides fastened by wingnuts, position the box down around 2 ft / 0.60 m from the end of with the slit in it. Try to get the loop wire to make as close to a perfect circle as you can. If it's too big on one side adjust it left or right in the slit at the top to even it out.
Once everything is laid out in a good placement with a reasonably circular loop wire use a thin tipped marker or pen to mark the PVC through the center holes on the top and bottom of the MLA-30 box. Use a small drill bit to drill holes on each of the markings aligned to those center mounting holes on the MLA-30 box. Then use a screwdriver with the screws included in the MLA-30 kit to fasten the MLA-30 box to the PVC pipe, one screw at the top and one at the bottom of the box.
Press the loop wire far enough into the slit that the cap can fit on the end of the PVC with the wire running out beneath it.
Once the antenna is assembled and mounted or held by a bucket or something else you're ready to start receiving with it.
The MLA-30 box on the PVC has a coax/SMA wire coming out of it, unroll that far enough that the antenna can sit out away from structures, power lines, and other sources of interference. Connect the antenna coax to the connection on the MLA-30 small power injector box labeled "To Antenna"
Connect the small SMA male to SMA male coax cable included with the MLA-30 kit to the USB SDR plugged in to the Fruit Jam on one end, and the connector labeled "To Receiver" on the small MLA-30 power injector box on the other end.
Connect the MLA-30 power injector box to power with its USB micro cable.
Strip 1/3 to 1/2 an inch / 0.83 to 1.27 cm of insulation off one end of the 58 foot antenna wire, and the 19 ft / 5.79 m ground wire. Twist the ends of the stranded copper wires within, and tin them with a bit of solder.
These ends go into the Balun One Nine terminal connectors. Leave them disconnected while you string up the antenna wire and unfurl the ground wire so that they can freely untwist if they've been coiled up. Once the wires are fully extended, then connect them to the terminal connectors and tighten with a small flat head screwdriver.
The long wire antenna can be extended fully straight with one end tied up to a tree or pole using non-conductive rope or string, or looped around something non-conductive near the middle to make a large V shape.
I strung the long wire up with the middle looped around a tree branch. The far end I clamped to the edge of a plastic 5 gallon bucket with a plastic clamp. Near the Balun end of the long wire I clamped it to a fold in a nylon collapsible outdoor chair for strain relief. The wire should be tight enough to be up off the ground on both sides of the tree. The clamps allow it to be nearly taught.
The GND wire should run along the ground away from the Balun and antenna wire. Set it out straight along the ground or tuck the end of it into some grass to keep it coiling itself back up.
I opted for the 6 ft / 1.82 m coax SMA cable between the Balun and SDR so I set up a second outdoor chair a few feet away from the first to put the Fruit Jam on. With the small SMA adapter included with the Balun they would sit on the same chair. An additional plastic camp or two can help to provide strain relief and keep things on the chairs from shifting around too much.
Page last edited October 19, 2026
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
"""HF and ISS SSTV receiver on Fruit Jam (NESDR SMArt v5); pictures go to
/sd/hf_sstv/. They are shown on a 128x64 SH1107 OLED if one is on the
STEMMA QT port (I2C 0x3C), otherwise on HDMI.
For an ISS SSTV event, start
on its preset: run(preset=7) for 145.800 MHz, run(preset=8) for 437.550.
"""
import time
import supervisor
# hf_sstv_iss.py is compiled when imported, before its first line (the ring
# buffer, which moves the heap to PSRAM) runs, and compiling it grows the
# heap in internal SRAM: then the jack's audio buffers do not fit. A 1 MB
# block first puts the heap in PSRAM.
# pylint: disable=wrong-import-position
_ballast = bytearray(1024 * 1024)
from hf_sstv_iss import run
del _ballast
supervisor.runtime.autoreload = False
while True:
try:
run()
except Exception as error: # pylint: disable=broad-except
print("RADIO_ERROR", type(error).__name__, str(error))
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 and behavior.
hf_sstv_iss.py
This is the main application code. It listens for and reacts to input from the user on USB keyboard on on-board buttons. It has a PRESETS list that contains the list of frequencies and modes. The list in the code contains a good mix of HF band frequencies to try looking for ham SSTV images on including the default 14.230 which is most active, especially evenings and weekends. The list also includes ARISS frequencies 145.800 and 437.550 used during past SSTV events. You can edit the list if you know of more channels that contain SSTV transmissions in your area.
It contains a high level run() function that is called by code.py which has a number of arguments that can be used to change the default startup behavior including:
preset- an index of a preset inside ofPRESETSlist of preset channels and modes.frequency- a direct specific frequency to tune to by default instead of a preset.volume- the volume level of the 3.5mm output from the TLV320 dac.
One of the first things it does is check the I2C bus for the Featherwing OLED, based on whether it is connected the OLED or DVI based UI file will be imported.
# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""HF SSTV receiver: amateur slow-scan TV pictures on 20 m (14.230 MHz USB)
and the other SSTV calling frequencies, received, decoded and saved on the
Fruit Jam. Also receives the ISS (ARISS) SSTV events on
145.800 and 437.550 MHz FM.
If a 128x64 SH1107 OLED answers on the STEMMA QT port (I2C address 0x3C),
the pictures and status go to it (hf_sstv_display_oled.py); if not, to HDMI
(hf_sstv_display_hdmi.py). Only the module of the display used is
imported, so HDMI alone does not need adafruit_displayio_sh1107. With
neither working (or display=False) it runs without a display and still
saves the pictures.
A NESDR SMArt v5 (R820T2 tuner, HF through its direct-sampling input) on
the Fruit Jam's USB host port receives upper sideband; The 32 kHz audio
goes to the headphone jack, and _hf_sstv cuts it to 8 kHz into
a ring buffer in PSRAM while watching it for pictures:
- a VIS header (the 1.1 s of tones before each picture) gives the mode, the
start of the picture and the sender's tuning error;
- failing that (the header lost in a fade or under another station), a
train of line syncs at one mode's line rate starts a recording too.
The picture is drawn as it comes in: line by line on HDMI, or on the OLED
dithered to black and white (a row of the 64-row thumbnail every few
lines). When it ends, the recording is decoded on the Fruit Jam in
short steps while reception continues, which fixes slant from the sender's
clock error and removes the tuning error. Then, with the USB stream paused
briefly, it is saved to /sd/hf_sstv/ as an 8 kHz WAV and a full-size
colour BMP, with a line in log.txt, and the decoded picture replaces the
live one. If the next picture is already coming in, the save waits for it
to end.
ISS / ARISS: at and above FM_MIN (30 MHz) the receiver demodulates narrowband
FM with _sstv_dsp in place of _ham_dsp's upper sideband. Its automatic
frequency control (AFC) follows the satellite's Doppler shift
(about +-3.5 kHz on 2 m, +-11 kHz on 70 cm), the tuner gain
is fixed (FM_GAIN), and the jack plays the audio only
while the noise squelch hears a carrier. Everything after the demodulator
is the same: the VIS header or line syncs start a recording, and ISS
events send Robot 36 or PD120, both decoded here. On the ISS frequencies
(ISS_FREQUENCIES +-ISS_WINDOW) the carrier also starts a recording, since
a weak pass may never give a VIS header or a train of line syncs: it ends
when the carrier has been gone for HANG seconds, but not before the
picture's end (MIN_RECORD while its mode is unknown), recordings with less
than MIN_CARRIER seconds of carrier are dropped, and the rest are saved even
with no picture in them. Until the VIS header or the line syncs give the
mode, the recording counts as Robot 36. The presets after the HF ones are
ISS 2 m, ISS 70 cm and a NOAA weather station (an FM carrier to
test with, not SSTV).
Modes: Martin 1 and 2, Scottie 1, 2 and DX, PD90, PD120, PD180, Robot 36.
Scottie DX (270 s) is longer than the ring: only its first ~235 s are kept.
Buttons: B1/B2 tune down/up 100 Hz, B3 next preset; hold B1 to record now
(or end the recording), (OLED) B2 to switch between the picture and the
details view, and B3 to switch to the picture viewer and back. Serial
console: f<MHz>, + -, p, m (mute), d, r, g (viewer), and (OLED) v for the
view.
Picture viewer: shows the pictures saved in /sd/hf_sstv/, newest first;
B1 (or -) goes to the previous one, B2 (or +) to the next. Reception stops
while it is open (the receiver first decodes and saves any recording still
waiting), and starts again when it closes. It does not open while a
picture is coming in.
"""
# pylint: disable=wrong-import-position, global-statement, import-outside-toplevel, too-many-lines
# pylint: disable=too-many-locals, broad-except
# pylint: disable=unsupported-assignment-operation, unsubscriptable-object, too-many-nested-blocks
# pylint: disable=too-many-branches, too-many-statements, wrong-import-order, unused-variable
# Ring buffer of the 8 kHz audio. Allocated before anything else: it goes to
# PSRAM, and because it is bigger than all of internal SRAM, every later
# Python heap area is at least as big and also goes to PSRAM. That leaves
# internal SRAM for the USB bulk ring and the audio DMA buffers.
# 240 s holds the longest common mode (PD180, 188 s) with its pre-roll,
# plus time to decode it before new audio overwrites its start.
RING_SECONDS = 240
_ring = bytearray(RING_SECONDS * 16000)
import time
import gc
import os
import sys
import json
import math
import board
import busio
import displayio
import keypad
import supervisor
import usb.core
import usb_host_bulk
from ham_tuner import open_ham_receiver
from jack_audio import JackAudio
import _ham_dsp as dsp
import _hf_sstv as hf
import _sstv_dsp as fm
USB_MODE = 2 # _ham_dsp mode: upper sideband
RATE8 = 8000
# (label, dial frequency in Hz). SSTV is sent on upper sideband everywhere.
PRESETS = (
("20m SSTV", 14230000),
("20m SSTV (overflow)", 14227000),
("20m SSTV (overflow)", 14233000),
("40m SSTV", 7171000),
("80m SSTV (US, nights)", 3845000),
("15m SSTV", 21340000),
("10m SSTV", 28680000),
("ISS SSTV 2 m", 145800000),
("ISS SSTV 70 cm", 437550000),
("NOAA weather (FM test)", 162550000),
)
DEFAULT_PRESET = 0
STEP = 100 # Hz per +/- or arrow key
FM_STEP = 1000 # ... on FM
# FM (ISS) at and above FM_MIN, with _sstv_dsp: noise squelch (for the jack
# only: recordings start on the VIS header or line syncs, as on HF), tuner
# gain in tenths of a dB (None = tuner AGC) and the AFC's range around the
# dial.
FM_MIN = 30000000
FM_SQUELCH = 1500
FM_GAIN = 496
AFC_RANGE = 15000
FM_FLAG_AFC = 4
# ISS: on these frequencies (+-ISS_WINDOW, which covers tuning around them)
# a carrier starts a recording, by these rules:
ISS_FREQUENCIES = (145800000, 437550000)
ISS_WINDOW = 25000
CARRIER_START = 2 # carrier in this many readings (64 ms apart) starts a recording
HANG = 6.0 # carrier gone this long ends it (rides out fades)...
MIN_RECORD = 42.0 # ...but not before this long (a Robot 36 picture with its header
# and the pre-roll), or the picture's end once its mode is known
MIN_CARRIER = 5.0 # recordings with less carrier than this are dropped (bursts)
# The hardware centre sits above the dial so the signal is away from DC;
# tuning inside the window only moves the DSP oscillator.
CENTRE_OFFSET = 56000
WINDOW = (12000, 100000)
BLOCK = 8192 # I/Q bytes per DSP call -> 512 PCM samples (16 ms)
PCM_BLOCK = BLOCK // 8 # bytes of 32 kHz PCM per block
SAMPLES8 = PCM_BLOCK // 8 # 8 kHz samples per block (128)
PRE_ROLL = 2.0 # seconds kept before the VIS header or first sync
END_MARGIN = 3.0 # seconds kept after a picture's nominal end
SYNC_LOST = 12.0 # no line sync for this long ends a picture (HF fades
# last up to a few seconds)
MIN_SYNCS = 20 # line syncs needed to keep a recording (a VIS header
# with nothing after it is a false alarm)
MIN_FREE = 8 * 1024 * 1024 # keep this much of the card free
GC_IDLE = 120.0 # seconds between garbage collections while idle
SD_DIR = "/sd/hf_sstv"
ARROW_KEYS = {"[A": "+", "OA": "+", "[B": "-", "OB": "-", "[C": "p", "OC": "p"}
OLED_ADDRESS = 0x3C # SH1107 OLED on the STEMMA QT port
I2C_FREQUENCY = 400000 # board.I2C() runs at 100 kHz, too slow for the OLED
# The RTL2832U's digital AGC in direct sampling (ham_tuner turns it on). It
# lifts a weak antenna's output above the 8-bit quantization floor, but with
# a strong amplified antenna (such as an active loop) it drives the I/Q
# output into clipping. Off, the level reads about 15 dB lower.
RTL_AGC = False
MODES = [
hf.mode_info(i) for i in range(hf.N_MODES)
] # (name, vis, w, h, lines, line_us, seconds_ms, vis_to_sync0_us)
ISS_MODE = [m[0] for m in MODES].index(
"Robot 36"
) # a carrier recording's mode until it is known
_i2c = None
def shared_i2c():
"""The I2C bus of the STEMMA QT port and the jack's codec, at 400 kHz.
Created once and kept, so a restarted receiver can use it again."""
global _i2c
if _i2c is None:
# A display from before a soft reload still holds the bus (and the
# board starts with an HDMI framebuffer): release them first.
displayio.release_displays()
try:
_i2c = busio.I2C(board.SCL, board.SDA, frequency=I2C_FREQUENCY)
except ValueError:
# Pins already in use by board.I2C(): share that (100 kHz) one.
_i2c = board.I2C()
return _i2c
def open_display(kind=True):
"""The display to use: the OLED if it answers at OLED_ADDRESS, else
HDMI; None if neither works. kind 'oled' or 'hdmi' tries only that one.
Only the module of the display used is imported."""
ui = None
if kind in (True, "oled"):
i2c = shared_i2c()
while not i2c.try_lock():
pass
try:
found = OLED_ADDRESS in i2c.scan()
finally:
i2c.unlock()
if found:
try:
from hf_sstv_display_oled import OledDisplay
ui = OledDisplay(i2c, OLED_ADDRESS)
except Exception as error:
# For example adafruit_displayio_sh1107 missing from lib/.
print("OLED_ERROR", type(error).__name__, error)
if ui is None and kind in (True, "hdmi"):
try:
from hf_sstv_display_hdmi import HdmiDisplay
ui = HdmiDisplay()
except Exception as error:
print("HDMI_ERROR", type(error).__name__, error)
print("DISPLAY", ui.NAME if ui else None)
return ui
class Status:
"""What the display shows. The receiver keeps it up to date and calls
ui.show(status); the display module formats it."""
def __init__(self):
self.dial = 0
self.label = ""
self.demod = "USB" # 'USB' or 'FM'
self.level = -99 # dB
self.muted = False
self.record_all = False
self.state = "listen" # 'listen', 'rx', 'decode' or 'save'
self.mode = None # MODES entry being received, decoded or saved
self.line = 0 # line coming in
self.trigger = "" # what started the recording: 'vis', 'sync' or 'manual'
self.offset = None # sender's tuning error (Hz), if known
self.progress = 0 # decoding, percent
self.sd = False # card mounted
self.saved = 0 # files saved since start
self.pictures = 0 # pictures saved since start
self.free_mb = 0 # free on the card (after the last save)
self.last = (
None # last saved: (file name, mode name or None if no picture, lines)
)
self.note = None # (long, short) text in place of the last saved
def start_stream(d, audio):
# Audio first (its FIFO is allocated later, on first write), then the
# largest USB ring that fits: 128 ms of buffering, or 64 ms.
audio.start()
for size in (65536, 32768):
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 parse_frequency(text):
"""'14.23' (MHz) or '14230000' (Hz) -> Hz, without single-precision
floats, which cannot hold every frequency to the hertz."""
text = text.strip().lower().replace("mhz", "")
if "." in text:
whole, frac = text.split(".", 1)
if not frac.isdigit() or (whole and not whole.isdigit()):
raise ValueError(text)
return int(whole or "0") * 1000000 + int((frac + "000000")[:6])
value = int(text)
return value * 1000000 if value < 2000 else value
def level_db(power_q16):
"""Mean channel power (Q16 from _ham_dsp.status), dB relative to a
full-scale 8-bit sine."""
return 4.342944819 * math.log(power_q16 / 65536 / 16256.25 + 1e-12)
def wav_header(nbytes, rate=RATE8):
h = bytearray(44)
h[0:4] = b"RIFF"
h[4:8] = (36 + nbytes).to_bytes(4, "little")
h[8:16] = b"WAVEfmt "
h[16:20] = (16).to_bytes(4, "little")
h[20:22] = (1).to_bytes(2, "little") # PCM
h[22:24] = (1).to_bytes(2, "little") # mono
h[24:28] = rate.to_bytes(4, "little")
h[28:32] = (rate * 2).to_bytes(4, "little")
h[32:34] = (2).to_bytes(2, "little")
h[34:36] = (16).to_bytes(2, "little")
h[36:40] = b"data"
h[40:44] = nbytes.to_bytes(4, "little")
return h
def bmp_header(width, height):
"""24-bit uncompressed BMP header (rows bottom-up, BGR)."""
size = width * height * 3
h = bytearray(54)
h[0:2] = b"BM"
h[2:6] = (54 + size).to_bytes(4, "little")
h[10:14] = (54).to_bytes(4, "little")
h[14:18] = (40).to_bytes(4, "little")
h[18:22] = width.to_bytes(4, "little")
h[22:26] = height.to_bytes(4, "little")
h[26:28] = (1).to_bytes(2, "little")
h[28:30] = (24).to_bytes(2, "little")
h[34:38] = size.to_bytes(4, "little")
return h
def uptime():
"""Whole seconds since the board started."""
return time.monotonic_ns() // 1000000000
def mount_sd():
"""True if /sd is a mounted card. The supervisor mounts it at start-up;
if that failed, /sd is only the empty folder on CIRCUITPY, and writing
there would fill the internal flash, so try mounting the card here."""
try:
if os.statvfs("/sd") != os.statvfs("/"):
return True
except OSError:
pass
try:
import sdcardio
import storage
spi = busio.SPI(board.SD_SCK, board.SD_MOSI, board.SD_MISO)
storage.mount(storage.VfsFat(sdcardio.SDCard(spi, board.SD_CS)), "/sd")
return os.statvfs("/sd") != os.statvfs("/")
except Exception as error:
print("SD_MOUNT_ERROR", error)
return False
class Store:
"""Numbered WAV and BMP files and a log in SD_DIR."""
def __init__(self, directory=SD_DIR):
self.dir = directory
self.ok = mount_sd()
names = []
if self.ok:
try:
try:
os.mkdir(directory)
except OSError:
pass
names = os.listdir(directory)
except OSError as error:
print("SD_ERROR", error)
self.ok = False
self.next = 1
for name in names:
if name.startswith("hfsstv_") and name.endswith(".wav"):
try:
self.next = max(self.next, int(name[7:-4]) + 1)
except ValueError:
pass
self.saved = 0
self.images = 0
def free(self):
try:
s = os.statvfs(self.dir)
return s[0] * s[3]
except OSError:
return 0
def write_wav(self, ring, start, length):
"""Write ring[start:start+length] (bytes, wrapping) as the next WAV
file; returns its path without the extension."""
base = "%s/hfsstv_%04d" % (self.dir, self.next)
view = memoryview(ring)
size = len(ring)
with open(base + ".wav", "wb") as f:
f.write(wav_header(length))
pos, left = start % size, length
while left:
n = min(left, size - pos, 32768)
f.write(view[pos : pos + n])
pos = (pos + n) % size
left -= n
self.next += 1
self.saved += 1
return base
def write_bmp(self, base, bgr, width, height):
with open(base + ".bmp", "wb") as f:
f.write(bmp_header(width, height))
view = memoryview(bgr)
n = width * height * 3
for p in range(0, n, 32768):
f.write(view[p : min(n, p + 32768)])
self.images += 1
def log(self, info):
with open(self.dir + "/log.txt", "a") as f:
f.write(json.dumps(info) + "\n")
class Decoder:
"""Work memory for the decoder, the live preview and the BMP image, all
allocated once (PSRAM) for the largest mode."""
def __init__(self, ring_len):
self.work = bytearray(
max(hf.decode_work_bytes(i, ring_len) for i in range(hf.N_MODES))
)
self.preview = bytearray(
max(hf.preview_work_bytes(i) for i in range(hf.N_MODES))
)
self.bgr = bytearray(max(m[2] * m[3] for m in MODES) * 3)
def result(self):
r = hf.decode_result(self.work)
return {
"mode": MODES[r[0]][0],
"lines": r[1],
"first_line": r[2],
"vis": r[3],
"period_us": r[4],
"align": ("none", "vis", "first sync", "last sync")[r[5]],
"syncs": r[6],
"offset_hz": r[7],
}
def draw_picture(ui, bgr, width, height):
"""Show the decoded picture (in bgr, the BMP buffer) on the display."""
ui.picture_begin(width, height)
while not ui.picture_row(bgr):
pass
ui.picture_show()
def load_bmp(path, bgr):
"""Read a 24-bit uncompressed BMP (as this receiver saves) into bgr in
the decoder's layout: BGR, rows bottom-up, unpadded. Returns (width,
height)."""
with open(path, "rb") as f:
head = f.read(54)
if len(head) < 54 or head[0:2] != b"BM":
raise ValueError("not a BMP")
width = int.from_bytes(head[18:22], "little")
height = int.from_bytes(head[22:26], "little")
top_down = height >= 1 << 31
if top_down:
height = (1 << 32) - height
if head[28] != 24 or head[30:34] != b"\0\0\0\0":
raise ValueError("not a 24-bit uncompressed BMP")
if not 0 < width * height * 3 <= len(bgr):
raise ValueError("%d x %d is too big" % (width, height))
f.seek(int.from_bytes(head[10:14], "little"))
view = memoryview(bgr)
row = width * 3
pad = (-row) & 3
if not pad and not top_down:
# In pieces: one huge read from the SD card hangs and fails.
n, p = row * height, 0
while p < n:
k = f.readinto(view[p : min(n, p + 32768)])
if not k:
break
p += k
else:
skip = bytearray(pad)
for i in range(height):
y = height - 1 - i if top_down else i
f.readinto(view[y * row : (y + 1) * row])
if pad:
f.readinto(skip)
return width, height
def picture_info(directory):
"""{'hfsstv_NNNN': (mode, lines)} from the log in directory."""
info = {}
try:
with open(directory + "/log.txt") as f:
while True:
text = f.readline()
if not text:
break
if '"file"' not in text:
continue
try:
entry = json.loads(text)
decoded = entry.get("decode") or {}
name = entry["file"].split("/")[-1][:-4]
info[name] = (
decoded.get("mode") or entry.get("mode"),
decoded.get("lines", 0),
)
except (ValueError, KeyError, TypeError, AttributeError):
pass
except OSError:
pass
return info
def picture(result):
"""Whether the decoder found a picture in the recording."""
return result is not None and (
result["vis"] and result["syncs"] >= 5 or result["syncs"] >= MIN_SYNCS
)
class Replay:
"""Stands in for the USB stream and the demodulator: plays a WAV file
(16-bit mono, 32 kHz, or 8 kHz which is zero-stuffed to 32 kHz and
filtered by the decimator) through the receiver in real time, so the
whole chain can be tested without a signal on the air."""
def __init__(self, path):
self.f = open(path, "rb")
head = self.f.read(64)
self.rate = int.from_bytes(head[24:28], "little")
if self.rate not in (8000, 32000) or head[34] != 16:
raise ValueError("replay needs a 16-bit 8 or 32 kHz WAV")
at = head.find(b"data")
self.f.seek(at + 8 if at >= 0 else 44)
self.small = bytearray(PCM_BLOCK // 4)
self.next = time.monotonic_ns()
self.lost_packets = 0
self.done = False
def readinto(self, buf):
"""A whole block every 16 ms, like the USB stream."""
if time.monotonic_ns() < self.next:
return None
self.next += 16000000
return len(buf)
def fill(self, out):
"""The next 32 kHz PCM block into out (a byte view)."""
if self.rate == 32000:
k = self.f.readinto(out)
else:
k = 4 * self.f.readinto(self.small)
s = self.small
for i in range(0, len(s) - 1, 2):
# x4 in level, then three zero samples
v = s[i] | s[i + 1] << 8
v = (v - 65536 if v & 32768 else v) * 4
v = max(-32768, min(32767, v)) & 65535
j = 4 * i
out[j] = v & 255
out[j + 1] = v >> 8
out[j + 2] = out[j + 3] = out[j + 4] = out[j + 5] = out[j + 6] = out[
j + 7
] = 0
if not k or k < len(out):
self.done = True
for i in range(k or 0, len(out)):
out[i] = 0
def deinit(self):
self.f.close()
def decode_wav(path, mode=None, display=True):
"""Decode a saved recording (8 kHz WAV from this receiver, or a 32 kHz
16-bit mono WAV, e.g. from a PC) on the Fruit Jam,
write the BMP next to it and show it. The VIS header gives the mode,
else a sync train does, else `mode` (an index into MODES)."""
ring = _ring
det = bytearray(hf.STATE_BYTES)
with open(path, "rb") as f:
head = f.read(64)
rate = int.from_bytes(head[24:28], "little")
data_at = head.find(b"data")
f.seek(data_at + 8 if data_at >= 0 else 44)
view = memoryview(ring)
n = 0
if rate == 8000:
# In pieces: one huge read from the SD card hangs and fails.
while n < len(ring):
k = f.readinto(view[n : n + 65536])
if not k:
break
n += k
n -= n & 1
for p in range(0, n, 65536):
hf.scan(det, ring, p, min(65536, n - p))
elif rate == 32000:
buf = bytearray(65536)
while n < len(ring) - 16384:
k = f.readinto(buf)
if not k:
break
n = hf.feed(det, memoryview(buf)[: k & ~1], ring, n)
else:
raise ValueError("8 or 32 kHz WAV needed, not %d Hz" % rate)
events = []
while True:
e = hf.event(det)
if e is None:
break
events.append(e)
vis = [
e for e in events if e[0] == 1 and e[1] >= 0 and (mode is None or e[1] == mode)
]
sync = [e for e in events if e[0] == 2]
vis_pos = offset = None
if vis:
e = max(vis, key=lambda v: v[4])
mode, offset, vis_pos = e[1], e[3], n // 2 - e[5]
elif sync and mode is None:
mode = sync[0][1]
if mode is None:
print("DECODED", json.dumps({"file": path, "image": False, "events": events}))
return None
del det
gc.collect()
ui = open_display(display) if display else None
if ui:
ui.file_begin(path)
decoder = Decoder(len(ring))
dw, dh = ui.DECODE_SIZE if ui else (320, 240)
image = ui.decode_image if ui else None
t = time.monotonic_ns()
ok = hf.decode_begin(decoder.work, ring, 0, n, mode, offset, vis_pos, dw, dh)
p = 0
while ok and p < 100:
p = hf.decode_step(decoder.work, ring, image, decoder.bgr)
info = (
decoder.result() if ok else {"mode": MODES[mode][0], "syncs": 0, "vis": False}
)
info["ms"] = (time.monotonic_ns() - t) // 1000000
info["file"] = path
print("DECODED", json.dumps(info))
if ok and (info["vis"] or info["syncs"] >= MIN_SYNCS):
base = path[:-4] if path.lower().endswith(".wav") else path
w, h = MODES[mode][2], MODES[mode][3]
with open(base + ".bmp", "wb") as f:
f.write(bmp_header(w, h))
f.write(memoryview(decoder.bgr)[: w * h * 3])
if ui:
draw_picture(ui, decoder.bgr, w, h)
ui.file_done(info)
elif ui:
ui.file_done(None)
return info
def run(
seconds=0,
preset=DEFAULT_PRESET,
frequency=None,
volume=-10.0,
monitor=True,
display=True,
record_all=False,
commands=(),
log_every=10,
direct_input="Q",
replay=None,
rtl_agc=RTL_AGC,
fm_gain=FM_GAIN,
squelch=FM_SQUELCH,
):
"""Run the receiver. seconds=0 runs forever.
frequency (Hz) overrides the preset. monitor plays the audio on the jack.
record_all keeps recordings even when the decoder finds no picture.
commands is a list of (seconds, command) pairs fed to the command
handler, for unattended tests. replay: a WAV file to play through the
receiver instead of the radio (see Replay); it stops at the file's end.
display: True uses the OLED if one is found, else HDMI; 'oled' or
'hdmi' only that one; False none.
rtl_agc turns the RTL2832U's digital AGC on (see RTL_AGC).
fm_gain and squelch: the tuner gain and noise squelch on FM (FM_MIN and
up).
"""
supervisor.runtime.autoreload = False
preset_index = preset % len(PRESETS)
label, dial = PRESETS[preset_index]
if frequency is not None:
dial, label = frequency, "manual"
muted = not monitor
commands = sorted(commands)
ring = _ring
ring_len = len(ring)
ring_n = ring_len // 2 # samples
store = Store(SD_DIR)
decoder = Decoder(ring_len)
det = bytearray(hf.STATE_BYTES)
if store.ok:
# The board has no clock: times in the log are seconds since start-up.
try:
store.log(
{
"event": "start",
"uptime_s": uptime(),
"frequency": dial,
"rtl_agc": rtl_agc,
"fm_gain": fm_gain,
}
)
except OSError as error:
print("SD_ERROR", error)
gc.collect()
i2c = shared_i2c()
ui = open_display(display) if display else None
# Sizes the live preview and the decoder fit the picture into.
pw, ph = (ui.W, ui.H) if ui else (320, 240)
dw, dh = ui.DECODE_SIZE if ui else (320, 240)
status = Status()
audio = keys = d = stream = radio = None
if replay is None:
if ui:
ui.connecting()
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")
time.sleep(0.5)
d.set_configuration()
radio = open_ham_receiver(d, direct_input=direct_input)
def clamp(f):
if radio is None:
return f
return max(
radio.min_frequency + WINDOW[1], min(radio.max_frequency - WINDOW[1], f)
)
def on_iss(f):
return f >= FM_MIN and any(
abs(f - iss_f) <= ISS_WINDOW for iss_f in ISS_FREQUENCIES
)
dial = clamp(dial)
fm_band = dial >= FM_MIN
iss = on_iss(dial)
centre = dial + CENTRE_OFFSET
if radio is not None:
radio.initialize(
frequency=centre, sample_rate=256000, gain=fm_gain if fm_band else None
)
radio.hold_buffer()
def set_rtl_agc():
# Direct sampling only; entering it (again) turns the AGC on.
if radio is not None and radio.direct:
radio.demod(0, 0x19, 0x25 if rtl_agc else 0x05)
set_rtl_agc()
state = bytearray(8192)
fm_state = bytearray(4096)
def configure():
conjugate = 1 if radio is not None and radio.conjugate else 0
if fm_band:
fm.configure(
fm_state, dial - centre, squelch, FM_FLAG_AFC | conjugate, AFC_RANGE
)
else:
dsp.configure(state, USB_MODE, dial - centre, 0, conjugate)
def channel_power():
return (fm.status(fm_state) if fm_band else dsp.status(state))[0]
def band_note():
if radio is not None and radio.tuner_name != "R82xx" and not fm_band:
return ("no HF: use a NESDR SMArt v5", "NO HF")
return None
# Positions are in 8 kHz samples of the stream since start (total); the
# ring holds the last ring_n of them, sample s at byte 2 * (s % ring_n).
total = 0
wp = 0
barrier = 0 # no pre-roll from before this point (a pause)
rec = None # [start, mode, trigger, vis_end or None, offset or None, end_by, peak power,
# lowest AFC (Hz), highest AFC (None on HF), on the ISS (kept even with
# no picture), carrier readings, carrier lost at (sample) or None,
# mode known]. trigger 'carrier': end_by is the earliest end.
jobs = [] # recordings waiting for (or in) decoding
job = None # [start, length, mode, offset, vis_pos, info, stage, result] being decoded
preview = None # [line, sync sample] being drawn
next_line = 0
track = (-1, 0, 0, 0, 0, 0)
track_total = 0
rec_rows = None # display rows (y0, y1) or None for each line of the picture
job_p = 0 # decoding progress, percent
# note: (long text, short text) in place of the last picture saved
note = band_note()
# FM: whether the squelch hears a carrier (the jack plays only then),
# read every fourth block. A replay has no squelch: always played.
carrier = replay is not None
quarter = 0
open_reads = 0 # readings in a row with carrier, before a carrier recording
try:
audio = JackAudio(volume=volume, i2c=i2c)
keys = keypad.Keys(
(board.BUTTON1, board.BUTTON2, board.BUTTON3),
value_when_pressed=False,
pull=True,
)
configure()
gc.collect()
if replay is None:
radio.reset_buffer()
stream, usb_ring = start_stream(d, audio)
else:
audio.start()
stream, usb_ring = Replay(replay), 0
if ui:
ui.set_live(True)
iq = bytearray(BLOCK)
iqv = memoryview(iq)
filled = 0
max_dsp = max_feed = max_loop = max_ui = 0
lost_total = 0
stalls = []
decode_steps = 0
max_step = 0
start = time.monotonic()
last_log = start
last_ui = start
last_gc = start
last_track = start
pressed_at = [None, None, None]
line = None
esc = None
print(
"LIVE_START",
json.dumps(
{
"ring_size": usb_ring,
"dial": dial,
"centre": centre,
"tuner": radio.tuner_name if radio else "replay",
"direct": radio.direct if radio else None,
"rtl_agc": rtl_agc,
"fm": fm_band,
"record_ring_s": ring_n / RATE8,
}
),
)
paused = 0 # pause_stream() calls not yet resumed (they nest)
def pause_stream():
nonlocal lost_total, paused
paused += 1
if paused > 1:
return
if replay is None:
lost_total += stream.lost_packets
stream.deinit()
audio.stop()
audio.clear()
radio.hold_buffer()
if ui:
ui.set_live(False)
def resume_stream():
nonlocal stream, usb_ring, filled, barrier, paused
paused -= 1
if paused:
return
if replay is None:
barrier = total
radio.reset_buffer()
filled = 0
stream, usb_ring = start_stream(d, audio)
if ui:
ui.set_live(True)
def sd_info():
"""The saved counts and free space (statvfs can be slow: not live)."""
status.sd = store.ok
status.saved = store.saved
status.pictures = store.images
status.free_mb = store.free() // (1024 * 1024) if store.ok else 0
def show():
if not ui:
return
status.dial = dial
status.label = label
status.demod = "FM" if fm_band else "USB"
status.level = level
status.muted = muted
status.record_all = record_all
status.note = note
if rec is not None:
status.state = "rx"
status.mode = MODES[rec[1]]
status.line = max(0, track[1] if track[0] == rec[1] else 0)
status.trigger = rec[2]
status.offset = rec[4]
elif job is not None:
status.state = "decode"
status.mode = MODES[job[2]]
status.progress = job_p
status.trigger = job[5]["trigger"]
status.offset = job[3]
else:
status.state = "listen"
status.mode = None
ui.show(status)
def start_rec(mode, trigger, t_event, offset):
"""t_event: VIS end (vis) or earliest matched sync (sync)."""
nonlocal rec, next_line, preview, rec_rows
m = MODES[mode]
line_n = m[5] * RATE8 // 1000000
if ui:
# (PD modes send two picture rows per line.)
rows = 2 if m[0].startswith("PD") else 1
rec_rows = [
ui.rows(m[2], m[3], k * rows, (k + 1) * rows) for k in range(m[4])
]
ui.new_picture()
if trigger == "vis":
begin = t_event - int((0.91 + PRE_ROLL) * RATE8)
end_by = (
t_event + (m[6] - 910) * RATE8 // 1000 + int(END_MARGIN * RATE8)
)
elif trigger == "carrier":
# (t_event: when the carrier was first heard)
begin = t_event - int(PRE_ROLL * RATE8)
else:
begin = t_event - 4 * line_n - int(PRE_ROLL * RATE8)
end_by = t_event + m[4] * line_n + int(END_MARGIN * RATE8)
begin = max(begin, total - ring_n + 8 * SAMPLES8, barrier)
if trigger == "carrier":
end_by = begin + int(MIN_RECORD * RATE8)
rec = [
begin,
mode,
trigger,
t_event if trigger == "vis" else None,
offset,
end_by,
0,
None,
None,
iss,
0,
None,
trigger != "carrier",
]
next_line = 0
preview = None
print(
"RECORD_START",
json.dumps(
{
"mode": m[0],
"trigger": trigger,
"offset_hz": offset,
"seconds_back": (total - begin) / RATE8,
}
),
)
def set_mode(mode, t_event, offset, vis):
"""A carrier recording learns its mode, from the VIS header (vis:
t_event is its end) or a train of line syncs (t_event: the
earliest sync), and then lasts at least to the picture's end."""
nonlocal next_line, preview, rec_rows
m = MODES[mode]
if vis:
rec[3] = t_event
rec[4] = offset
end = t_event + (m[6] - 910) * RATE8 // 1000
else:
end = t_event + m[4] * (m[5] * RATE8 // 1000000)
rec[5] = end + int(END_MARGIN * RATE8)
rec[12] = True
if mode != rec[1]:
rec[1] = mode
if ui:
rows = 2 if m[0].startswith("PD") else 1
rec_rows = [
ui.rows(m[2], m[3], k * rows, (k + 1) * rows)
for k in range(m[4])
]
ui.new_picture()
next_line = 0
preview = None
print(
"RECORD_MODE",
json.dumps(
{
"mode": m[0],
"from": "vis" if vis else "sync",
"offset_hz": offset,
}
),
)
def finish(reason):
nonlocal rec, preview
(
begin,
mode,
trigger,
vis_end,
offset,
end_by,
peak,
afc_lo,
afc_hi,
keep,
carrier_reads,
) = rec[:11]
rec = None
preview = None
hf.track(det, -1)
length = total - begin
carrier_s = round(carrier_reads * 4 * SAMPLES8 / RATE8, 1)
if trigger == "carrier" and carrier_s < MIN_CARRIER and reason != "manual":
print(
"RECORD_DROPPED",
json.dumps({"seconds": length / RATE8, "carrier_s": carrier_s}),
)
return
info = {
"uptime_s": uptime(),
"seconds": round(length / RATE8, 1),
"mode": MODES[mode][0],
"trigger": trigger,
"reason": reason,
"dial": dial,
"offset_hz": offset,
"peak_level_db": round(level_db(peak), 1) if peak else None,
}
if fm_band:
info["demod"] = "FM"
info["afc_hz"] = [afc_lo, afc_hi]
if keep:
info["iss"] = True
if trigger == "carrier":
info["carrier_s"] = carrier_s
print("RECORD_END", json.dumps(info))
jobs.append(
[
begin,
length,
mode,
offset,
None if vis_end is None else vis_end - begin,
info,
0,
None,
]
)
def save(j, result):
"""Write the WAV, BMP and log line (stream paused)."""
nonlocal note
begin, length, mode, offset, vis_pos, info = j[:6]
info["decode"] = result
image = picture(result)
if not image and not record_all and not info.get("iss"):
info["saved"] = False
note = ("no picture in last recording", "no pic")
elif not store.ok:
note = ("not saved: no SD card", "NO SD")
elif store.free() < 2 * length + 2 * 1024 * 1024 + MIN_FREE:
note = ("not saved: SD card full", "SD FULL")
else:
t = time.monotonic_ns()
try:
base = store.write_wav(ring, 2 * (begin % ring_n), 2 * length)
info["file"] = base + ".wav"
name = base.split("/")[-1]
if image:
m = MODES[mode]
store.write_bmp(base, decoder.bgr, m[2], m[3])
status.last = (name, m[0], result["lines"])
else:
status.last = (name, None, 0)
note = None
info["write_ms"] = (time.monotonic_ns() - t) // 1000000
except OSError as error:
note = ("save failed: %s" % error, "SD ERR")
print("SAVE_ERROR", error)
sd_info()
try:
if store.ok:
store.log(info)
except OSError as error:
print("SAVE_ERROR", error)
print("SAVED", json.dumps(info))
def complete_job(result):
nonlocal job, last_gc
pause_stream()
try:
if ui:
status.state = "save"
status.mode = MODES[job[2]]
ui.show(status)
save(job, result)
if ui and picture(result) and rec is None and job[6] != 4:
# The decoded picture replaces the live one (unless the
# next picture came in meanwhile).
if job[6] == 3:
ui.picture_show()
else:
m = MODES[job[2]]
draw_picture(ui, decoder.bgr, m[2], m[3])
gc.collect()
last_gc = time.monotonic()
finally:
job = None
resume_stream()
def set_dial(f):
nonlocal dial, centre, barrier, fm_band, note, carrier, iss
dial = clamp(f)
iss = on_iss(dial)
band = dial >= FM_MIN
# On FM the AFC moves the DSP oscillator up to AFC_RANGE further.
low, high = (
(WINDOW[0] + AFC_RANGE, WINDOW[1] - AFC_RANGE) if band else WINDOW
)
if radio is not None and (
band != fm_band or not low <= centre - dial <= high
):
centre = dial + CENTRE_OFFSET
pause_stream()
try:
if band != fm_band:
# Remembered while in direct sampling, and applied
# when tune() leaves it.
radio.set_gain(fm_gain if band else None)
radio.tune(centre)
set_rtl_agc()
finally:
resume_stream()
if band != fm_band:
fm_band = band
note = band_note()
carrier = replay is not None
configure()
def finish_jobs():
"""Decode and save every recording still waiting, now."""
nonlocal job
while jobs or job is not None:
if job is None:
job = jobs.pop(0)
if job[6] >= 2:
complete_job(job[7])
continue
begin, length, mode, offset, vis_pos = job[:5]
ok = hf.decode_begin(
decoder.work,
ring,
2 * (begin % ring_n),
2 * length,
mode,
offset,
vis_pos,
dw,
dh,
)
p = 0 if ok else 100
image = ui.decode_image if ui and rec is None else None
while p < 100:
p = hf.decode_step(decoder.work, ring, image, decoder.bgr)
complete_job(decoder.result() if ok else None)
def read_controls():
"""The next action from the buttons or the serial console, or
None. Buttons: B1 down, B2 up, B3 next preset; hold B1 record now
(or end the recording), hold B2 switch the view (OLED; on HDMI
it tunes up), hold B3 the picture viewer. Serial mirrors them."""
nonlocal line, esc
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) >= 650
pressed_at[k] = None
views = ui is not None and ui.VIEWS > 1
action = (
("r" if held else "-"),
("v" if held and views else "+"),
("g" if held else "p"),
)[k]
if supervisor.runtime.serial_bytes_available:
ch = sys.stdin.read(1)
if ch == "\x1b":
esc, ch = "", ""
elif esc is not None:
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:
pass
elif line is not None:
if ch in "\r\n":
action, line = "f" + line, None
elif ch in "\x08\x7f":
line = line[:-1] if line else None
else:
line += ch
elif ch in "fF":
line = ""
else:
action = ch.lower()
return action
def picture_viewer():
"""The saved pictures, one at a time (B1/B2 previous/next), until
hold B3 (g) again. Reception stops meanwhile."""
nonlocal last_gc, muted
pause_stream()
try:
finish_jobs()
names = []
if store.ok:
try:
names = sorted(
n[:-4] for n in os.listdir(store.dir) if n.endswith(".bmp")
)
except OSError as error:
print("SD_ERROR", error)
info = picture_info(store.dir) if names else {}
k = len(names) - 1
show_at = k
print("VIEWER", json.dumps({"pictures": len(names)}))
ui.viewer_begin()
ui.viewer_text(
k, len(names), names[k] if names else None, None, 0, store.ok
)
while True:
if show_at is not None:
k, show_at = show_at, None
if names:
name = names[k]
mode, lines = info.get(name, (None, 0))
ui.viewer_text(k, len(names), name, "loading", 0, True)
t = supervisor.ticks_ms()
try:
w, h = load_bmp(
"%s/%s.bmp" % (store.dir, name), decoder.bgr
)
ui.viewer_picture(decoder.bgr, w, h)
if not mode:
mode = "%dx%d" % (w, h)
except (OSError, ValueError) as error:
print("VIEW_ERROR", name, error)
ui.viewer_picture(None, 0, 0)
mode, lines = "cannot read", 0
ui.viewer_text(k, len(names), name, mode, lines, True)
print(
"VIEW",
json.dumps(
{
"picture": name,
"index": k,
"mode": mode,
"ms": (supervisor.ticks_ms() - t) & 0x1FFFFFFF,
}
),
)
action = read_controls()
if (
not action
and commands
and time.monotonic() - start >= commands[0][0]
):
action = commands.pop(0)[1]
if action == "g":
break
if action in ("+", "-") and names:
show_at = (k + (1 if action == "+" else -1)) % len(names)
elif action == "v" and ui.VIEWS > 1:
ui.set_view(1 - ui.view)
elif action == "m":
muted = not muted
elif not action:
time.sleep(0.01)
ui.viewer_end()
gc.collect()
last_gc = time.monotonic()
finally:
resume_stream()
print("VIEWER_END")
sd_info()
# The loop below must not allocate in the per-block path (a garbage
# collection scans the heap and stalls for longer than the USB ring
# holds); gc.collect() runs while idle instead.
views = [iqv[k:] for k in range(0, BLOCK, 64)]
hang_n = int(HANG * RATE8)
min_reads = int(MIN_CARRIER * RATE8) // (4 * SAMPLES8)
tick = supervisor.ticks_ms
last_tick = tick()
now = start
level = -99
running = True
while running:
t = tick()
dt = (t - last_tick) & 0x1FFFFFFF
last_tick = t
max_loop = max(max_loop, dt)
if dt > 60 and len(stalls) < 8:
stalls.append((round(now - start, 1), dt))
n = stream.readinto(views[filled >> 6] if not filled & 63 else iqv[filled:])
if n == 0:
raise RuntimeError("USB stream ended")
if n:
filled += n
block = filled == BLOCK
if block:
filled = 0
now = time.monotonic()
if seconds and now - start >= seconds:
running = False
audio.service()
out = audio.write_view_bytes(PCM_BLOCK // 2)
t = tick()
if replay is not None:
stream.fill(out)
if stream.done:
running = False
elif fm_band:
fm.process(iq, out, fm_state)
else:
dsp.process(iq, out, state)
t2 = tick()
wp = hf.feed(det, out, ring, wp)
t3 = tick()
total += SAMPLES8
quarter = (quarter + 1) & 3
if not quarter:
# (Not every block: each call builds a tuple.)
if fm_band and replay is None:
carrier = fm.status(fm_state)[2]
# ISS: the carrier starts and ends recordings.
if rec is None:
open_reads = open_reads + 1 if iss and carrier else 0
if open_reads >= CARRIER_START:
open_reads = 0
start_rec(
ISS_MODE,
"carrier",
total - CARRIER_START * 4 * SAMPLES8,
None,
)
rec[10] = CARRIER_START
elif rec[2] == "carrier":
if not iss:
finish("retuned")
else:
if carrier:
rec[10] += 1
rec[11] = None
elif rec[11] is None:
rec[11] = total
# (A burst, too short to keep, ends without waiting.)
if (
rec[11] is not None
and total - rec[11] >= hang_n
and (total >= rec[5] or rec[10] < min_reads)
):
finish("carrier lost")
if not muted and (carrier or not fm_band):
audio.commit(PCM_BLOCK // 2)
audio.service()
t2, t3 = (t2 - t) & 0x1FFFFFFF, (t3 - t2) & 0x1FFFFFFF
max_dsp = max(max_dsp, t2)
max_feed = max(max_feed, t3)
e = hf.event(det)
while e is not None:
kind, mode, code, offset, extra, age = e
t_event = total - age
print(
"EVENT",
json.dumps(
{
"kind": ("", "vis", "sync")[kind],
"mode": MODES[mode][0] if mode >= 0 else None,
"vis_code": code,
"offset_hz": offset,
"extra": extra,
"seconds_ago": age / RATE8,
}
),
)
if kind == 1 and mode >= 0:
if rec is not None and rec[2] == "carrier" and rec[3] is None:
# The header of the picture this carrier brings.
set_mode(mode, t_event, offset, True)
else:
if rec is not None:
finish("new VIS")
start_rec(mode, "vis", t_event, offset)
elif kind == 2 and rec is None:
start_rec(mode, "sync", t_event, None)
elif kind == 2 and rec[2] == "carrier" and not rec[12]:
set_mode(mode, t_event, None, False)
e = hf.event(det)
if rec is not None:
# (A carrier recording ends when the carrier does, above.)
if total >= rec[5] and rec[2] != "carrier":
finish("end")
elif total - rec[0] >= ring_n - 2 * RATE8:
finish("ring full")
elif now - last_track >= 0.25:
track = hf.status(det)
track_total = total
last_track = now
# Peak level: read here, not every block (each call
# builds a tuple, and the heap fills with them).
if fm_band:
power, _, _, afc_hz = fm.status(fm_state)
if rec[7] is None or afc_hz < rec[7]:
rec[7] = afc_hz
if rec[8] is None or afc_hz > rec[8]:
rec[8] = afc_hz
else:
power = dsp.status(state)[0]
if power > rec[6]:
rec[6] = power
if (
rec[2] != "carrier"
and track[0] == rec[1]
and track[3] > SYNC_LOST * RATE8
and total - rec[0] > SYNC_LOST * RATE8
):
finish("syncs lost")
elif ui and track[0] == rec[1] and preview is None:
# Live picture: the next whole line not yet drawn.
m = MODES[rec[1]]
line_n = m[5] * RATE8 / 1000000
anchor = track_total - track[4]
# (floor division: a line not yet complete gives
# -1 here, which int() would round up to 0)
newest = (
int((total - anchor - line_n - 0.02 * RATE8) // line_n)
+ track[1]
)
if newest >= next_line:
if newest - next_line > 2:
next_line = newest
# Only lines that land on a display row
# are drawn (on the OLED, about one in four).
while (
next_line < newest
and 0 <= next_line < m[4]
and rec_rows[next_line] is None
):
next_line += 1
if (
0 <= next_line < m[4]
and rec_rows[next_line] is not None
):
s = int(anchor + (next_line - track[1]) * line_n)
if s > total - ring_n:
hf.preview_begin(
decoder.preview,
ring,
2 * (s % ring_n),
rec[1],
next_line,
rec[4] or 0,
pw,
ph,
)
preview = next_line
next_line += 1
if job is not None and total - job[0] >= ring_n - 2 * RATE8:
# New audio is about to overwrite the recording being
# decoded (or waiting to be saved): finish it now, with
# the stream paused, even in the middle of a recording.
if job[6] >= 2:
result = job[7]
else:
pause_stream()
ok = job[6] == 1 or hf.decode_begin(
decoder.work,
ring,
2 * (job[0] % ring_n),
2 * job[1],
job[2],
job[3],
job[4],
dw,
dh,
)
image = ui.decode_image if ui and rec is None else None
p = 0 if ok else 100
while p < 100:
p = hf.decode_step(decoder.work, ring, image, decoder.bgr)
resume_stream()
result = decoder.result() if ok else None
complete_job(result)
if (
rec is None
and job is None
and not jobs
and now - last_gc >= GC_IDLE
):
# A collection takes ~125 ms with the ring in the heap:
# longer than the loop can catch up on (the demodulator
# and detector use ~14 of every 16 ms), so pause the
# stream for it.
pause_stream()
try:
gc.collect()
finally:
resume_stream()
last_gc = now
if total > 1 << 29:
# Keep the counters small ints: move them back by
# whole rings (the ring position is unchanged).
shift = (total // ring_n - 2) * ring_n
total -= shift
barrier = max(0, barrier - shift)
elif not n:
# Idle until the next USB data: one short piece of work.
# The display first: an I2C refresh busy-waits, so it is
# only sent while the USB ring is empty.
t = tick()
if ui and ui.service():
t = (tick() - t) & 0x1FFFFFFF
max_ui = max(max_ui, t)
else:
if preview is not None and ui:
if hf.preview_step(decoder.preview, ring, ui.image):
if rec is not None and rec_rows[preview] is not None:
ui.image_rows(*rec_rows[preview])
preview = None
elif job is not None:
# Stages: 0 begin, 1 decode, 2 display rows (OLED
# thumbnail), 3 done, 4 done but a newer picture came
# in (not shown).
if job[6] == 0:
begin, length, mode, offset, vis_pos = job[:5]
job_p = 0
if hf.decode_begin(
decoder.work,
ring,
2 * (begin % ring_n),
2 * length,
mode,
offset,
vis_pos,
dw,
dh,
):
job[6] = 1
else:
job[6] = 3
elif job[6] == 1:
# (HDMI: the decoder draws the picture, unless
# the next one is coming in.)
job_p = hf.decode_step(
decoder.work,
ring,
ui.decode_image if ui and rec is None else None,
decoder.bgr,
)
decode_steps += 1
if job_p >= 100:
job[7] = decoder.result()
if ui and rec is None and picture(job[7]):
m = MODES[job[2]]
ui.picture_begin(m[2], m[3])
job[6] = 2
else:
job[6] = 4 if rec is not None else 3
elif job[6] == 2:
if ui.picture_row(decoder.bgr):
job[6] = 3
elif rec is None:
complete_job(job[7])
else:
# Saving pauses the stream (about 1 s, all lost),
# so it waits for the picture coming in to end: a
# gap inside a recording shifts its line syncs,
# the receiver then loses them and splits the
# picture.
job[6] = 4
time.sleep(0.0005)
elif jobs:
job = jobs.pop(0)
else:
time.sleep(0.0005)
t = (tick() - t) & 0x1FFFFFFF
max_step = max(max_step, t)
action = read_controls()
if commands and block and now - start >= commands[0][0]:
action = commands.pop(0)[1]
if action:
if action in ("+", "-"):
step = FM_STEP if fm_band else STEP
set_dial(dial + (step if action == "+" else -step))
label = "manual"
elif action == "p":
preset_index = (preset_index + 1) % len(PRESETS)
label, f = PRESETS[preset_index]
set_dial(f)
elif action == "m":
muted = not muted
audio.clear()
elif action == "d":
record_all = not record_all
elif action == "v":
# A whole-screen redraw is longer than the USB ring
# holds: with the stream paused, and not while a
# picture is coming in.
if ui and ui.VIEWS > 1 and rec is None:
pause_stream()
try:
ui.set_view(1 - ui.view)
finally:
resume_stream()
elif action == "g":
# The picture viewer: not while a picture is coming in.
if ui and rec is None:
picture_viewer()
else:
print("VIEWER_BUSY" if ui else "VIEWER_NO_DISPLAY")
action = None
elif action == "r":
# Record now (as Martin 1 unless the decoder finds the
# header), or end the recording.
if rec is None:
start_rec(0, "manual", total, None)
rec[5] = total + int((MODES[0][6] / 1000 + END_MARGIN) * RATE8)
else:
finish("manual")
elif action[0] == "f":
try:
set_dial(parse_frequency(action[1:]))
label = "manual"
except ValueError:
print("BAD_FREQUENCY", action[1:])
else:
action = None
if action:
show()
print(
"SET",
json.dumps(
{
"dial": dial,
"centre": centre,
"label": label,
"muted": muted,
"record_all": record_all,
"fm": fm_band,
}
),
)
if block and ui and now - last_ui >= 0.5 and preview is None:
level = int(level_db(channel_power()))
show()
last_ui = now
if block and now - last_log >= log_every:
fs = fm.status(fm_state) if fm_band else None
power = fs[0] if fm_band else dsp.status(state)[0]
st = hf.status(det)
print(
"LIVE",
json.dumps(
{
"seconds": round(now - start, 1),
"dial": dial,
"level_db": round(level_db(power), 1),
"sync_score": st[5] / 1000,
"fm": (
{
"sq_noise": round(fs[1] / 65536, 3),
"carrier": fs[2],
"afc_hz": fs[3],
}
if fs
else None
),
"recording_s": (
(total - rec[0]) / RATE8 if rec is not None else None
),
"iss": iss,
"track": st[:3],
"jobs": len(jobs) + (job is not None),
"saved": store.saved,
"dsp_max_ms": max_dsp,
"feed_max_ms": max_feed,
"step_max_ms": max_step,
"ui_max_ms": max_ui,
"loop_max_ms": max_loop,
"decode_steps": decode_steps,
"lost_packets": lost_total + stream.lost_packets,
"stalls": stalls,
"audio": audio.stats(),
}
),
)
last_log = now
max_loop = max_dsp = max_feed = max_step = max_ui = 0
stalls = []
if rec is not None:
finish("stopped")
finish_jobs()
print(
"RESULT",
json.dumps(
{
"seconds": time.monotonic() - start,
"saved": store.saved,
"lost_packets": lost_total + stream.lost_packets,
}
),
)
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~~")
hf_sstv_display_hdmi.py
Contains the UI for the DVI output version of the project. Connect an HDMI cable between the Fruit Jam's DVI output and a compatible display to use this version. It draws full color SSTV images line by line as they are received. It also shows a few status lines that indicate current reception level and whether an images is being received, decoded, or saved, and how many photos have been captured during this session.
# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""HDMI display for hf_sstv_iss.py: one fixed 320x240 screen.
hf_sstv_iss.py imports this module when no OLED answers on I2C;
hf_sstv_display_oled.py has the same methods for the OLED.
The picture (live, then decoded) fills the top IMAGE_H rows; two text rows
below show the frequency, signal and receiver state, then the last saved
file and the pictures saved since the start. Nothing ever redraws
the whole screen while the USB stream runs (a full redraw takes longer
than the USB ring holds): only changed text rows and the image rows just
drawn are refreshed. The refreshes are quick enough to send at once, so
the methods the OLED needs for queueing (set_live, service) do nothing.
"""
# pylint: disable=unused-argument, unnecessary-pass, no-self-use
import board
import displayio
import framebufferio
import picodvi
import terminalio
IMAGE_H = 212 # picture area height; the decoder fits each mode into 320 x IMAGE_H
def format_frequency(hz):
"""14230000 -> '14.230.00 MHz' (10 Hz resolution)."""
hz = int(hz)
return "%d.%03d.%02d MHz" % (hz // 1000000, hz // 1000 % 1000, hz // 10 % 100)
class HdmiDisplay:
NAME = "hdmi"
W, H = 320, IMAGE_H # the live preview draws into W x H
DECODE_SIZE = (320, IMAGE_H) # and the decoder too (decode_image)
VIEWS = 1
view = 0
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()
# The decoder and the live preview write RGB565 pixels straight into
# this bitmap's buffer; it is dithered to the 8-bit framebuffer.
self.image = displayio.Bitmap(320, IMAGE_H, 65536)
self.decode_image = self.image
converter = displayio.ColorConverter(
input_colorspace=displayio.Colorspace.RGB565, dither=True
)
self.group.append(displayio.TileGrid(self.image, pixel_shader=converter))
pal = displayio.Palette(2)
pal[0] = 0x07111D
pal[1] = 0xEAF1FA
fw, fh = terminalio.FONT.get_bounding_box()[:2]
self.columns = 320 // fw
rows = max(1, (240 - IMAGE_H) // fh)
grid = displayio.TileGrid(
terminalio.FONT.bitmap,
pixel_shader=pal,
width=self.columns,
height=rows,
tile_width=fw,
tile_height=fh,
)
g = displayio.Group(x=0, y=IMAGE_H + (240 - IMAGE_H - rows * fh) // 2)
g.append(grid)
self.group.append(g)
self.term = terminalio.Terminal(grid, terminalio.FONT)
self.rows_shown = rows
self._shown = {}
self.display.root_group = self.group
self.display.refresh(minimum_frames_per_second=0)
def text(self, row, text):
"""Rewrite one text row if it changed (about 7 ms); returns whether
it did."""
if row >= self.rows_shown:
return False
# One column short of the width: filling the last row wraps the
# cursor, which scrolls the terminal and blanks that row.
text = ("%-*s" % (self.columns - 1, text))[: self.columns - 1]
if self._shown.get(row) == text:
return False
self._shown[row] = text
self.term.write("\x1b[%d;1H%s" % (row + 1, text))
self.display.refresh(minimum_frames_per_second=0)
return True
def set_live(self, live):
pass
def service(self):
return False
def set_view(self, view):
return 0
def show(self, st):
"""The receiver's status (a hf_sstv_iss.Status)."""
mode = st.mode
if st.state == "rx":
state = "RX %s line %d/%d%s" % (
mode[0],
st.line,
mode[4],
"" if st.offset is None else " %+d Hz" % st.offset,
)
elif st.state == "decode":
state = "DECODING %s %d%%" % (mode[0], st.progress)
elif st.state == "save":
state = "SAVING %s" % mode[0]
else:
state = "listening"
self.text(
0,
"%s %s %4d dB %s%s"
% (
format_frequency(st.dial),
st.demod,
st.level,
state,
" MUTED" if st.muted else "",
),
)
# Pictures saved since this run started, at the right end of row 1.
pics = "%d pic%s" % (st.pictures, "" if st.pictures == 1 else "s")
if st.last:
name, mode_name, lines = st.last
last = (
"%s %s %d lines" % (name, mode_name, lines)
if mode_name
else "%s.wav (no picture)" % name
)
elif st.sd:
last = st.label
else:
last, pics = "NO SD CARD", ""
last += (" " + st.note[0] if st.note else "") + (
" [d: keep all]" if st.record_all else ""
)
width = self.columns - 2 - len(pics)
self.text(1, "%-*s %s" % (width, last[:width], pics))
def connecting(self):
self.text(0, "CONNECTING: looking for the USB receiver")
def file_begin(self, path):
"""decode_wav() is decoding the file at path."""
self.text(0, "DECODING %s" % path)
def file_done(self, info):
"""decode_wav() is done: info is the decoder's result, or None if
there was no picture."""
if info:
self.text(
0,
"%s %d lines%s"
% (info["mode"], info["lines"], ", VIS" if info["vis"] else ""),
)
else:
self.text(0, "NO IMAGE: no SSTV header or line syncs found")
def rows(self, width, height, row0, row1):
"""Display rows (y0, y1) where rows row0..row1-1 of a width x height
picture land (the preview fits it into W x H, centred)."""
if 320 * height <= IMAGE_H * width:
oh = 320 * height // width
else:
oh = IMAGE_H
oy = (IMAGE_H - oh) // 2
return oy + row0 * oh // height - 1, oy + (row1 * oh + height - 1) // height + 1
def new_picture(self):
"""A new live picture: drawn over the last one, line by line."""
pass
def image_rows(self, y0, y1):
"""Show image rows y0..y1-1 after the decoder or preview wrote them."""
y0 = max(0, y0)
y1 = min(IMAGE_H, y1)
if y1 > y0:
self.image.dirty(0, y0, 320, y1)
self.display.refresh(minimum_frames_per_second=0)
# The decoder draws the picture into decode_image itself: showing it
# is one refresh.
def picture_begin(self, width, height):
pass
def picture_row(self, bgr):
return True
def picture_show(self):
self.image_rows(0, IMAGE_H)
def clear_image(self):
"""Black picture area. A full refresh: call with the stream paused."""
self.image.fill(0)
self.display.refresh(minimum_frames_per_second=0)
# The picture viewer (the stream is paused).
def viewer_begin(self):
self.clear_image()
def viewer_text(self, index, count, name, mode, lines, sd):
"""Picture index (from 0) of count, its file name (no extension),
mode and lines (0 if not known); mode 'loading' while it loads."""
if count:
what = (
"loading..."
if mode == "loading"
else ("%s %d lines" % (mode, lines) if lines else (mode or ""))
)
self.text(0, "PICTURE %d/%d %s %s" % (index + 1, count, name, what))
else:
self.text(0, "PICTURES: none saved" if sd else "PICTURES: no SD card")
self.text(1, "B1 previous B2 next hold B3: back to receiving")
def viewer_picture(self, bgr, width, height):
"""Show a saved picture (bgr as the decoder leaves it: BGR, rows
bottom-up), fitted into the picture area, or none. About 1-2 s:
one sample per screen pixel, converted to RGB565 here."""
self.image.fill(0)
if bgr is not None:
if 320 * height <= IMAGE_H * width:
ow, oh = 320, 320 * height // width
else:
ow, oh = IMAGE_H * width // height, IMAGE_H
ox, oy = (320 - ow) // 2, (IMAGE_H - oh) // 2
cols = [(2 * x + 1) * width // (2 * ow) * 3 for x in range(ow)]
out = memoryview(self.image) # 16-bit pixels, rows unpadded at this width
for y in range(oh):
r = (height - 1 - (2 * y + 1) * height // (2 * oh)) * width * 3
i = (oy + y) * 320 + ox
for c in cols:
a = r + c
out[i] = (
(bgr[a + 2] & 0xF8) << 8
| (bgr[a + 1] & 0xFC) << 3
| bgr[a] >> 3
)
i += 1
self.image.dirty()
self.display.refresh(minimum_frames_per_second=0)
def viewer_end(self):
self.clear_image()
hf_sstv_display_oled.py
Contains the UI for the Featherwing OLED version of the project. Connect the Featherwing OLED to the Fruit Jam with a STEMMA QT cable to use this version. It draws scaled down, black and white, thumbnails of the received SSTV photos. The right side of the display shows a small status section with brief indicators about current tuning and state.
# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""SH1107 128x64 OLED (I2C) display for hf_sstv_iss.py.
hf_sstv_iss.py imports this module only when the OLED answers at its
I2C address; hf_sstv_display_hdmi.py has the same methods for HDMI. Text
is in the built-in 6x12 font.
Two views:
picture (the default) details
+--------------+-------+ +---------------------+
| |RX 123 | inverse |RX Martin 1 123/256 | inverse
| 86 x 64 |14.2300| dial |14.230.00 USB -28dB |
| dithered |-28dB | level |Martin 1 VIS +57 Hz |
| picture |Mart 1 | mode / pics |saved 3 pics 3 29G |
| |#0003 | last saved |#0003 Martin 1 256 ln|
| |===== | signal bar +---------------------+
+--------------+-------+
The signal bar is thick while a picture is coming in and thin otherwise.
The picture: the live preview draws RGB565 pixels into `image`, which is
not shown; image_rows() dithers it (bitmaptools.dither, native code) and
copies only the rows just drawn to the shown 1-bit `thumb`, so a new
picture wipes down over the last one, as on a real SSTV screen. The
decoded picture replaces it: picture_begin() and picture_row() average its
luma from the decoder's BMP buffer one row per call (in the receive loop's
idle time), and picture_show() stretches the contrast (weak pictures come
out grey), dithers it and sends the whole picture.
Sending to the display is the expensive part: an I2C refresh busy-waits,
about 10 ms per whole text row at 400 kHz, two to three times that while
USB streams, and a whole screen 50 ms or more. The demodulator and the
detector leave the receive loop only 2-3 ms of every 16, so only the
characters (and the part of the bar, and the picture rows) that changed
are sent, and with the stream running (live) the methods only note what
changed: service(), called by the receive loop when it has caught up,
sends one of them at a time. Otherwise (the stream paused: saving)
changes are shown at once. Switching views and picture_show() redraw the
whole screen, so the receiver does those with the stream paused.
"""
# pylint: disable=too-many-branches, too-many-locals, attribute-defined-outside-init, no-self-use
import displayio
import terminalio
import bitmaptools
from i2cdisplaybus import I2CDisplayBus
from adafruit_displayio_sh1107 import SH1107
ROTATION = 90 # 270 turns the picture upside down
THUMB_W, THUMB_H = 86, 64 # 86: a 16-bit Bitmap row of 86 pixels has no padding,
# as the decoder's RGB565 output needs
COLUMN = 7 # characters beside the picture (86 + 7 * 6 = 128)
COLUMNS = 21 # characters across the details view
BAR_W = 42
LEVEL_RANGE = (-70, -10) # dB at the ends of the signal bar (-63 dB with no antenna)
# Text rows: 0-4 beside the picture, 5-9 the details view. Each is a
# one-row terminal: writing the last column of a multi-row terminal scrolls it.
DETAILS = 5
# Order in which service() sends queued changes: state, bar, picture first.
ORDER = (0, 5, "bar", "thumb", 1, 2, 3, 4, 6, 7, 8, 9)
# Mode names for the 7-character column beside the picture.
SHORT = {
"Martin 1": "Mart 1",
"Martin 2": "Mart 2",
"Scottie 1": "Scot 1",
"Scottie 2": "Scot 2",
"Scottie DX": "ScotDX",
"Robot 36": "Rob 36",
}
def format_frequency(hz):
"""14230000 -> '14.230.00' (MHz, 10 Hz resolution)."""
hz = int(hz)
return "%d.%03d.%02d" % (hz // 1000000, hz // 1000 % 1000, hz // 10 % 100)
def fit(width, height):
"""(ow, oh, ox, oy): a width x height picture fitted into the
thumbnail, centred, as the decoder fits it."""
if THUMB_W * height <= THUMB_H * width:
ow, oh = THUMB_W, THUMB_W * height // width
else:
ow, oh = THUMB_H * width // height, THUMB_H
return ow, oh, (THUMB_W - ow) // 2, (THUMB_H - oh) // 2
def _palette(inverse=False):
pal = displayio.Palette(2)
pal[0] = 0xFFFFFF if inverse else 0x000000
pal[1] = 0x000000 if inverse else 0xFFFFFF
return pal
class OledDisplay:
NAME = "oled"
W, H = THUMB_W, THUMB_H # the live preview draws into W x H
DECODE_SIZE = (320, 240) # (the decoder draws nothing here: decode_image)
VIEWS = 2
def __init__(self, i2c, address):
# Also frees the HDMI framebuffer the board starts with: its SRAM is
# needed for the USB bulk ring and the audio DMA buffers.
displayio.release_displays()
bus = I2CDisplayBus(i2c, device_address=address)
self.display = SH1107(
bus, width=128, height=64, rotation=ROTATION, auto_refresh=False
)
self.term = []
self.width = []
self._shown = {}
# The live preview writes RGB565 pixels straight into this bitmap's
# buffer; it is dithered into _dith, and rows of that go to thumb.
self.image = displayio.Bitmap(THUMB_W, THUMB_H, 65536)
# The decoded picture is made from the BMP buffer instead.
self.decode_image = None
self._dith = displayio.Bitmap(THUMB_W, THUMB_H, 2)
self.thumb = displayio.Bitmap(THUMB_W, THUMB_H, 2)
self.group = displayio.Group()
self.group.append(displayio.TileGrid(self.thumb, pixel_shader=_palette()))
for k in range(5):
self._text(self.group, THUMB_W, 12 * k, COLUMN, k == 0)
self.signal_bar = displayio.Bitmap(BAR_W, 3, 2)
self.group.append(
displayio.TileGrid(self.signal_bar, pixel_shader=_palette(), x=THUMB_W, y=61)
)
self.details = displayio.Group()
for k in range(5):
self._text(self.details, 0, 2 + 12 * k, COLUMNS, k == 0)
self.view = 0 # 0 picture, 1 details
self.live = False # see set_live()
self._want = {} # row, 'bar' or 'thumb' -> not yet shown
self._level = -1
self._top = 0 # thumb rows above this show the new picture
self._key = None # what show() last formatted
self.luma = bytearray(THUMB_W * THUMB_H)
self._hist = [0] * 64
self._fit = None # decoded picture's fit and size, for picture_row()
self._ty = 0
self.display.root_group = self.group
self.display.refresh(minimum_frames_per_second=0)
def _text(self, group, x, y, columns, inverse=False):
fw, fh = terminalio.FONT.get_bounding_box()[:2]
grid = displayio.TileGrid(
terminalio.FONT.bitmap,
pixel_shader=_palette(inverse),
width=columns,
height=1,
tile_width=fw,
tile_height=fh,
)
g = displayio.Group(x=x, y=y)
g.append(grid)
group.append(g)
self.term.append(terminalio.Terminal(grid, terminalio.FONT))
self.width.append(columns)
self.term[-1].write(" " * columns)
def _visible(self, key):
if key in ("bar", "thumb"):
return self.view == 0
return (key >= DETAILS) == (self.view == 1)
def _write(self, row, text):
"""Write only the characters that differ: every tile written is sent
to the display, changed or not."""
old = self._shown.get(row, " " * len(text))
self._shown[row] = text
a, b = 0, len(text)
while a < b and old[a] == text[a]:
a += 1
while b > a and old[b - 1] == text[b - 1]:
b -= 1
if a < b:
self.term[row].write("\x1b[1;%dH%s" % (a + 1, text[a:b]))
def _draw_bar(self, level):
"""level = length * 2 + thick. Only the part that changed is drawn."""
old, self._level = self._level, level
n, thick = level >> 1, level & 1
y0, y1 = (0, 3) if thick else (1, 2)
if old >= 0 and old & 1 == thick:
m = old >> 1
if n > m:
bitmaptools.fill_region(self.signal_bar, m, y0, n, y1, 1)
elif n < m:
bitmaptools.fill_region(self.signal_bar, n, y0, m, y1, 0)
return
self.signal_bar.fill(0)
if n:
bitmaptools.fill_region(self.signal_bar, 0, y0, n, y1, 1)
def _draw_rows(self, band):
"""Dither the whole image (rows above a band do not depend on rows
below it) and copy the band's rows to the shown thumbnail."""
y0, y1 = band
bitmaptools.dither(
self._dith,
self.image,
displayio.Colorspace.RGB565,
bitmaptools.DitherAlgorithm.Atkinson,
)
bitmaptools.blit(self.thumb, self._dith, 0, y0, x1=0, y1=y0, x2=THUMB_W, y2=y1)
def _apply(self, key, value):
if key == "bar":
self._draw_bar(value)
elif key == "thumb":
self._draw_rows(value)
else:
self._write(key, value)
def _queue(self, key, value):
"""Show a change now, or (live) note it for service()."""
if self.live:
self._want[key] = value
return
self._apply(key, value)
if self._visible(key):
self.display.refresh(minimum_frames_per_second=0)
def set_live(self, live):
"""True while the USB stream runs; False shows what is queued."""
self.live = live
if not live and self._want:
for key in ORDER:
if key in self._want:
self._apply(key, self._want.pop(key))
self.display.refresh(minimum_frames_per_second=0)
def service(self):
"""Live: send the first queued change; changes to the view not shown
are only written. Call when the receive loop has caught up. Returns
True if it refreshed the display."""
if not self._want:
return False
for key in ORDER:
if key in self._want:
self._apply(key, self._want.pop(key))
if self._visible(key):
self.display.refresh(minimum_frames_per_second=0)
return True
return False
def text(self, row, text):
"""Rows 0-4: the column beside the picture (7 characters); 5-9: the
details view (21). Only a changed row is queued or shown."""
width = self.width[row]
text = ("%-*s" % (width, text))[:width]
if self._shown.get(row) == text:
self._want.pop(row, None)
elif self._want.get(row) != text:
self._queue(row, text)
def meter(self, fraction, thick):
"""Signal bar (0..1), thick while a picture is coming in."""
n = min(BAR_W, max(0, int(fraction * BAR_W))) & ~1
level = n * 2 + (1 if thick else 0)
if level == self._level:
self._want.pop("bar", None)
else:
self._queue("bar", level)
def set_view(self, view):
"""0: picture, 1: details. Redraws everything: call with the stream
paused."""
if view != self.view:
self.view = view
self.set_live(False)
self.display.root_group = self.details if view else self.group
self.display.refresh(minimum_frames_per_second=0)
return self.view
def show(self, st):
"""The receiver's status (a hf_sstv_iss.Status)."""
mute = " M" if st.muted else ""
self.text(2, "%ddB%s" % (st.level, mute))
self.text(
6, "%s %s %ddB%s" % (format_frequency(st.dial), st.demod, st.level, mute)
)
self.meter(
(st.level - LEVEL_RANGE[0]) / (LEVEL_RANGE[1] - LEVEL_RANGE[0]),
st.state == "rx",
)
# The other rows only when what they show changed (formatting them
# allocates, and this runs every 0.5 s).
key = (
st.state,
st.mode,
st.line,
st.progress,
st.trigger,
st.offset,
st.dial,
st.label,
st.note,
st.last,
st.sd,
st.saved,
st.pictures,
st.free_mb,
st.record_all,
)
if key == self._key:
return
self._key = key
mode = st.mode
if st.state == "rx":
state, state_long = "RX %d" % st.line, "RX %s %d/%d" % (
mode[0],
st.line,
mode[4],
)
elif st.state == "decode":
state, state_long = "DEC %d%%" % st.progress, "DECODING %s %d%%" % (
mode[0],
st.progress,
)
elif st.state == "save":
state, state_long = "SAVING", "SAVING %s" % mode[0]
else:
state, state_long = "LISTEN", "LISTENING" + (
" keep all" if st.record_all else ""
)
last_short = last_long = ""
if st.last:
name, mode_name, lines = st.last
last_short = "#" + name[-4:]
if mode_name:
last_long = "%s %s %d ln" % (last_short, mode_name, lines)
else:
last_long = "%s no picture" % last_short
if not st.sd:
sd_text = "NO SD CARD: no saving"
else:
free = st.free_mb
sd_text = "saved %d pics %d %s" % (
st.saved,
st.pictures,
"%dG" % (free // 1024) if free >= 10000 else "%dM" % free,
)
self.text(0, state)
# (7 characters: 1 kHz resolution from 100 MHz up)
if st.dial >= 100000000:
self.text(1, "%d.%03d" % (st.dial // 1000000, st.dial // 1000 % 1000))
else:
self.text(1, "%d.%04d" % (st.dial // 1000000, st.dial // 100 % 10000))
# Listening: pictures saved since this run started, in place of the
# band (the dial shows it).
pics = st.pictures
self.text(
3,
(
SHORT.get(mode[0], mode[0])
if mode
else (
("%d pic%s" % (pics, "" if pics == 1 else "s"))
if pics < 100
else "%dpic" % pics
)
),
)
self.text(4, st.note[1] if st.note else last_short)
self.text(5, state_long)
if mode:
self.text(
7,
"%s %s%s"
% (
mode[0],
"VIS" if st.trigger == "vis" else st.trigger,
"" if st.offset is None else " %+d Hz" % st.offset,
),
)
else:
self.text(7, st.label)
self.text(8, sd_text)
self.text(9, st.note[0] if st.note else last_long)
def connecting(self):
self.text(0, "USB")
self.text(5, "CONNECTING")
self.text(6, "looking for RTL-SDR")
def file_begin(self, path):
"""decode_wav() is decoding the file at path."""
name = path.split("/")[-1]
self.text(0, "DECODE")
self.text(1, name[-11:-4] if name.lower().endswith(".wav") else name[-7:])
self.text(5, "DECODING")
self.text(6, name)
def file_done(self, info):
"""decode_wav() is done: info is the decoder's result, or None if
there was no picture."""
if info:
self.text(0, "DONE")
self.text(2, SHORT.get(info["mode"], info["mode"]))
self.text(3, "%d ln" % info["lines"])
self.text(4, "VIS" if info["vis"] else "sync")
self.text(5, "DECODED")
self.text(
7,
"%s %d lines%s"
% (info["mode"], info["lines"], ", VIS" if info["vis"] else ""),
)
self.text(8, "offset %+d Hz" % info["offset_hz"])
else:
self.text(0, "NO IMG")
self.text(5, "NO IMAGE")
self.text(7, "no SSTV header or")
self.text(8, "line syncs found")
def rows(self, width, height, row0, row1):
"""Thumbnail rows (y0, y1) that show rows row0..row1-1 of a width x
height picture, or None if none does (the preview fits the picture
into W x H, centred, and gives each thumbnail row the picture row
nearest its centre)."""
f = fit(width, height)
oh, oy = f[1], f[3]
rows = [
d
for d in range(
max(0, row0 * oh // height - 1), min(oh, row1 * oh // height + 2)
)
if row0 <= (2 * d + 1) * height // (2 * oh) < row1
]
return (oy + rows[0], oy + rows[-1] + 1) if rows else None
def new_picture(self):
"""A new live picture: its rows will wipe down over the last one."""
self.image.fill(0)
self._top = 0
self._want.pop("thumb", None)
def image_rows(self, y0, y1):
"""Show thumbnail rows y0..y1-1 after the preview wrote them, and the
rows above them not shown yet for this picture (lines skipped)."""
y0 = max(0, min(y0, self._top))
y1 = min(THUMB_H, y1)
if y1 <= y0:
return
self._top = max(self._top, y1)
band = self._want.get("thumb")
self._queue("thumb", (min(y0, band[0]), max(y1, band[1])) if band else (y0, y1))
def picture_begin(self, width, height):
"""Start a thumbnail of a decoded width x height picture."""
self._fit = f = fit(width, height) + (width, height)
self._ty = 0
# Byte offsets in a BMP row of the three sample columns of each pixel.
self._cols = [(2 * k + 1) * width // (6 * f[0]) * 3 for k in range(3 * f[0])]
luma = self.luma
for i in range(len(luma)):
luma[i] = 0
hist = self._hist
for k in range(64):
hist[k] = 0
def picture_row(self, bgr):
"""One thumbnail row from the decoder's BMP buffer (BGR, rows
bottom-up): luma averaged over 3 x 3 samples spread over each
pixel's area (weak pictures are mostly noise; fewer samples leave
too little of the picture at this size). Returns True when all rows
are done."""
ow, oh, ox, oy, w, h = self._fit
y = self._ty
if y < oh:
r0 = (h - 1 - (6 * y + 1) * h // (6 * oh)) * w * 3
r1 = (h - 1 - (6 * y + 3) * h // (6 * oh)) * w * 3
r2 = (h - 1 - (6 * y + 5) * h // (6 * oh)) * w * 3
luma, hist, cols = self.luma, self._hist, self._cols
i = (oy + y) * THUMB_W + ox
# (No tuple assignments or tuples: building one allocates, and
# allocating here would bring on a garbage collection.)
for x in range(ow):
v = 0
for k in range(3 * x, 3 * x + 3):
c = cols[k]
a = r0 + c
b = r1 + c
d = r2 + c
v += (
29 * (bgr[a] + bgr[b] + bgr[d])
+ 150 * (bgr[a + 1] + bgr[b + 1] + bgr[d + 1])
+ 77 * (bgr[a + 2] + bgr[b + 2] + bgr[d + 2])
)
v //= 2304
luma[i] = v
if v:
# Lines never received are black: leave them out of
# the contrast stretch.
hist[v >> 2] += 1
i += 1
y += 1
self._ty = y
return y >= oh
def picture_show(self):
"""Show the finished thumbnail: contrast stretched between the 2nd
and 98th percentiles, dithered. Redraws the picture: call with the
stream paused."""
if self._fit is None:
return
hist = self._hist
count = sum(hist)
lo, hi, total = 0, 255, 0
for k in range(64):
total += hist[k]
if total > count // 50:
lo = k * 4
break
total = 0
for k in range(63, -1, -1):
total += hist[k]
if total > count // 50:
hi = k * 4 + 3
break
span = max(hi - lo, 16)
# Grey RGB565 for each luma value (the letterbox, luma 0, stays black).
lut = [0] * 256
for v in range(1, 256):
g = min(255, max(0, (v - lo) * 255 // span))
lut[v] = (g & 0xF8) << 8 | (g & 0xFC) << 3 | g >> 3
out = memoryview(self.image) # 16-bit pixels, rows unpadded at this width
luma = self.luma
for i in range(len(luma)):
out[i] = lut[luma[i]]
self._fit = None
self._top = THUMB_H
self._want.pop("thumb", None)
self._draw_rows((0, THUMB_H))
if self.view == 0:
self.display.refresh(minimum_frames_per_second=0)
# The picture viewer (the stream is paused: changes are shown at once).
def viewer_begin(self):
self.image.fill(0)
self.thumb.fill(0)
self._fit = None
self._top = THUMB_H
self._want.pop("thumb", None)
self.meter(0, False)
if self.view == 0:
self.display.refresh(minimum_frames_per_second=0)
def viewer_text(self, index, count, name, mode, lines, sd):
"""Picture index (from 0) of count, its file name (no extension),
mode and lines (0 if not known); mode 'loading' while it loads."""
if count:
pos = "%d/%d" % (index + 1, count)
if mode == "loading":
short, long = "load..", "loading..."
else:
short = SHORT.get(mode, mode) if mode else ""
long = "%s %d lines" % (mode, lines) if lines else (mode or "")
rows = (
"VIEW",
pos,
"#" + name[-4:],
short,
"%d ln" % lines if lines else "",
"VIEWING %s" % pos,
name + ".bmp",
long,
"B1 prev B2 next",
)
else:
rows = (
"VIEW",
"none" if sd else "NO SD",
"",
"",
"",
"VIEWER: no pictures" if sd else "VIEWER: no SD card",
"",
"",
"",
)
for k in range(9):
self.text(k, rows[k])
self.text(9, "hold B3: receive")
def viewer_picture(self, bgr, width, height):
"""Show a saved picture (bgr as the decoder leaves it), or none."""
if bgr is None:
self.thumb.fill(0)
if self.view == 0:
self.display.refresh(minimum_frames_per_second=0)
return
self.picture_begin(width, height)
while not self.picture_row(bgr):
pass
self.picture_show()
def viewer_end(self):
"""Back to receiving: a blank picture; show() rewrites the text."""
self.viewer_begin()
self._top = 0
self._key = None
# 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.
* 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)
# librtlsdr's R82xx 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
# librtlsdr's 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 in supervisor.ticks_ms, 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 supervisor
import adafruit_tlv320
# pylint: disable=too-many-branches, attribute-defined-outside-init
RATE = 32000
MCLK = 15_000_000
TICKS_MASK = 0x1FFFFFFF # supervisor.ticks_ms wraps at 2**29 ms
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.
i2c is the bus to the codec (default board.I2C()), for sharing it with
other devices on the STEMMA QT port at a faster clock.
"""
def __init__(self, half=2048, fifo=16384, target=4096, volume=-10.0, i2c=None):
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
if half * 1000 % RATE:
raise ValueError("half must last a whole number of ms")
self.half_ms = half * 1000 // 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(i2c or 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_ms = 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 = supervisor.ticks_ms()
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 = (supervisor.ticks_ms() - self._t0) & TICKS_MASK
j = now // self.half_ms
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_ms
self.max_lateness_ms = max(self.max_lateness_ms, 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
if self._next >= 1 << 16:
# Every ~70 minutes, move the start forward by an even number of
# halves (the same half is next), long before the ticks wrap.
k = (self._next - 2) & ~1
self._t0 = (self._t0 + k * self.half_ms) & TICKS_MASK
self._next -= k
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_ms,
"queued": self.wr - self.rd,
}
def deinit(self):
self.stop()
self._i2s.deinit()
self._mclk.deinit()
self._reset_pin.deinit()
Turbo Modules
There are three Turbo modules that are responsible for demodulating the received 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 _sstv_dsp.mpy, _hf_sstv.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 19, 2026
Use
The largest portion of the display will show live previews of SSTV photos line by line as they come in, and then corrected versions after the decoder finishes. Depending on the encoding of the image it can take 36 seconds, up to about 3 minutes for an image to be fully received. Decoding and saving begins automatically after it's been received.
The display also shows a few lines of text that show the current frequency and status of the receiver app.
The Featherwing OLED displays an abbreviated version of the same details on the right side of the display. It shows a black and white dithered preview thumbnail rendering of the incoming SSTV photos. It can be difficult to make out details of photos on the OLED. The photos saved on the SD card are still full size and color to view later on a computer or with the DVI display.
Audio Output
The receiver app will output audio from the current frequency via the 3.5mm jack on the Fruit Jam. Connect standard headphones to listen in. This is completely optional, the receiver will record and decode automatically even if nothing is plugged in the 3.5mm jack.
It can be helpful to listen after you first get set up to ensure the antenna is connected correctly. There is a NOAA weather radio station in the presets for the purpose of listening to for validation of a properly connected and working antenna.
On the SSTV frequencies listening can also help inform you of local interference. If you hear loud buzzing or other unexpected sounds, you can try moving the antenna or powering off things in the vicinity until it goes away in the audio.
It's also interesting to listen to the beeps, boops, and warbling tones that get decoded into the picture.
Controls
You can use the built-in buttons on the Fruit Jam or a USB keyboard to control the receiver app.
Change Presets
Cycle through the list of preset frequencies. You can edit the list PRESETS in hf_sstv_iss.py if you want to add your own stations or remove any of the included ones.
On-board Buttons
Press button 3 on the Fruit Jam to change to the next preset frequency.
USB Keyboard
Press the "P" key on the USB keyboard to change to the next preset frequency.
Manual Tune
Both USB keyboard and on-board buttons offer a way to seek up and down though the frequencies. The USB keyboard also lets you directly tune to a specific station.
On-board Buttons
Press button 1 and button 2 to seek down and up through frequencies.
USB Keyboard
Press the arrow down and arrow up keys on the USB keyboard to seek down and up through frequencies. To tune to a specific frequency press the "F" key, then type the desired frequency, and finally press the enter key.
Access Photo Viewer Mode
The receiver app has a photo viewer mode that lets you look at all of the photos that have been decoded and saved on the SD card. Listening stops while in viewer mode.
On-board Buttons
Press and hold button 3 for a full second then release it to access photo viewer mode. Use the same long-press on button 3 to go back to the receiver when you're ready.
USB Keyboard
Press the "G" key on the USB keyboard to enter photo viewer mode, and press "G" again to exit back to the receiver mode.
Change Photos in Viewer Mode
Photo viewer mode shows the most recent photo by default. You can cycle through all of the stored photos forward or backwards.
On-board Buttons
Press button 1 to go to the previous stored photo, and press button 2 to go to the next stored photo.
USB Keyboard
Press the down arrow key to go to the previous stored photo, and the up arrow key to go to the next photo.
Manual Recording
The receiver app will automatically record incoming SSTV images that are identified correctly with header and metadata. Sometimes you may want to record something else that you find interesting that isn't SSTV. I heard Morse code messages on one of the preset frequencies which led me to add this feature so that I could capture and decode the Morse.
On-board Buttons
Long press button 1 on the Fruit Jam to start a manual recording, long-press button 1 again to stop the recording that is in progress.
USB Keyboard
Press the "R" key on the USB keyboard to start a manual record, and press "R" again to stop the recording that is in progress.
Page last edited October 19, 2026
ARISS SSTV
A few times a year, ARISS holds SSTV events in which images are broadcast from the International Space Station (ISS) as it orbits the Earth. These photos are tricky to capture because you need to be set up and listening during time when the ISS is passing over your location at a reasonably high angle.
Keep an eye on the ARISS SSTV Events page to find the dates of upcoming events.
The images above are the best captures I got from SSTV Expedition 75 Series 33, featuring "Student Education". These are black and white depictions of the photos created by filtering noise out of the capture and using luma averaging. The first photo clearly depicts the rectangle shape of the image within the transmitted SSTV slide. The text along the top is recognizable as "Student Education 2026", which I knew to look for after visiting the gallery of submitted photos. The second capture contained only the footer of the image, in the bottom left "NA1SS" is legible, which is the designated amateur call sign for the ISS.
Series 34 "ARISS Hardware" came hot on the heels of series 33. But, I was better prepared this time with a selection of different antennas. I managed to capture some great photos during the series 34 event.
The 437.55 frequency used by the recent and upcoming SSTV events can be captured using 433 MHz antennas such as the longer of the two whip antennas that comes with the NESDR Smart V5 bundle.
The base of the mount is magnetic and it needs to be stuck to a flat piece of metal to work well, like a car roof, baking sheet, or piece of sheet metal. That is what I used during the Series 33 event
The best captures that I got during the Series 34 event were received on this 433 MHz ground plane antenna. I mounted it on a 4 foot piece of 2x4 and used a 5 gallon bucket with some sand in it and a hole in the lid for a base.
The reception area of ground plane antennas is shaped like a large torus or donut over the top of the antenna with a line extending from the point of the antenna upward through the donut hole in the center of the torus shape. That means there is a "quiet zone" directly above the antenna where reception will not be as strong. This property makes the ground plane best suited for for lower angled passes. It yielded the best results for me on all passes that were below 80 degrees max angle.
The other antenna that I tried during this event is the RTL-SDR blog multipurpose dipole kit. For 437.550 MHz, use the shorter of the two sets of metal telescoping antennas, extended to their full length and set at a 120 degree angle apart from each other. The dipole should be laid flat with the two points pointing at the horizon and the broad side pointed to the sky. The dipole antenna in this configuration picks up better signal directly above it than the ground plane does. At the height of a pass that is near the full 90 degrees max angle, the ISS will spend some time in a zone that the dipole is better suited for receiving. An 81 degree max angle pass is the only one during this event where the dipole received a cleaner photo than the ground plane.
If you want a single antenna, go with a 433 MHz ground plane. There are typically many more low and mid range angle passes over a given area during the few days of an SSTV event than there are very high ones near 90 degrees.
There are handheld Yagi antennas that can be purchased or made DIY. These are held and pointed manually towards the ISS, sweeping in an arc along the sky with it as it passes. It requires more preparation and using an app or some other source to know where the ISS will be in relation to your location so you can line it up correctly, but is said to have good reception.
Page last edited October 19, 2026