Fabric School

Fishball7020 · PlutoSky · 7020-SDR

Fabric School

A ground-up course in software-defined radio, and in the FPGA inside this one. It assumes you have never written Verilog or opened Vivado, and are not sure what an FPGA, a spectrum or a decibel is. By the end you will have your own signal processing running inside the radio's datapath.

Every term is defined the first time it appears. Every trap is one that actually cost someone an afternoon on this board.

XC7Z020-CLG400 AD9361 · 2R2T Vivado 2022.2 Ubuntu 22.04 Verilog-2001

Before any code

0

What a radio does, and what "software-defined" changes

Start here even if it feels too basic.

A radio signal is a wave — a voltage that swings up and down very fast. How fast is its frequency, in hertz (Hz), cycles per second. A million per second is a megahertz (MHz); a billion is a gigahertz (GHz). This board works between 70 MHz and 6 GHz.

To send information you modulate the wave: change something about it in a pattern the other end can read — its height (amplitude), its timing (phase), or its frequency. That is all radio is.

The traditional way, and the software way

A conventional radio does this with dedicated circuits. An FM radio's demodulator is soldered in; it cannot become a Wi-Fi receiver.

A software-defined radio (SDR) keeps only the parts that must be analogue — amplifiers, filters, converters — and turns the signal into numbers as early as possible. What the radio is then depends on what you do with the numbers.

Three words you now own

ADC
Analogue-to-Digital Converter. Measures a voltage many times a second and produces a number each time. The doorway in.
DAC
Digital-to-Analogue Converter. Turns a stream of numbers back into a voltage. The doorway out.
Sample
One of those numbers — one measurement of the signal at one instant.

Every SDR has the same shape: antenna → analogue parts → ADC → numbers → something that processes them → and back out. This course is about that "something".

Why put your own logic in there at all

Often a PC is the right place. But samples arrive at up to 61.44 million pairs per second, and shipping them costs bandwidth and uncontrolled delay. Anything that must react in microseconds, shrink the data first, or be exactly timed belongs where the samples are: the FPGA.

1

What an FPGA is, and why it is not a processor

The single mental shift that makes everything else make sense.

A processor — the CPU in your laptop — is fixed circuitry that reads instructions one after another. It is fast because each step is quick, but it does one thing at a time.

An FPGA — Field-Programmable Gate Array — is a large field of tiny, blank logic elements plus a switching network between them. "Programming" it means configuring what circuit it physically becomes, not giving it instructions.

What the field is made of

LUT
Look-Up Table. A tiny memory, typically 6 inputs wide, that can be filled in to produce any logical function of those inputs. This board's chip has 53,200 of them.
Flip-flop
A one-bit memory that captures its input at a precise moment and holds it. Anything that remembers a value between clock ticks is built from these.
DSP slice
A hard-wired multiplier-and-adder. Multiplication is expensive in LUTs, so the chip includes 220 ready-made ones. Filters live on these.
Block RAM
Small dedicated memories for buffering data on-chip.

The consequence: everything happens at once

Describe ten filters and you get ten filters, all running simultaneously; an eleventh uses more chip, not more time. That suits radio: fixed hardware handles every one of 61 million samples per second as it passes, with predictable timing.

The beginner's mistake

Writing Verilog as if it were software. A line of Verilog is not a step after the previous line — it is circuitry that exists at the same time as every other piece. Two always blocks are two independent lumps of hardware, both live on every clock edge. If you catch yourself thinking "and then it does…", ask what the circuit looks like.

The price you pay

  • It is slower per operation: tens to a few hundred MHz. It wins by parallelism.
  • The build is slow. Synthesis, placement and routing take twenty minutes to an hour on this board, which is why simulation matters so much (lesson 10).
  • Resources are finite and visible. You will run out of DSP slices or fail timing, and have to make real trade-offs.
2

The Fishball7020, part by part

Two computers, one radio chip, and the connection between them.

The main chip is a Xilinx XC7Z020-CLG400, a Zynq: a processor and an FPGA on the same die.

PS
Processing System — two ARM Cortex-A9 cores. Fixed silicon, where Linux boots, the IIO daemon runs and your Python sits.
PL
Programmable Logic — the FPGA fabric of lesson 1: 53,200 LUTs, 220 DSP slices. What Verilog describes and a bitstream configures.
AXI
The bus that connects them. When Linux writes a register and your fabric logic sees it change, AXI carried that write.

The radio chip is an Analog Devices AD9361: a complete transceiver covering 70 MHz to 6 GHz, with two receivers and two transmitters — amplifiers, mixers, filters, ADCs and DACs. A fast digital interface connects it to the fabric, and the Linux driver configures it over SPI, a simple serial control bus.

The parts that matter

From the vendor schematic, checked on a running board; full table in docs/hardware.md.

PartWhat it isWhy you care
Xilinx XC7Z020-CLG400Zynq-7000: two Cortex-A9 cores plus Artix-7 fabricEverything this course calls "the fabric".
Analog Devices AD93612×2 transceiver, 70 MHz–6 GHz The radio. Two receive and two transmit chains, hence 2R2T.
2 × Mini-Circuits PGA-102+transmit power amplifier, one per channelWhat makes this board not a Pluto. Measured at about 15.7 dB of gain at 900 MHz.
2 × Micron MT41K256M16DDR3L, 4 Gbit each on a 32-bit bus1 GB. The board reports MemTotal: 1027848 kB.
Realtek RTL8211Fgigabit Ethernet PHYA stock Pluto has USB only. Wired gigabit is why streaming both receivers is practical.
Winbond W25Q128JV16 MB QSPI flashFSBL, U-Boot and a small recovery Linux, in four partitions totalling exactly 16 MiB.
FTDI FT2232HLUSB to JTAG and serial console One socket, two ttyUSB ports. The serial console shows the boot.
Microchip USB3320CUSB 2.0 OTG PHYThe usb0 network interface — the other way to reach the board.
4 × RF baluns (T1–T4) single-ended SMA to the AD9361's differential pins One per SMA port. The schematic gives no part number.

Balun

Balanced to unbalanced. A coaxial cable and an SMA connector are unbalanced: one conductor carries the signal, the shield is ground. The AD9361's radio pins are balanced (differential): each port is a pair, TX1A_P and TX1A_N, carrying equal and opposite swings. A balun translates between the two; here, a tiny transformer.

Differential pairs reject noise that lands on both wires equally. Baluns are also fairly narrowband: the board covers only what its baluns pass, which can only be measured (lesson 42).

What the radio will actually do

These are the limits the board itself reports, readable from any board with iio_attr.

RangeWorth knowing
RX tuning70 MHz – 6 GHz
TX tuning46.875 MHz – 6 GHzThe transmitter tunes lower than the receiver.
Sample rate2.083 – 61.44 MSPSBelow 2.083 MSPS the AD9361's own FIR must be engaged; the tools do it for you.
RX bandwidth200 kHz – 56 MHzThe analogue baseband filter, set separately from the sample rate.
RX gain−3 – +71 dBAn index into a gain table, not a dial — lessons 47 and 48.
TX attenuation0 – −89.75 dB−89.75 is the floor, and the value every safety check in this repository asserts.

This board has power amplifiers, and most Pluto advice does not

Out: plan for roughly +19 dBm flat out. That is the self-test's capped estimate, never put on a power meter: an order of magnitude, not a specification.

In: the receive input's absolute maximum is about +2.5 dBm, roughly 16 dB below that, so a bare cable from a transmit port to a receive port destroys the receiver. Fit at least 20 dB of attenuation in any TX→RX loopback, and measure through exactly 20 dB — a bigger pad lets the board's own internal leakage into your result. Before raising output, record that you have looked at the port: ./devkit tx-guard affirm 0 (TX1A) or 1 (TX2A).

Clocks, and the one that is the radio's accuracy

Six oscillators, but only the 40 MHz reference feeding the AD9361 matters for radio work. Every frequency is derived from it, so its error is the radio's error — a reference 10 ppm high puts 900 MHz 9 kHz off.

Its pin 1, on a net named XTAL_VTC, is on JP5 pin 15; the schematic calls that pin OE, so whether it tunes the oscillator or switches it off is unconfirmed: check before driving it. EXT_CLK on a U.FL is connected to nothing as shipped: fitting the empty R109 joins it to the AD9361's reference, to feed a GPS-locked or shared reference in (or this board's 40 MHz out), and R110 joins it to the FPGA. Without soldering, ./devkit clock corrects the reference in software. TX_LO and RX_LO are on U.FL too, for running two boards coherently.

What one of these measures like

Bench measurements on a single unit: indicative, not a specification.

Gain accuracy, 56 slope measurementswithin 1.7 % of 1.000 dB/dB
Image rejection, after calibration44 – 60 dBc
Harmonics, 2nd / 3rd−64 to −80 / −71 to −85 dBc
Transmit mute depthat least 75 dB
Loop gain through 20 dB, 200 MHz – 1 GHz+19 to +22.5 dB
Receiver against receiverRX2 is 1.5 dB more sensitive
Transmitter against transmitterwithin 0.2 dB
Fabric used by the default build94 of 220 DSPs, 12 521 LUTs
… and by STOCK_RX_FILTER=1, upstream’s wiring72 of 220 DSPs, 11 896 LUTs

How to tell this board from the ones the internet writes about

Run iio_attr -S. FISH Ball PlutoSDR Rev.A (Z7020-AD9361) is this board. Z7010 means half the fabric; AD9363 (the ADALM-PLUTO's chip) is specified to 325 MHz–3.8 GHz and 20 MHz bandwidth. Either way this firmware will not fit unchanged.

Board vocabulary

Bitstream
The file that configures the PL — about 4 MB. It lives inside BOOT.bin on the SD card and is loaded at every power-on.
FSBL
First Stage Boot Loader. The first code that runs; it loads the bitstream and then the bootloader.
Device tree
A data file describing the hardware to Linux — which chips exist, at which addresses, with which settings. Linux does not discover any of this; it is told.
2R2T
"Two receive, two transmit" — the AD9361 mode this board runs in. It has consequences in lesson 14.

Two things the fabric cannot reach

The USER LED sits on a PS pin (MIO 0). MIO pins are not wired into the fabric, so your HDL cannot blink it; it is a software job.

Most header pins are unknown territory. Four are verified and safe to drive: JP5 pins 7, 9, 11 and 13. Driving an arbitrary pin that turns out to be an input, or tied elsewhere, can damage the board.

3

The toolchain and the build system

Programs with confusing names, some of them optional. Here is which one does what.

ToolWhat it does
VivadoXilinx's FPGA tool. Takes Verilog plus a wiring diagram and produces a bitstream: synthesis, placement, routing and timing analysis. The factory target only, and even there optional (--xsa).
VitisNot needed, whatever older write-ups say: the FSBL builds from AMD’s public embeddedsw sources.
gcc-arm-none-eabiBuilds code for the ARM cores with no operating system under them — the FSBL's situation.
Icarus VerilogA free simulator. Runs your Verilog as a program so you can check it in about a second.
BuildrootBuilds the root filesystem for the factory target only. The modern target uses Debian instead.
gcc-arm-linux-gnueabiThe cross-compiler for Linux and U‑Boot. The hard‑float gnueabihf one works too; prefer gnueabi for the factory target, because only it rebuilds the factory kernel byte for byte.
Podman (or Docker)Optional. Runs the build inside a container — a packaged Linux userspace that ignores whichever Linux you have. See below.
./devkitThis repo's wrapper. Drives all of the above in the right order, and refuses to do dangerous things.

The commands you will actually type

terminalShell
# run from: the repo root
./devkit doctor     # can this machine build? answers in a second, not at minute 40
./devkit setup --target factory     # fetch upstream source and apply this repo's patches
./devkit sim        # simulate the custom HDL          (~1 second)
./devkit build --target factory     # everything                       (45-90 min)
./devkit build --target factory --hdl-only   # just the FPGA part       (~20 min)
./devkit verify --target factory    # is the build sane? checks timing, compression, files
./devkit flash --target factory     # copy onto the running board over the network

The other target: --target modern

Everything above builds the factory firmware (firmware/): the vendor's 5.15 kernel and a Buildroot root filesystem held in RAM. The modern target (firmware-modern/) is ADI's Linux 6.12 and a full Debian 13 (armhf) system on the card's ext4 partition. Modern is the default: the same commands build it without --target factory (or with --target modern, which says so explicitly). DEVKIT_TARGET=factory in your environment makes factory the default again.

terminalShell
# run from: the repo root
./devkit setup --target modern     # about 0.6 GB, not 6.8: no vendor kernel, no Buildroot
./devkit container build --target modern --xsa "$(./firmware-modern/fetch-pinned-xsa.sh)"
./devkit verify --target modern    # reads BOOT.bin's parts back out and checks them
./devkit build --target modern --rootfs-only   # the Debian system, on the host (~10 min)
sudo ./devkit write-card --target modern /dev/sdX   # the Debian root cannot be flashed over the network
  • An XSA is the FPGA design in one file: the bitstream plus a description of the hardware around it. The modern target never runs Vivado, so --xsa is required. A release's XSA is that release's design, so the tool will not guess: fetch-pinned-xsa.sh downloads the XSA of the factory release named in firmware-modern/factory-xsa.pin (v1.7 today) and refuses it unless its sha256 matches the one written there.
  • BOOT.bin is the first file the chip reads at power-on: FSBL, bitstream and U-Boot (which loads Linux). Given the same XSA, the modern target's FSBL and bitstream are byte-for-byte the factory ones.
  • On Windows, a downloaded release needs no clone at all: double-click write-card.cmd in the folder holding its files. Windows cannot make the Linux partition, so the script builds it itself, as ext3 (ext2 plus a journal), which the kernel mounts with its ext4 driver. Step by step: writing the card on Windows.
  • A cross-compiler runs on your PC but produces code for the board's ARM chip. If your desktop has no ARM Linux one, container provides it. The Debian root is the exception: it builds in a container of its own, so run that step on the host, not inside container.

The number that shapes your whole workflow

Simulation takes one second; a build takes twenty minutes. At 1200:1, every question you can answer in the simulator, you answer there (lesson 10).

Four refusals worth knowing about

Every ./devkit step is a readable script; what it adds is order and refusal, because several build mistakes are silent.

It checks before the hour. doctor tests compilers, headers, disk and board in a second, instead of a missing gmp.h failing forty minutes in.

It refuses an unpatched source tree. The build stamps which patches were applied. Add one and forget to re-run setup, and it stops rather than building the old design.

It verifies a copy before swapping it in. flash backs the SD card up, checksums the new file on the board, then moves it into place, keeping the old one. A bad BOOT.bin means a board that will not boot, and recovery then needs a card reader.

It will not use DFU, and you never should. The USB recovery path has no BOOT.bin target, so it cannot deliver an FPGA change — and on this board it has bricked units.

The loop you will actually live in

The FPGA is built on the factory target only, so each setup, build, verify and flash below takes --target factory, as in the commands above.

WhenWhat you runCosts
Once, everdoctor → setup~5 min
Every edit to your Verilogsim~1 s
When the logic is right and you want it on the chipbuild --hdl-only → verify → flash~20 min
Changed the kernel or a driverflash --kernel-only~2 min
Before a release, from a clean clonebuild → verify → verify --board45–90 min

Which build, and which flash

Pick the smallest option that covers your change.

OptionUse it when
build --hdl-onlyFactory target only. You changed Verilog, the block design or filter coefficients. Reuses the kernel, u-boot and root filesystem, so needs a full build first.
build --preflight-onlyRun the guards without building.
flash (no option)The common case: BOOT.bin and uImage.
flash --boot-onlyAn FPGA change — the only remote route that can update the bitstream.
flash --kernel-onlyA driver or kernel change. Rebuild uImage on its own (about two minutes) and flash that one file; the old kernel stays on the card as uImage.prev.
flash --rootfs-onlyFactory target only: just uramdisk.image.gz. The modern target refuses it (and --all); write a card instead.
flash --allFactory target only: all five files. For a release, or when unsure what changed.
flash --no-rebootCopy and verify, but leave the old firmware running until you reboot.

The one that catches everybody: a changed design that does not get built

The build script reuses an existing Vivado project, and the project is where the block design and filter coefficients live. Change either, leave the project in place, and the build succeeds with the old ones — a bitstream without your change.

Delete the project directory before any change to the block design or a .coe file. verify prints the DSP count and which coefficient file is in use, so you can see the change landed.

Vivado in a container

Vivado 2022.2 (pinned: a different Vivado makes a different bitstream) supports Ubuntu 18.04, 20.04 and 22.04 and nothing newer; elsewhere neither it nor its installer starts. The container supplies Ubuntu 22.04 on your own kernel.

terminalShell
# run from: the repo root
./devkit container build-image      # once, ~3 min
./devkit container install ~/Downloads/Xilinx_Unified_2022.2_*.bin
./devkit container doctor --target factory
./devkit container setup --target factory
./devkit container build --target factory   # the same build, in the container

Vivado is not in the image (the filesystem a container starts from); your installation is bind-mounted in (a host directory made visible inside), keeping the image about a gigabyte instead of forty-five.

It is the same build, and that was checked

The container's BOOT.bin is byte-for-byte identical to the host build, and a clean clone gives the documented figures: 94 of 220 DSP48s, 12 521 LUTs, 0.215 ns of timing slack (with STOCK_RX_FILTER=1: 72 DSP48s, 11 896 LUTs, 0.205 ns). If your clean build disagrees, your toolchain differs.

3A

Reaching the board, and changing its address

The board answers on 192.168.2.1 over USB and asks for an address over Ethernet: from your router, or from your PC when a cable runs straight between them. How you change either depends on which rootfs you run.

Words used here

DHCP — a router handing out addresses automatically. Static address — one you fix yourself. Default route, or gateway — where a device sends traffic for destinations off its own network; without one it reaches only its neighbours. U-Boot — the small program that runs before Linux and loads it. QSPI flash — a flash chip soldered to the board, separate from the SD card. mDNS — a device announcing its own name on the local network, so fishball.local resolves with no server.

First: which userspace is on your card?

The two targets configure the network in completely different ways. Ask the board:

terminalShell
# run on the board
grep ^ID= /etc/os-release   # ID=debian  -> firmware-modern
                            # no such file -> Buildroot (firmware/)
firmware/ (Buildroot)firmware-modern/ (Debian)
who configures eth0S40network, from U-Boot variables/etc/network/interfaces, a fixed file
a static addressfw_setenv ipaddr_eth …edit /etc/network/interfaces
the hostnamefw_setenv hostname …hostnamectl set-hostname …
survives reflashing the card?yes — it is in QSPIno — it is a file on the rootfs
./devkit net dhcp|static|nameworksrefuses, and prints the equivalent

Read whichever half applies. The uEnv.txt trap applies to both.

On Debian: the file is the configuration

/etc/network/interfaces is read by ifupdown at boot, so editing it is the method:

terminalShell
# run on the board
$EDITOR /etc/network/interfaces
#   iface eth0 inet static
#       address 192.168.1.50
#       netmask 255.255.255.0
#       gateway 192.168.1.1        <- you get to include this, unlike Buildroot
systemctl restart networking      # no reboot needed

hostnamectl set-hostname lab-sdr  # avahi picks it up immediately
  • You can set a gateway and DNS, which the Buildroot static branch cannot.
  • It does not survive a fresh card. ./devkit write-card gives you the default back; put the change in firmware-modern/debian/overlay/etc/network/interfaces to have it on every card.
  • The MAC still comes from U-Boot. Keep the shipped pre-up ip link set dev $IFACE address "$(fw_printenv -n ethaddr)" line, or the random-MAC problem below comes back.

On Debian usb0 is brought up at 192.168.2.1 by fishball-usb-bind, which hard-codes that address, and there is no DHCP server on the USB link. Give your host end an address yourself:

terminalShell
# run on your HOST, once - replace enx… with the interface the board created
sudo ip addr add 192.168.2.10/24 dev enx001122334455
sudo ip link set enx001122334455 up
ssh root@192.168.2.1

On the modern firmware the login prints what the board runs: the build of its boot files and of its Debian root (in red if they differ), the FPGA design, its addresses, whether both transmitters are muted, and its temperatures. Read it every time; it is the quickest check there is.

Stop typing the password

The board ships with a published root password. One command replaces it with a key:

terminalShell
# run from: the repo root
./devkit ssh-key
ssh fishball

The key is for this board only, so the board never holds a credential for your other machines; the login test uses BatchMode, which cannot fall back to a password.

Do not turn the password off yet

On Debian that is one line, and a typo in it means a card reader: systemd-logind is masked on purpose (it saturates PID 1), so there is no systemctl reboot, and no console without the FTDI DEBUG cable. Prove key login works first.

On Buildroot: where the addresses actually live

Not on the SD card. They live in the U-Boot environment, a 128 KB block in QSPI flash. At every boot S40network reads it and generates the Linux network configuration.

terminalShell
# run on the board
cat /etc/fw_env.config
#   /dev/mtd1    0x0000    0x20000    0x20000
cat /proc/mtd | grep mtd1
#   mtd1: 00020000 00010000 "qspi-uboot-env"

So editing /etc/network/interfaces lasts until the next reboot. And the variables have defaults compiled into the script, so fw_printenv ipaddr answering "ipaddr" not defined does not mean no USB address — the script fell back to 192.168.2.1.

The switch that chooses DHCP or static

There is no "mode" setting: the script branches on whether ipaddr_eth has a value.

/etc/init.d/S40network, trimmedShell
if [ -n "$ETH_IPADDR" ]; then
        echo "iface eth0 inet static"   >> $IFAC
        echo "\taddress $ETH_IPADDR"    >> $IFAC
        echo "\tnetmask $ETH_NETMASK"   >> $IFAC
else
        echo "iface eth0 inet dhcp"     >> $IFAC
fi

So "back to DHCP" means deleting the variable, which fw_setenv with no value does:

terminalShell
# run on the board
fw_setenv ipaddr_eth 192.168.1.50    # a fixed address on your router's network
fw_setenv netmask_eth 255.255.255.0
fw_printenv ipaddr_eth netmask_eth   # read it back BEFORE rebooting
reboot

fw_setenv ipaddr_eth                 # no value = delete = back to DHCP
fw_setenv netmask_eth
reboot

The script also reads ipaddr (the board's USB address, default 192.168.2.1), ipaddr_host (the one address its USB DHCP server hands your PC, default 192.168.2.10), netmask, hostname (also the mDNS name) and ssid_wlan/pwd_wlan for a USB Wi-Fi dongle.

The file that looks like it works

The SD card's uEnv.txt is plain text and already contains lines like ipaddr=192.168.2.1. Editing them changes nothing in Linux. U-Boot loads uEnv.txt with env import into its environment in RAM; no saveenv runs in the SD boot path, so those values are gone before Linux starts, and Linux's fw_printenv reads /dev/mtd1, which was never touched.

Why this one fools everybody

"I edited uEnv.txt and it still works" passes either way: the script's built-in default is the same 192.168.2.1. To make a change stick from U-Boot, use its serial console — setenv ipaddr_eth …, saveenv, boot — which writes QSPI, like fw_setenv.

The route that needs no shell: config.txt

Over USB the board also appears as a small drive holding config.txt. Edit it, set reset = 1 under [ACTIONS], save, and eject the drive — the eject is the trigger. It writes the values through fw_setenv and leaves SUCCESS_ENV_UPDATE on the drive, or FAILED_INVALID_UBOOT_ENV if the write failed.

The section heading is wrong for this board

ipaddr_eth and netmask_eth sit under [USB_ETHERNET], but on the Fishball7020 they configure the RJ45 gigabit socket. The name is inherited from the ADALM-Pluto, whose only eth0 was a USB Ethernet dongle.

What static mode leaves out

The static branch writes no gateway line, and nothing writes /etc/resolv.conf. A statically addressed Buildroot board has no default route and no DNS. Measured at 192.168.129.200:

terminalShell
# run on the board
ip route
#   192.168.2.0/24     dev usb0 scope link  src 192.168.2.1
#   192.168.128.0/23   dev eth0 scope link  src 192.168.129.200
cat /etc/resolv.conf     # No such file or directory
ping -c1 8.8.8.8         # fails: no route

libiio on the same subnet still works; ntpd, git and name lookups fail silently. For a fixed address and internet, use a DHCP reservation on your router. Failing that, add what static mode omits to /mnt/jffs2/autorun.sh, the persistent partition that runs at every boot on Buildroot (nothing runs it on Debian).

Two different names, and why the router shows neither

A router listing the board as 26:ae:c6:de:ce:e0 shows two faults. Routers take the name from the DHCP request (option 12), and stock udhcpc sends none (mDNS is a separate name). And the MAC is not stable: the device tree has no local-mac-address, so the driver improvises:

dmesgKernel
macb e000b000.ethernet: invalid hw address, using random

What a random MAC per boot actually costs you

Every reboot the router sees a new device, so no DHCP reservation is possible. Two consecutive boots took 192.168.129.139 then .140 — easy to misread as "DHCP working".

Two lines in the stanza S40network generates fix both: busybox's ifupdown turns hostname into udhcpc -x hostname:, and hwaddress into an ip link set addr before the interface comes up.

/etc/network/interfacesGenerated
auto eth0
iface eth0 inet dhcp
        hostname fishball
        hwaddress ether 00:0a:35:00:01:22

The address is U-Boot's own ethaddr. The devkit ships this as firmware/patches/0013; 0014 makes the default hostname fishball, so the board answers to fishball.local.

The one thing that cannot be checked from here

Whether every unit got a different ethaddr is unknown. If two boards on one network both go quiet, fw_setenv ethaddr <mac> on one of them.

Day to day the devkit wraps all this. It knows which rootfs it is talking to, so on Debian dhcp, static and name refuse and print the equivalent:

terminalShell
# run from: the repo root
./devkit net                 # what address did it get, and how?
./devkit net dhcp            # ask the router          (the default)
./devkit net static 192.168.1.50
./devkit net name lab-sdr    # answer to lab-sdr.local instead
./devkit net find            # locate it without knowing the address

Each reads the setting back before rebooting, then finds the board again.

A cable straight to your PC

With no router there is no DHCP server, so make your PC one. NetworkManager does it in shared mode: it gives the port an address, runs a small DHCP and DNS server on it, and routes the board to the internet through the PC. The board needs no change; it asks for DHCP as always.

terminalShell
# run from: your HOST; IFACE is the port the cable is in (ip -br link)
nmcli con add type ethernet con-name fishball-eth ifname IFACE \
      ipv4.method shared ipv4.addresses 10.42.0.1/24 ipv6.method link-local
nmcli con up fishball-eth
# a firewall that denies incoming must let the board's DHCP request in, on that port only
sudo ufw allow in on IFACE to any port 67 proto udp

The board then takes an address from 10.42.0.0/24 and fishball.local finds it. If USB is plugged in too, the name answers on both links; take the PC's USB network down to keep everything on the cable.

On v2.3 and earlier, an address added by hand disappears within a minute

On Debian eth0 is set to DHCP, and on a cable where nothing answers, dhclient keeps retrying. Each time it gives up it removes every IPv4 address on eth0, including one you just added with ip addr add. A connection that worked a moment ago then hangs. Serve DHCP from the PC, or stop the client first with kill $(cat /run/dhclient.eth0.pid).

Firmware built after v2.3 uses dhcpcd instead. It leaves an address you added alone, and it follows the cable: move the cable between your router and your PC while the board runs, and it has a new address about ten seconds later. With dhclient, reboot the board after moving the cable.

A cable is not much faster than Wi-Fi here. On a direct gigabit link the board sustained 12 MS/s of 16-bit samples through iiod (11 over Wi-Fi) and 20 MS/s of 8-bit ones (the same as over Wi-Fi), and plain TCP reached only about 600–700 Mb/s, with one ARM core at 100% handling the network. The board's CPU is the limit, not the cable.

Finding the board again

terminalShell
# run from: your HOST
iio_info -s
#   1: 192.168.129.200 (FISH Ball PlutoSDR Rev.A (Z7020-AD9361)),
#      serial=b8f4c99de8525565d3f4fe3c917ad834 [ip:fishball.local]

avahi-resolve -n fishball.local
#   fishball.local	192.168.129.200

iio_info -s gives address, model, serial, and proof the radio service is up. Use ip:fishball.local as the libiio URI rather than an address (fw_setenv hostname pluto restores pluto.local).

Why you cannot really lock yourself out (Buildroot)

ipaddr_eth touches only eth0, so a USB cable and ssh root@192.168.2.1 is always the way back. After that: config.txt on the USB drive; the serial console at 115200 baud; and the U-Boot prompt, reached by interrupting the three-second boot delay, with setenv and saveenv. Reflashing the SD card does not help — the addresses are in QSPI.

The full version, including no-reboot commands and other ways to find a board, is changing the board's IP address.

Verilog from nothing

4

Your first module

You need about a fifth of Verilog, and this lesson is most of it.

A module is the unit of Verilog: a box with wires going in and out, and a description of what is inside.

counter.vVerilog
// Everything after two slashes is a comment.
module counter (
  input  wire        clk,     // one bit, coming in
  input  wire        rst,     // one bit, coming in
  output reg  [31:0] count    // 32 bits, going out
);

  always @(posedge clk) begin
    if (rst)
      count <= 32'd0;
    else
      count <= count + 32'd1;
  end

endmodule

Reading it line by line

  • module counter ( … ); — declares the box and lists its wires; endmodule closes it.
  • input / output — which way each wire points.
  • [31:0] — a bundle of 32 wires, 31 down to 0, bit 0 least significant: a vector.
  • always @(posedge clk) — "whenever clk goes from low to high, do the following". posedge is the rising edge.
  • <= — an assignment. Lesson 6 explains why it is this arrow and not =.
  • 32'd0 — a literal: 32 bits wide, d for decimal, value 0. You will also see 'h (hex) and 'b (binary).

Read it as hardware, not instructions: a 32-bit register count, with an adder computing count + 1 and a selector choosing that or zero by rst; on every rising edge the register captures the selector's output. About 32 flip-flops and a handful of LUTs, existing all at once.

wire versus reg

wire
A connection. Something else drives it continuously. Use for anything you assign with assign, and for module inputs.
reg
Anything you assign inside an always block. Misleadingly named: it becomes a flip-flop only if assigned on a clock edge; in a combinational block it is just a wire.
5

Clocks, registers and reset

Why digital hardware has a heartbeat, and what it is for.

A clock alternates high and low forever at a fixed rate. It carries no data; its job is to say now.

Logic takes time to settle — for a few nanoseconds an adder's output is meaningless. The clock divides time into slices: within each the logic settles, and at the edge every flip-flop captures the settled value at once.

This is what "timing" means

Timing analysis is one question: does every signal settle between one clock edge and the next? If the longest path takes longer than a period, the flip-flop at its end captures a half-finished value. Vivado reports the margin as slack (lesson 21). A pipeline register fixes it by cutting one long path into two shorter ones.

Reset

At power-on flip-flops hold arbitrary values; reset forces them to known ones.

Reset only what needs it: the reset must reach every flip-flop that uses it within one clock period, so over-resetting costs fabric and timing. A counter needs reset; a pipeline register overwritten within two cycles does not.

The clock on this board

The datapath clock, l_clk, is recovered from the AD9361's own data clock. It is not a fixed frequency: it scales with the sample rate, which software can change underneath your logic. Never assume a number of clock cycles per second.

6

The two assignments, and why it matters

The commonest cause of designs that simulate correctly and fail in hardware.

The rule, no exceptions

Use non-blocking <= inside clocked blocks (always @(posedge clk)).
Use blocking = inside combinational blocks (always @(*)).

Check yourself: which of these makes three flip-flops, and which makes one?

b <= a; c <= b; makes three — a, b and c each get a register, and c receives the old b, so a value takes two clock ticks to travel the chain.

b = a; c = b; makes one: the assignments happen in order, so c receives the new value and the intermediate register collapses away.

Why the rule exists

In a shift register all flip-flops capture simultaneously, so c gets the old b.

a shift register, correctVerilog
always @(posedge clk) begin
  b <= a;
  c <= b;      // gets the OLD b - three separate flip-flops
end
the same thing, wrongVerilog
always @(posedge clk) begin
  b = a;
  c = b;       // gets the NEW b - collapses to a single flip-flop
end

Non-blocking assignments read every right-hand side first, then update all left-hand sides together — exactly what flip-flops do on an edge. Blocking assignments run in written order: right for a chain of gates, wrong for registers. Mix them and simulation and synthesis disagree: the testbench passes and the board misbehaves.

7

Combinational logic, and the latch trap

Logic with no memory: outputs follow inputs continuously.

two formsVerilog
// continuous assignment - permanent wiring
assign sum   = a + b;
assign isbig = (a > b);          // a comparator
assign pick  = sel ? a : b;      // a multiplexer ("mux")

// block form, for anything needing if/case
always @(*) begin
  case (sel)
    2'b00:   out = a;
    2'b01:   out = b;
    2'b10:   out = c;
    default: out = 16'd0;    // ALWAYS write a default
  endcase
end

@(*) means "re-evaluate whenever any input changes", as gates do.

Inferred latches

If a combinational block fails to assign a signal on some path, the synthesiser must make the signal remember its previous value — so it builds a latch, a memory element that is not clocked.

Latches are almost never intended: hard to time, and they behave differently in simulation and hardware. Write a default in every case and an else on every if — or assign every output a safe value at the top of the block.

8

Numbers: width, signedness, overflow

Radio samples are signed and awkwardly sized. Verilog will silently do the wrong thing if you let it.

Width is not checked

Assign a 16-bit expression to a 12-bit target and Verilog silently discards the top four bits. This board moves constantly between 12-bit samples and 16-bit words, so be explicit about widths.

Signed means saying so

IQ samples are two's complement signed numbers: the top bit means negative. A plain reg [15:0] is unsigned as far as Verilog is concerned, so a > b gives wrong answers whenever negatives are involved — and half your samples are negative.

signed arithmeticVerilog
wire signed [11:0] adc;        // 12 bits from the converter
wire signed [15:0] wide;

// widening a signed number means REPLICATING the sign bit,
// not padding with zeros
assign wide = {{4{adc[11]}}, adc};

// {a, b}   concatenates
// {4{x}}   repeats x four times

Overflow, and what to do about it

Adding two 16-bit numbers needs 17 bits; multiplying needs 32. Kept in 16 bits, a large sum wraps around — a big positive becomes a big negative: a violent click and broad spectral splatter. Either grow the width, or saturate — clamp at the maximum. Saturation is usually right for signals: a clipped peak does far less damage than an inverted one.

The sizes on this board

Receive
The ADC gives 12 bits, signed, sign-extended into a 16-bit container. Full scale is ±2047, not ±32767.
Transmit
The DAC takes the top 12 bits of your 16-bit word and discards the bottom four. Scale your transmit samples to the full 16 bits — scaling them to ±2047 transmits 24 dB too quietly.
9

Fixed point: the arithmetic the fabric actually does

There is no floating point in the fabric: every DSP block manipulates integers pretending to be fractions.

What "fixed point" means

A floating-point number carries its own scale (an exponent), which costs hardware. The fabric uses plain integers and you remember where the binary point is; it never moves, hence fixed point.

The usual notation is Qm.n: m integer bits, n fractional bits, plus a sign bit. A signed 16-bit word holding values between −1 and +1 is Q0.15: one sign bit and fifteen fractional bits.

FormatRangeStepUsed for
Q0.15 (16-bit)−1 … +0.999971/32768Normalised samples, filter coefficients
Q1.14−2 … +1.999941/16384After a gain of up to 2
Q15.16 (32-bit)−32768 … +327671/65536Accumulators

The number that governs everything: 6.02N + 1.76

An ideal N-bit converter has a best possible signal-to-noise ratio of

the fundamental limitdB
SNR = 6.02 × N + 1.76   dB

Each extra bit buys about 6 dB. For the AD9361's 12-bit converters that is 74 dB — the ceiling.

This is where the decimation gain comes from

That 74 dB is spread across the whole sampled bandwidth. Filter down to a fraction of it and you keep the signal but discard most of the noise — process gain, 10·log₁₀(D) (lesson 27). Divide by 6.02 to get "extra bits": decimating by 307 gives 24.9 dB, 4.1 bits, taking a 12-bit converter to about 16 bits in that channel.

Scaling: the mistake that costs 40 dB

Fixed point has no automatic gain: use a small part of the range and you get a small part of the dynamic range, permanently.

Two ways to under-scale on this board

On transmit. The DAC takes bits [15:4]. Scale to ±2047, as if they were receive samples, and you use only its bottom bits. Measured on this hardware: amplitude 32767 gives 24 dB more output than 2047 — the factor of 16 the alignment predicts. Scale to ±32767.

In your own arithmetic. A signal at a tenth of full scale through a filter chain loses about 20 dB you never get back.

Growth

A 129-tap filter accumulating products needs even more width than a multiply. Grow the width and round back down at the end, or saturate (lesson 8) — never let it wrap silently, which is what Verilog does by default.

saturating addVerilog
wire signed [16:0] sum = a + b;          // 17 bits: cannot overflow
wire signed [15:0] out =
  (sum >  17'sd32767) ?  16'sd32767 :      // clamp high
  (sum < -17'sd32768) ? -16'sd32768 :      // clamp low
                        sum[15:0];

Rounding versus truncation

Truncating low bits always biases downwards, which over a long filter becomes a DC offset. Rounding — add half a least-significant bit before shifting — costs one adder and removes it.

Dither: deliberately adding noise to get a better answer

Patterned rounding error lands on discrete frequencies as spurs. A tiny random offset before rounding (dither) breaks the pattern: the floor rises slightly, the worst spur falls.

A measurement trap I walked into on this board

Quantisation error is noise-like only if uncorrelated with the signal. A tone at a simple fraction of the sample rate, such as fs/8, concentrates the error into harmonics and makes spur-free dynamic range look far worse than the hardware deserves. A full-rate sweep here at exactly fs/8 reported SFDR of 42–48 dB — pessimistic, because of the tone. Use an awkward frequency, such as a prime number of hertz.

Check yourself: your filter output is 32 bits wide and the DAC wants 16. Which 16 do you take?

Not the bottom 16 (the fractional part: you would keep the noise and lose the signal), and not blindly the top 16. Work out where the binary point sits after the multiply-accumulate, choose the window covering your signal range with headroom, round, and saturate. Then simulate with a full-scale input, the case that overflows.

10

Testbenches, and why you will not skip them

One second against twenty minutes.

A testbench is a Verilog module with no ports that drives your design's inputs, checks its outputs and complains if they are wrong. It exists only in the simulator, so it may use constructs hardware cannot.

tb_counter.vVerilog
module tb;
  reg clk = 0, rst = 1;
  wire [31:0] count;

  counter dut (.clk(clk), .rst(rst), .count(count));   // dut = design under test

  always #5 clk = ~clk;      // flip every 5 time units -> a clock

  initial begin
    $dumpfile("tb.vcd"); $dumpvars(0, tb);   // record every signal

    repeat (2) @(posedge clk);
    rst = 0;
    repeat (10) @(posedge clk);

    if (count !== 32'd10) begin
      $display("FAIL: count=%0d, expected 10", count);
      $fatal;
    end
    $display("PASS");
    $finish;
  end
endmodule
terminalShell
iverilog -o tb.out tb_counter.v counter.v && vvp tb.out
gtkwave tb.vcd        # when the numbers alone do not explain it

Simulator vocabulary

#5
Wait 5 simulation time units. Meaningless in synthesis; essential here.
initial
A block that runs once at the start. Testbench-only.
!==
Compares including the unknown state x, so it catches uninitialised signals that != would pass.
VCD
Value Change Dump: every signal over time, viewable as waveforms in GTKWave.

The mutation check

A test that always passes is worse than none. This repo guards against that:

terminalShell
./devkit sim --mutate   # deliberately corrupt the design; the test MUST now fail

If your test still passes with a broken design, it is not testing. Write the testbench before the module; then the first run means something.

The radio's datapath

11

What an IQ sample actually is

Every number on this board comes in pairs. Here is why.

Sample a radio wave and get 0.5: is it rising or falling? One number gives amplitude at an instant and nothing about the phase — where much of the information lives.

So SDRs take two measurements at each instant, from the same signal, using reference oscillators a quarter-cycle (90°) apart:

I
In-phase — measured against a cosine reference.
Q
Quadrature — measured against a sine reference, 90° later.

As a point on a plane — I across, Q up — the distance from the origin is the amplitude and the angle is the phase. A steady tone traces a circle; its speed of rotation is its frequency offset from the tuned centre.

Why this makes negative frequency meaningful

With I and Q a signal 1 MHz above the tuned frequency rotates one way and one 1 MHz below the other; a single real stream cannot tell them apart. That is why a spectrum here runs from negative to positive frequency either side of centre.

How it is carried here

Each sample is two signed 16-bit integers (12-bit values sign-extended on receive), interleaved I, Q, I, Q: four bytes per sample, so 5 MSPS is 20 MB/s in each direction.

Two more terms you will meet

Complex baseband
This I/Q representation, centred on zero: the carrier removed, the signal's shape around it left.
Mixing
Multiplying by an oscillator to shift a signal in frequency — from the antenna's gigahertz down to baseband, or any shift you do in the fabric (lesson 28).
12

Sample rate, Nyquist and aliasing

The theory you cannot skip: violating it produces signals that are not there.

The sample rate is how many samples per second you take. This board goes from 2.083 to 61.44 million samples per second (MSPS).

The Nyquist theorem, for complex I/Q sampling: rate f faithfully represents a bandwidth f, centred on the tuned frequency, from −f/2 to +f/2. At 5 MSPS you see 2.5 MHz either side of centre. (A radio sampling one real stream gets only half that — the form most textbooks state first.)

Aliasing: why a signal can appear where it is not

Sampling only glances at the signal at evenly spaced instants; nothing between is recorded. So two different sine waves can pass through exactly the same points:

solid: 1 cycle dashed: 7 cycles dots = the only moments you measure
Both waves hit every dot, so they are the same list of numbers; no algorithm can separate them.

A signal too fast for your sample rate does not go missing or announce itself: it is recorded as a slower one, indistinguishable from a genuine signal there. This is aliasing — the same effect that makes film wagon wheels turn backwards.

Where a given signal lands

Add or subtract whole multiples of the sample rate until the frequency falls inside the window. At 5 MSPS (window −2.5 to +2.5 MHz):

A real signal at…Arithmetic…appears at
+1.0 MHzalready inside+1.0 MHz — correct
+3.0 MHz3 − 5−2.0 MHz
+7.0 MHz7 − 5+2.0 MHz
−4.0 MHz−4 + 5+1.0 MHz

Try it — where does a signal actually land?

Check yourself: at 20 MSPS, where does a signal 12 MHz above centre appear?

The window is ±10 MHz; 12 − 20 = −8 MHz, 8 MHz below centre. Try it in the calculator, then try 28 MHz, which lands in the same place.

The only real defence: filter before you sample

Once sampled, the alias is the data, so the fix must happen while the signal is still analogue. That is rf_bandwidth: a filter inside the AD9361, ahead of its converters.

terminalShell
# run on your HOST - set the rate, then match the filter to it
iio_attr -u ip:192.168.2.1 -i -c ad9361-phy voltage0 sampling_frequency 5000000
iio_attr -u ip:192.168.2.1 -i -c ad9361-phy voltage0 rf_bandwidth        4000000

Set it slightly narrower than the sample rate — commonly 0.75 × the rate, derived below. Much wider lets in signals that can only arrive as aliases; much narrower throws away spectrum you paid to sample.

It wraps, it does not mirror — and that catches people out

With real sampling an alias reflects about the band edge. With complex I/Q sampling the band is a circle: a tone pushed off the top reappears at the bottom.

At 1 MSPS, with the window running −0.5 to +0.5 MHz:

Tone atComplex sampling (wrap)Real sampling (mirror)
+0.90 MHz−0.100+0.100
+1.50 MHz−0.500+0.500
−1.20 MHz−0.200+0.200

Hence the rule above is a modulo, not a reflection.

Decimation moves Nyquist, and things that were safe stop being safe

When you decimate — keep one sample in every D (lesson 27) — there are two Nyquist limits, and the smaller governs.

the only rule that matters after decimating
original rate   fs          window  +/- fs/2
decimate by D   fs / D      window  +/- fs / (2D)     <-- this one

a signal safely inside the first window can be well outside the second

Nothing warns you: a signal legitimately inside the band when sampled folds when you decimate, and becomes a peak that was never on the air.

Setting the cutoff to Nyquist is not enough, and here is the measurement

“Filter at the new Nyquist” is wrong: a real filter has a transition band. 16 MSPS decimated by 8 (2 MSPS out, Nyquist 1 MHz), 193-tap Hamming low-pass cut off at exactly 1 MHz:

A tone hereis attenuated byfolds to
1.00 MHz−6.0 dB−1.00
1.05 MHz−13.8 dB−0.95
1.10 MHz−27.9 dB−0.90
1.20 MHz−60.0 dB−0.80

A signal at 1.05 MHz arrives only 13.8 dB down. The correct rule: choose the widest frequency you will keep, the passband edge fp. Anything at or above fs/D − fp folds into it, so the stopband must begin there:

anti-alias filter, after decimating by D
passband edge   fp                    what you keep
stopband edge   (fs / D) - fp         where rejection must already be reached
stopband depth  >= your dynamic range  so folded energy lands under the noise

Nyquist, fs/(2D), sits in the MIDDLE of that transition - not at its start.

Keep 0.8 MHz of a 2 MSPS output and the stopband starts at 2 − 0.8 = 1.2 MHz: a filter 0.8 × the Nyquist width, which is where the “0.75 to 0.8” rules of thumb come from.

Try it — will it alias after decimation, and is your filter wide enough to matter?

How to catch an alias in the field

Suspect a peak? Change the sample rate and look again. A genuine signal stays put; an alias jumps or vanishes.

What this costs you in practice

At 61.44 MSPS each direction is 245 MB/s. Measured on this board, capture alone runs at the full 61.44 MSPS over gigabit Ethernet with a handful of dropped samples per two million. The walls are elsewhere: simultaneous transmit and receive streaming starve above about 5 MSPS, and a modest CPU cannot do much with 245 MB/s in real time.

Transmit is fragile earlier than you would guess. Fed from the host at only 3.072 MSPS (12 MB/s), it took one starve mute inside ten seconds; with the client on the board, none. What matters is the play-out time each buffer holds: 256 K samples at 3.072 MSPS is 85 ms, so a longer stall empties the DAC, and 250 ms of empty mutes the transmitter. Larger buffers buy slack.

Streaming without a break is set by the board's CPU, not the network: 12 MS/s at 16 bits and 20 MS/s at 8 bits per receiver, measured on a direct gigabit cable, which is barely more than over Wi-Fi. Anything faster has to be captured on the board first (lesson 3A has the numbers).

If you only care about a 200 kHz signal, why sample 56 MHz at all? See lesson 27.

13

The block design: the map, and what it quietly assumes

You are joining a design that already works, so the useful question is where you can cut in, and what will bite you.

AD9361 RX1 / RX2 axi_ad9361 LVDS · 2R2T 0x7902_0000 cpack util_cpack2 adc_dma → DDR → Linux dac_dma CYCLIC = 1 tx_upack util_upack2 axi_ad9361 DAC side AD9361 TX1 / TX2 everything between the converters runs on l_clk receive ▲ transmit ▼
The stock design. Your logic goes between axi_ad9361 and cpack on receive, or between tx_upack and axi_ad9361 on transmit.

It is a script, not a drawing

Vivado shows the block design as a diagram, but here it is generated, every build, by firmware/src/hdl/projects/pluto/system_bd.tcl. So your change is a reviewable diff; clicking in the diagram edits a project that will be regenerated; and the project is a treacherous cache — the build reuses an existing project rather than re-running the script (lesson 21).

How software reaches into the fabric at all

Through memory-mapped I/O. Most of the processor's addresses are ordinary memory (the DDR chips), but some are wired to hardware: writing one changes a register in a fabric block, and reading one asks the hardware what it currently is. Nothing in the number says which kind it is; the address map and the device tree tell you. The block design's job is to decide which addresses land on which blocks.

Reading the addresses

The notation

0x
A hexadecimal number — base 16, digits 0–9 then A–F. Each hex digit is exactly four bits, so digits line up with address wires.
_
A separator for human eyes: 0x7C40_0000 is 0x7C400000.
Base address
Where a block's contiguous range of addresses starts.
Offset
How far into that range a register sits: offset 0xBC from base 0x7902_4000 is 0x7902_40BC.
IRQ
Interrupt request — a wire to the processor meaning "something happened", so a driver need not keep polling. ps-13 is the processor's fabric interrupt input 13.

This board's map

Base addressBlock in the fabricLinux calls itInterrupt
0x4160_0000axi_iic_main — an I²C bus master axi_iicps-15
0x7902_0000axi_ad9361 — the radio interface cf-ad9361-lpc (receive)—
0x7902_4000the same block, 0x4000 further in cf-ad9361-dds-core-lpc (transmit)—
0x7C40_0000receive DMA engine dma@7c400000ps-13
0x7C42_0000transmit DMA engine dma@7c420000ps-12
0x7C43_0000axi_spi — an SPI bus master axi_quad_spips-11

One physical block appears to Linux as two devices: receive registers at the base, transmit registers 0x4000 further in — hence cf-ad9361-lpc and cf-ad9361-dds-core-lpc. The DMAs have interrupts to announce "a buffer is finished"; the radio interface only answers questions.

A register poke is a base plus an offset

terminalShell
iio_attr -u ip:192.168.2.1 -D cf-ad9361-dds-core-lpc direct_reg_access 0xBC

The device name selects base 0x7902_4000, so this reads 0x7902_40BC — the register whose bit 1 switches on the sample-locked GPIO feature.

Why the map is a contract, not a note

Nothing discovers any of this. Linux is told, by the device tree — zynq-pluto-sdr-fishball.dts — which lists every block, its address, interrupt and settings. So each address is written in two independent places, the block design and the device tree, and nothing checks that they agree.

What a disagreement looks like

Move a block in system_bd.tcl and forget the device tree, and the driver reads an address where nothing lives. That raises no error — it returns zeros or junk — so the symptom is a device that almost works, or is missing from iio_info, with a silent boot log. Change both files in the same commit.

Three things that are not where you would guess

The radio is not controlled through the SPI block sitting right next to it

The axi_spi master is not on the AD9361's control path. The radio is configured over the processor's own SPI0, routed through EMIO to separate balls (R17, V18, P16, V17).

So why is axi_spi there at all? Check its chip select.

The design is inherited from ADI's reference family, where such masters drive real peripherals. Here, in system_top.v:

firmware/src/hdl/projects/pluto/system_top.vVerilog
.spi_clk_o (pl_spi_clk_o),   // -> ball L14
.spi_sdo_o (pl_spi_mosi),    // -> ball N16
.spi_sdi_i (pl_spi_miso),    // <- ball N15
.spi_csn_i (1'b1),           // tied inactive
.spi_csn_o (),               // <-- THE CHIP SELECT GOES NOWHERE

Clock and data reach real pins, but the chip-select output is unconnected, and without a chip select a SPI master cannot address anything. As built, it is leftovers.

What that means if you want to use it

Its driver (axi_quad_spi), address and interrupt are in place; to use it, bring the chip select out: connect spi_csn_o to a port, pin it in the constraints file, and add the device to the device tree. The I²C master is ready as is — iic_scl and iic_sda reach balls M14 and M15 with pull-ups, and I²C addresses devices in the protocol.

Twelve of sixteen interrupt lines are free

An xlconcat gathers sixteen interrupt lines into the processor's IRQ_F2P port; only four are used. If your logic needs to signal an event, the wiring is there.

Four of the twenty-two EMIO GPIOs are this repository's

The processor exports 22 general-purpose pins into the fabric: eighteen are ADI's, four were added for the sample-locked header pins. The cheapest way to pass one bit between processor and fabric — no AXI block, no address, no device-tree node.

What not to touch, and why

ThingWhat happens if you do
The DDR timing parametersTuned for this PCB. Change them and it will not boot.
axi_ad9361/IDThe Linux driver gates its capture setup on ID == 0. Set it to anything else and capture silently stops working.
CMOS_OR_LVDS_NThe board is physically wired for LVDS.
An AXI base address, aloneThe device tree still points at the old one.
The filters' ÷8 / ×8 rateThe driver offers exactly {1, 8}. A ÷4 filter would build and be unreachable from software.

Read the real thing

Open firmware/src/hdl/projects/pluto/system_bd.tcl and search for ad_connect: every wire in the diagram is one of those lines, a few dozen in all.

14

Clocks, valid strobes, and the 2R2T trap

Three facts about this board that otherwise cost a day each.

First: what a clock domain is

A clock domain is the set of flip-flops driven by one clock. Inside one domain signals move in lockstep; trouble starts when a signal crosses between unrelated clocks, whose edges drift past each other (lesson 22). This board has three:

ClockWhere it comes fromRateWhat it drives
l_clkRecovered from the AD9361's own data clock Scales with sample rate The datapath — filters, packers, the fabric side of both DMAs, and anything you add. Your clock.
sys_cpu_clkFCLK_CLK0 from the processor 100 MHz, fixed The control-register bus, and the memory side of both DMAs.
sys_200m_clkFCLK_CLK1 from the processor 200 MHz, fixed Only a timing reference for the link to the radio chip. Not for your logic.

Two terms from that table

Recovered clock
The AD9361 sends a clock alongside its data; the fabric runs on it rather than generating its own, so it changes with the sample rate.
LVDS
Low-Voltage Differential Signalling — the chip-to-fabric link's electrical standard: each bit is the difference between two wires. Fast, noise-resistant, and few wires carrying many bits in turn.

l_clk is not a fixed frequency

Around 4 MHz at the AD9361's slowest rate; 61.44 MHz at 30.72 MSPS. No "wait 1000 cycles for one millisecond": design for the top end, and count events, not time.

Second: what a strobe is, and why a clock is not one

A strobe is a brief pulse that says "now", as distinct from a level:

A levelA strobe
Says"this is the state of things""this event is happening, right now"
ShapeStays high or low for as long as it appliesHigh for exactly one clock cycle, then low again
Example hereflag — the bit-map feature is on fifo_wr_en — a sample word is being written this cycle
You use it toChoose behaviourTrigger an action, once

So why not just use the clock?

Because the clock always ticks, and the data is not always new. Here a tick may carry nothing you want because:

  • The channels take turns. In 2R2T, half the ticks belong to the other channel.
  • A filter is decimating. With the ÷8 filter on, seven ticks in eight produce no output.
  • The data ran out. On transmit, the hardware substitutes zeros.

Between samples the wires hold the last value, so logic acting on every edge processes the same sample repeatedly. Average 1000 samples on every edge in 2R2T and you add each sample twice, averaging over half the intended window — a plausible, wrong number, which is what strobe bugs produce.

the pattern, every timeVerilog
always @(posedge clk) begin      // clk decides WHEN you may act
  if (valid_in)                  // the strobe decides WHETHER you should
    accumulator <= accumulator + sample_in;
end

The clock grants permission to act; the strobe supplies the reason. Every block in the datapath works this way, which is why they chain.

The strobes you will meet, and what each is announcing

Valid
"The data on these wires is real this cycle." The default meaning of "strobe".
Write enable
"Store this, now." cpack/fifo_wr_en is one.
Read enable
"Give me the next one." A request, not the data arriving.
Underflow
"I had nothing to give, so this is a substitute."
Check yourself: why does a strobe last exactly one cycle, rather than staying high while data is good?

It marks an event, and events are counted: high for three cycles, downstream logic acts three times on one sample. A lasting condition is a level, like flag; mixing the two gives counts off by a factor.

Third: 2R2T, where clock edges stop meaning samples

This board runs the AD9361 with two receivers and two transmitters — "2R2T" — over one physical link, so the channels are time-multiplexed: one clock period carries a channel-0 sample, the next a channel-1 sample, and so on.

l_clkchan 0 validchan 1 validcpack strobech0ch1ch0ch1ch0ch1ch0ch1eight l_clk edges · four channel-0 samples · four channel-1 samples
Each channel's samples arrive on alternate periods; the cpack strobe follows channel 0.

A clock edge is not a sample: there are twice as many edges as samples of one channel.

What goes wrong, concretely

A counter incremented every edge, its bottom bit on a header pin as a scope trigger, toggles at twice the intended rate; every pattern comes out doubled, and still looks plausible. Gate on the valid strobe:

the 2R2T ruleVerilog
if (valid_in) count <= count + 1'b1;   // counts SAMPLES
// count <= count + 1'b1;              // counts CLOCK EDGES - twice as fast
Check yourself: at 15 MSPS, how fast does l_clk run, and how many edges per channel-0 sample?

30 MHz, twice the sample rate, so two edges per channel-0 sample: one carrying channel 0, the next channel 1.

The strobes on this board

SignalWhat it means
cpack/fifo_wr_enReceive. A sample word is being written towards memory — your receive tap point.
tx_upack/fifo_rd_validTransmit. A real sample is standing at the output this cycle.
tx_upack/fifo_rd_underflowTransmit. Zeros are being substituted because the data ran out.
tx_upack/fifo_rd_enThe request for a sample. Not the arrival. See the trap below.

A request is not an arrival

The packer registers its output, so the word requested by fifo_rd_en appears the following cycle. Capture on fifo_rd_en and you latch the previous sample, silently one behind. Use fifo_rd_valid | fifo_rd_underflow: it goes high with the data, covering real samples and substituted zeros.

15

The packers, and the filter ADI gives only channel 0

Two blocks sit between the radio and memory. One is wired lopsidedly, and that will quietly ruin your second receiver if nobody warns you.

Why anything sits there at all

The radio produces one stream per receiver; memory wants one wide, regular stream. The packers reconcile the two.

What the radio givesWhat memory wants
ShapeSeparate streams, one per channelOne combined stream
Width16 bits at a time64 bits at a time
TimingWhenever a sample is readyIn bursts, when the bus is free
ChannelsOne or two, your choice at runtimeDoes not know channels exist

The receive one is cpack ("channel pack"); the transmit one is tx_upack ("unpack"), and does the reverse.

Three words used below

FIFO
First In, First Out — a small on-chip queue; one side pushes at its own pace, the other pulls at another.
Multiplexer
Mux: several inputs, one output, a control signal choosing which gets through.
Hierarchy
In a block design, a box that contains other boxes — a folder.

What "packing" actually does

With one receiver enabled, each 64-bit word holds four 16-bit samples of it; with two, two samples of each, interleaved. Software picks the channels when it opens a buffer, the packer rearranges on the fly, and memory is densely filled. One channel gives I, Q, I, Q…; two give I0, Q0, I1, Q1… — no header, no channel tag.

Then how does your program know which sample is which?

By something it already set. Before opening a buffer an application enables channels, and the hardware packs them in a fixed order: their scan index, ascending.

On this board's receive core the four scan indices are:

Scan indexlibiio nameWhat it carries
0voltage0Receiver 1, I
1voltage1Receiver 1, Q
2voltage2Receiver 2, I
3voltage3Receiver 2, Q
You enableYou receive, repeatingBytes per sample instant
voltage0, voltage1I1 Q1 I1 Q1 …4
voltage2, voltage3I2 Q2 I2 Q2 …4
all fourI1 Q1 I2 Q2 I1 Q1 I2 Q2 …8

You have been relying on this all along

The channel names at the end of every capture command are the mask:

terminalShell
# receiver 1 only - 4 bytes per sample instant
iio_readdev -u ip:192.168.2.1 -b 65536 -s 1048576 cf-ad9361-lpc voltage0 voltage1

# both receivers - 8 bytes per sample instant
iio_readdev -u ip:192.168.2.1 -b 65536 -s 1048576 cf-ad9361-lpc voltage0 voltage1 voltage2 voltage3

Enable order does not change pack order

Ask for voltage3 before voltage0 and the data still arrives in scan index order. Do not infer the layout from your argument order; ask the library: iio_buffer_first() gives a channel's first sample in the buffer and iio_buffer_step() the distance to its next one, so your de-interleaving stays correct if the mask changes.

Getting the mask wrong is silent

Enable four channels but de-interleave as though there were two, and every other sample pair lands in the wrong stream — no error, just signals that look like noise.

At the wire-protocol level the mask is a fixed-width hex field: 00000003 enables channels 0 and 1, 0000000F all four. Writing 3 instead of 00000003 fails with -22 EINVAL and no explanation.

Check yourself: you enable only channel 1. What does a 64-bit word contain?

Four 16-bit samples of channel 1 — two complete I/Q pairs — and nothing of channel 0. A disabled channel costs no memory and no bandwidth.

The strobe that moves each word, and the lopsided bit

Each packer has one signal that says "move a word now":

DirectionThe strobeComes from
Receivecpack/fifo_wr_en Channel 0's valid, alone.
Transmittx_upack/fifo_rd_en Channel 0's valid OR channel 1's.

Every channel is captured on channel 0's timing — the hinge this lesson turns on. On ADI's wiring, channel 1's own valid, adc_valid_i1, is connected to nothing at all. (In a default build of this repo it drives valid_in_2 of the decimator; the single write strobe is unchanged either way.)

The filter that, on ADI’s wiring, exists on one channel only

This describes ADI's wiring: what the factory bitstream runs, and what this repo builds with STOCK_RX_FILTER=1. The fix later in this lesson is applied by default. Between the radio interface and cpack, channel 0 passes through rx_fir_decimator; channel 1 goes straight past. That hierarchy contains:

  • One filter per stream — two here, for I and Q (four once channel 1 is routed through it too).
  • A clock-domain crossing for the on/off signal (lesson 22's problem, already solved here).
  • Bypass multiplexers, one per stream, all following a single active bit. The filters are always present in the fabric; what moves at runtime is the bypass.

What is it for? The chip has a floor

Why a decimating filter in the fabric, when the AD9361 has filters of its own? Because the AD9361 cannot go slow enough:

terminalShell
iio_attr -u ip:192.168.2.1 -i -c ad9361-phy voltage0 sampling_frequency_available
#   [2083333 1 61440000]     <- minimum, step, maximum

2,083,333 samples per second is a hard floor in the silicon, so the narrowest slice this radio delivers alone is about 2.1 MHz — 700 times wider than SSB voice (3 kHz), 10 times an FM broadcast channel or GSM carrier (200 kHz). The fabric decimator removes that floor. Measured on this board, converter as slow as it goes:

Without the filterWith it engaged
Converter rate2,083,333 SPS2,083,333 SPS
Rate delivered to you2,083,333 SPS260,416 SPS
Data rate8.33 MB/s1.04 MB/s
Processing gain—9 dB (~1.5 bits)

It extends the radio's usable range downward, past the silicon's floor. That also explains:

  • Why the factor is fixed at eight, and the driver offers only {1, 8}: it is one specific extension of the rate range, not a general resampler.
  • Why there is a matching ×8 interpolator on transmit: the floor applies in both directions.
  • Why both share one coefficient file: one generic anti-alias design for a factor of eight, used in opposite directions.

And why the channel-1 problem was invisible to whoever designed it

This block design serves a family of boards, many of them 1R1T — one receiver, one transmitter — where channel 0 is the only channel. It is a defect only on a 2R2T board.

Why it is a filter and a ÷8, never just a ÷8

Keeping every eighth sample is undersampling (lesson 12). One in eight of 61.44 MSPS is 7.68 MSPS, a ±3.84 MHz window, and everything outside it folds in: eight slices summed, so any transmitter in the other seven lands on your signal and the noise is roughly eight times higher.

The FIR filter empties those seven slices before the samples are discarded: an anti-alias filter.

Downsampling is keeping one sample in D, and aliases; decimation is filtering first, then keeping one in D.

Where the free dynamic range comes from

Decimating by D buys 10·log₁₀(D) dB of signal-to-noise (lesson 27) because the filter discards the noise in the slices you are not keeping. Remove the filter and the gain vanishes: processing gain and anti-alias filter are the same fact.

So what is in the .coe file?

One tap value per line, 129 of them. That list is the filter, and its stopband depth sets how much aliasing survives: at 80 dB whatever folds in arrives 80 dB weaker.

Check yourself: why can the AD9361's own analogue filter not do this job for you?

It protects the converter's rate (rf_bandwidth), and the converter still runs at full speed. Every point where the rate drops needs its own anti-alias filter.

The one line of Tcl that builds it

firmware/src/hdl/projects/pluto/system_bd.tclTcl
ad_add_decimation_filter "rx_fir_decimator" 8 2 1 {61.44} {61.44} <coe>
PieceWhat it isWhat happens if you change it
ad_add_decimation_filter A helper procedure in projects/common/xilinx/adi_fir_filter_bd.tcl that builds the whole hierarchy. Transmit has ad_add_interpolation_filter.
"rx_fir_decimator" The hierarchy's name. Every ad_connect using it must change too.
8 The decimation factor. Do not. The driver offers exactly {1, 8}; a ÷4 filter would build and be unreachable.
2 Channels: I and Q. —
1 Parallel paths: samples per clock tick. —
{61.44} The clock rate in MHz. Wrong, and the tool builds the wrong amount of hardware.
{61.44} The sample rate in MHz. Ticks per sample are what make taps cheap (lesson 27). —
<coe> The coefficient file. See the trap below.

How you switch it on

The hierarchy's active pin (low: bypass, high: filter) is driven from one bit of a general-purpose register via decim_slice. You never set it by hand; ask for the slower rate and Linux engages the filter:

terminalShell
# run on your HOST. Ask what rates the receive path will give you:
iio_attr -u ip:192.168.2.1 -i -c cf-ad9361-lpc voltage0 sampling_frequency_available

# Exactly TWO numbers, following the AD9361's current rate:
#   converter at 30.72 MSPS  ->  "30720000 3840000"
#   converter at 61.44 MSPS  ->  "61440000 7680000"

# Asking for the lower one turns the filter on:
iio_attr -u ip:192.168.2.1 -i -c cf-ad9361-lpc voltage0 sampling_frequency 3840000

The filter is bypassed unless something asks for the slow rate. An unexpected pair means the converter is not where you think:

terminalShell
iio_attr -u ip:192.168.2.1 -i -c ad9361-phy voltage0 sampling_frequency
Check yourself: you edit the coefficients, rebuild, flash — and the response is unchanged. Why?

Almost certainly the filter is bypassed: nothing asked for the decimated rate, so samples take the pass-through path. Set sampling_frequency to one eighth of the converter rate and measure again. (And check you deleted the Vivado project before rebuilding — lesson 21.)

One coefficient file feeds both directions

The stock taps are 129 values from library/util_fir_int/coefile_int.coe — the same file for receive and transmit. Edit it and you have changed both. Point one side at a different file instead.

Ignore the .v files in library/util_fir_int/ and util_fir_dec/: dead code in this project, never built. Only the .coe matters.

The real trap: turning the filter on quietly ruins channel 1

cpack captures every enabled channel on channel 0's timing, and channel 1 has no filter of its own. Engage the decimator and channel 1 is sampled at one eighth rate with no anti-alias filter: everything outside ±Fs/16 folds onto it, and it is shifted in time relative to channel 0 by the filter's group delay — the delay a filter imposes while it gathers enough samples to compute an output.

In the stock design, channel 1 is only trustworthy while the filter is bypassed. This is ADI's wiring, and this repo fixes it.

Fixing it: both receivers, in lockstep

The helper already loops over its channel count, so the repair is to ask for four channels and feed the second pair through as well:

firmware/patches/0021-filter-both-receive-channels-by-default.patchTcl
// 4 channels: ch0 I/Q and ch1 I/Q, rather than 2
ad_add_decimation_filter "rx_fir_decimator" 8 4 1 {61.44} {61.44} <coe>

// feed channel 1 in ...
ad_connect axi_ad9361/adc_data_i1  rx_fir_decimator/data_in_2
ad_connect axi_ad9361/adc_data_q1  rx_fir_decimator/data_in_3

// ... and take cpack's inputs from the filter, not from axi_ad9361
ad_connect cpack/fifo_wr_data_2  rx_fir_decimator/data_out_2
ad_connect cpack/fifo_wr_data_3  rx_fir_decimator/data_out_3

Lockstep: one active bit, one coefficient set, one group delay, so the receivers stay sample-aligned and cpack/fifo_wr_en taking valid_out_0 is now correct.

Channel 1, decimator engagedSTOCK_RX_FILTER=1Default
A tone 10 MHz out of band appears at+2.320 MHz (an alias)not at all
Attenuation of tones past 5 MHznone (+1.4 dB)70.1 dB on average
DSP48 slices used72 / 22094 / 220
Worst negative slack+0.205 ns+0.215 ns

Two extra filter instances, about 11 DSP slices each. Full write-up: docs/both-receive-channels.md in the repository.

Why one filter design is correct for both receivers

The AD9361 has exactly two local oscillators, RX_LO and TX_LO; both receivers share the first (there is no RX2_LO), and rf_bandwidth is shared too. Only gain is per-channel. Both receivers always see the same band at the same width, so one filter design fits both.

If you do want two different centre frequencies

Put a digital mixer on each channel in the fabric, ahead of the decimator (lesson 28), each shifting a different part of the band to zero. That is a channelizer — what the single receive LO cannot do but the fabric can.

And the transmit interpolator does not work at all

The transmit strobe is channel 0's valid OR channel 1's, and channel 1 has no interpolator, so it drags the packer at full rate. Measured: tx_upack was read at twelve times the intended rate, and a tone sent through the interpolator did not come out at all — the received spectrum matched a muted transmitter to within 1.2 dB.

You only reach this by setting the transmit core's sampling_frequency to one eighth of the AD9361's rate. Do not.

16

How samples reach memory, and back

The full journey in both directions: packer, DMA engine, a dedicated port into the DDR chips, your program's buffer. Every address and setting here is this board's.

At 61.44 MSPS each direction is 245 MB/s, more than a 666 MHz ARM core can copy. A DMA engine (Direct Memory Access) moves the data instead and tells the processor when a whole buffer is done.

The pieces, named

DDR
The board's main memory: two Micron chips totalling 1 GB, on the processor side.
AXI
The on-chip bus standard: AXI-Stream is a plain "word, valid, ready" flow; AXI-MM (memory-mapped) carries addresses.
HP port
A High-Performance port into the memory controller that the fabric uses without the CPU. This board wires two.
Descriptor
"Move this many bytes, to or from this address": written by software, executed by the engine.

The two engines on this board

Both are ADI's axi_dmac, one per direction, 64 bits wide on the fabric side — exactly the width the packers produce and consume.

ReceiveTransmit
Blockaxi_ad9361_adc_dmaaxi_ad9361_dac_dma
Register address0x7C40_00000x7C42_0000
Interruptps-13ps-12
Door to memoryS_AXI_HP1S_AXI_HP2
Fabric sideDMA_TYPE_SRC 2 — a FIFO fed by cpack DMA_TYPE_DEST 1 — AXI-Stream into tx_upack
Memory sideAXI-MM writing to DDRAXI-MM reading from DDR
Notable settingSYNC_TRANSFER_STARTCYCLIC 1
Linux devicecf-ad9361-lpccf-ad9361-dds-core-lpc

Those addresses are mirrored in the device tree (zynq-pluto-sdr-fishball.dts, one per target). Move a block in the block design and the driver probes the wrong place; add one and it needs a device-tree node before Linux can see it.

Each DMA straddles two clock domains

The fabric side runs on l_clk, which moves with the sample rate (lesson 14); the memory side on sys_cpu_clk, a fixed 100 MHz. The DMA is itself a well-tested clock-domain crossing.

Receive, step by step

  1. The AD9361 sends samples over the LVDS link. axi_ad9361 recovers the clock, deserialises, sign-extends 12 bits to 16, applies DC-offset correction.
  2. The samples pass through rx_fir_decimator (lesson 15) — both channels in a default build; only channel 0 on ADI's wiring.
  3. cpack interleaves the enabled channels into 64-bit words, one per pulse of fifo_wr_en.
  4. The receive DMA's input FIFO absorbs them, and the engine bursts them across S_AXI_HP1 into DDR, at addresses from a descriptor.
  5. When a buffer is full, the engine raises interrupt ps-13; the driver marks it ready and hands the next one to the hardware.
  6. Your program's read() — or iio_readdev, or pyadi-iio — returns the completed buffer. No sample was ever copied by the CPU.

SYNC_TRANSFER_START makes a capture begin on a clean packer boundary; without it your first samples could be the tail of a word, with the channel order shifted.

Transmit, step by step

  1. Your program writes samples into a buffer; the driver hands the DMA a descriptor pointing at it in DDR.
  2. The engine reads from DDR across S_AXI_HP2 and presents 64-bit words to tx_upack as an AXI-Stream, one per pulse of fifo_rd_en.
  3. tx_upack splits each word back into per-channel 16-bit samples.
  4. axi_ad9361 takes bits [15:4] of each — the DAC is 12 bits — and sends them over the LVDS link. Bits [3:0] are discarded, which is what the sample-locked GPIO feature reuses.
  5. Interrupt ps-12 tells the driver a buffer has been consumed, so it can queue the next.

Underflow looks like a broken radio

If software does not refill fast enough, the transmit engine substitutes zeros and raises fifo_rd_underflow. Measured on this board, that happens above about 5 MSPS when transmit and receive stream continuously at once — and it looks like terrible modulation quality, not missing data, so it is easy to misdiagnose.

The receive equivalent is overflow: software has not drained the previous buffer, so samples are lost.

CYCLIC 1, and why a crashed program can keep transmitting

The transmit engine can repeat a buffer forever — how you transmit at the full 61.44 MSPS with the host feeding nothing. The repetition lives in hardware, so your program exiting, crashing or being killed does not stop it.

An ordinary, non-cyclic transmit used to behave the same way, as a defect: killing a local transmit client left the radio live, measured 12.6 dB above the muted floor. This firmware now mutes when the converter stops being fed: no data for 250 ms and the attenuator goes to maximum, measured at 0.27 s from the kill. Read the timeout at /sys/bus/iio/devices/iio:device2/tx_starve_timeout_ms, and keep a different one across reboots with fw_setenv tx_starve_ms. The first block of a new buffer gets longer, in proportion to its size, because it is uploaded after the buffer is switched on: a 4.4 MB pattern used to be muted before it had even arrived.

Cyclic is exempt from that: a healthy cyclic stream sends nothing after its one buffer, so a kill -9 on it looks like normal operation. Make stopping it explicit and verified. A separate bound, tx_cyclic_timeout_ms, is armed at 60 s at every boot on the modern (Debian) target; on the factory target it is off unless you set fw_setenv tx_cyclic_bound.

Two things about that watchdog that are easy to get wrong. First, it does not re-arm. Once it has fired, data arriving again does not change the driver's mind — only opening a fresh buffer does. So after a starve-mute, writing a gain raises the attenuator and nothing puts it back, not even stopping the stream. What keeps the port quiet then is the powered-down TX LO, so never read hardwaregain alone and conclude anything; read out_altvoltage1_TX_LO_powerdown beside it.

Second: mute before you close the buffer, not after. When a stream stops, the driver caches whatever attenuation it finds, applies maximum, and gives the cached value to the next buffer anybody opens. Measured on the bench: a board reading a fully muted −89.75 dB came up at −61.5 dB the moment a buffer was opened, 28 dB nobody asked for, because the previous run closed before muting. Several tools in this repo had it backwards, including the one that runs in CI.

So opening a transmit buffer is not a neutral act: the enable can bring the oscillator up and lift an attenuator. A program that means to stay silent cannot write −89.75 and trust it; it must read both attenuators back after the enable and stop if either moved.

Try it — can your link carry this rate?

Buffer sizing, from Linux

The kernel's IIO DMA layer caps how large one block may be, and userspace sets the cap at boot. On the factory target (Buildroot) it is the script below; the modern (Debian) target has no S21misc and does the same from fishball-identity.service:

buildroot/board/pluto/S21miscShell
MAX_BS=`fw_printenv -n iio_max_block_size 2> /dev/null || echo 67108864`
echo ${MAX_BS} > /sys/module/industrialio_buffer_dma/parameters/max_block_size

64 MB by default — about 16 million samples — overridable with fw_setenv iio_max_block_size. Large buffers tolerate a host that pauses, at the cost of latency; small ones react quickly but underflow if software falls behind.

Watch it happen

The DMA engines report their own overflow and underflow; find where your link gives up:

terminalShell
# run on your HOST - raise the sample rate until this starts complaining
iio_adi_xflow_check -u ip:192.168.2.1 cf-ad9361-lpc

Changing the fabric

17

The worked example, line by line

A real module from this repo, trimmed to its core. Twenty lines of logic that teach four habits at once.

What it does. The AD9361's DAC is 12 bits, but you hand it 16-bit samples. It takes the top 12 and throws the bottom four away — literally, in ADI's HDL: dac_data_out <= dma_data[15:4]. This module catches those four bits and puts them on four header pins, in lockstep with the sample that carried them. It costs nothing in signal quality, because the bits never reached the DAC.

tx_gpio_bitmap.vVerilog
module tx_gpio_bitmap (
  input  wire       clk,        // l_clk
  input  wire       rst,
  input  wire [3:0] sample_in,  // the discarded low nibble
  input  wire       valid_in,   // fifo_rd_valid | fifo_rd_underflow
  input  wire       flag,       // enable, from an AXI register
  input  wire [3:0] gpio_in,    // what the PS wants when disabled
  output wire [3:0] pin_o
);

  // (1) 'flag' is written in the AXI clock domain and read here in
  //     l_clk. Two flip-flops make that safe. See lesson 22.
  reg flag_meta, flag_sync;
  always @(posedge clk) begin
    flag_meta <= flag;
    flag_sync <= flag_meta;
  end

  // (2) capture on the VALID strobe, never on the clock: in 2R2T a
  //     sample arrives only every second l_clk edge.
  reg [3:0] held;
  always @(posedge clk) begin
    if (rst)            held <= 4'd0;
    else if (valid_in)  held <= sample_in;
  end

  // (3) our nibble, or the processor's GPIO
  assign pin_o = flag_sync ? held : gpio_in;

endmodule

The four habits

  1. Synchronise anything arriving from another clock. flag is written by Linux. Sampling it directly risks metastability. Two flip-flops cost almost nothing.
  2. Gate on valid, never on the clock. The 2R2T trap from lesson 14.
  3. Reset only what needs it. held does; the synchroniser flops do not. Over-resetting wastes fabric and strains timing.
  4. Keep the bypass clean. With flag clear the pins behave exactly as before. A feature you cannot fully switch off is one people will not switch on.

Try it

Change the module so a second flag bit puts a free-running counter on the pins instead of the sample nibble. You now have a divided sample clock on a header pin — a scope trigger with a fixed, known relationship to the transmitted RF, which no software timing can give you.

18

Wiring it in with Tcl

This board's block design is a script, not a drawing — so your change is a reviewable diff rather than a mouse gesture nobody can check.

Tcl is the scripting language Vivado is driven by. You need four kinds of line, all in firmware/src/hdl/projects/pluto/system_bd.tcl.

system_bd.tclTcl
# 1. make the source file part of the project
add_files -norecurse $ad_hdl_dir/projects/pluto/tx_gpio_bitmap.v

# 2. instantiate it as a cell in the block design
create_bd_cell -type module -reference tx_gpio_bitmap tx_bitmap

# 3. slice the bits you want out of a wide bus
ad_ip_instance xlslice nibble_slice [list \
  DIN_WIDTH 16 DIN_FROM 3 DIN_TO 0 DOUT_WIDTH 4]

# 4. connect things up
ad_connect axi_ad9361/l_clk            tx_bitmap/clk
ad_connect axi_ad9361/rst              tx_bitmap/rst
ad_connect tx_upack/fifo_rd_data_0     nibble_slice/Din
ad_connect nibble_slice/Dout           tx_bitmap/sample_in
ad_connect tx_upack/fifo_rd_valid      bitmap_valid_or/Op1
ad_connect tx_upack/fifo_rd_underflow  bitmap_valid_or/Op2
ad_connect bitmap_valid_or/Res         tx_bitmap/valid_in

The helper blocks you will reach for

BlockUse
xlsliceTake bits [3:0] out of a 16-bit bus. Configured by parameters, no HDL required.
xlconcatGlue narrow signals into a wide one.
util_vector_logicAND / OR / NOT on buses — this is how the valid-or-underflow OR above is built.
xlconstantTie a signal permanently high or low.
create_bd_portBring a signal out to a physical pin — then constrain it, lesson 20.

Where in the file matters

add_files must run before the module is referenced, and this script is sourced from inside adi_project_create. Put the add_files line next to your create_bd_cell, not in system_project.tcl — by the time that runs the fileset is already built, and your module will simply be "not found".

19

Packaging your Verilog as an IP, and splicing it into the datapath

Lesson 18's three lines of Tcl are right for a small change, wrong for anything you intend to keep. This lesson turns Verilog into a real Vivado IP and cuts it into the receive or transmit path the way ADI's own blocks are.

Module or IP? Decide once, up front

create_bd_cell -type moduleA packaged IP
Effortthree lines of Tcla directory, a Tcl script and a build step
Reusable in another projectno — the path is hard-codedyes — it is in the catalog
ParametersVerilog parameters, no GUI, no validationnamed, typed, with a GUI and enablement rules
Interfacesloose wires, connected one at a timebuses — one ad_connect moves the whole bundle
Versioningnone1.0, 1.1, … and the design records which it used
Out-of-context synthesisno — resynthesised with the whole designyes, and cached, so rebuilds are faster

Prototype as a module, package when it works.

Step 1 — write the RTL with the packager in mind

Vivado infers interfaces from signal names: name ports the way it expects and a bus connects in one line; otherwise you get loose pins forever. A receive-path scaler in this board's conventions:

library/util_rxscale/util_rxscale.vVerilog
module util_rxscale #(
  parameter DATA_WIDTH = 16
) (
  input  wire                    clk,        // l_clk - the recovered clock
  input  wire                    resetn,

  // ---- the ADI datapath convention, in ----
  input  wire                    valid_in,   // one pulse per sample
  input  wire                    enable_in,  // channel is switched on (a level, not a strobe)
  input  wire [DATA_WIDTH-1:0] data_in,

  // ---- and out ----
  output reg                     valid_out,
  output wire                    enable_out,
  output reg  [DATA_WIDTH-1:0] data_out,

  input  wire [7:0]              shift       // runtime control, see step 6
);
  assign enable_out = enable_in;      // pass the level straight through

  wire signed [DATA_WIDTH-1:0] s = data_in;

  always @(posedge clk) begin
    if (!resetn) begin
      valid_out <= 1'b0;
      data_out  <= {DATA_WIDTH{1'b0}};
    end else begin
      valid_out <= valid_in;           // SAME latency as the data - one cycle
      data_out  <= s >>> shift;        // arithmetic shift: keeps the sign
    end
  end
endmodule

The contract you are signing when you cut into this datapath

  1. Delay valid by exactly as much as data. One extra register on the data and every sample downstream carries its neighbour's strobe.
  2. enable is a level, not a strobe — "this channel is on". Do not pipeline it or treat it as a per-sample qualifier.
  3. Do not change the rate unless you mean to. One valid_in, one valid_out. Producing fewer is a decimator, with the consequences below.
  4. Everything is on l_clk. Not sys_cpu_clk. A value from the processor side crosses domains — lesson 22.

Step 2 — package it

The GUI route (Tools → Create and Package New IP) cannot be reviewed or repeated; script it like the rest of the library:

library/util_rxscale/util_rxscale_ip.tclTcl
source ../../scripts/adi_env.tcl
source $ad_hdl_dir/library/scripts/adi_ip_xilinx.tcl

adi_ip_create util_rxscale                          # make the packaging project
adi_ip_files  util_rxscale [list "util_rxscale.v"]  # the sources it contains
adi_ip_properties_lite util_rxscale                 # name, vendor, taxonomy, clocks

ipx::save_core [ipx::current_core]
adi_ip_properties_lite
Fills in vendor, library, version and taxonomy and infers clock and reset. For a datapath block like this one.
adi_ip_properties
The same, plus it infers an AXI4-Lite slave from ports named s_axi_awvalid, s_axi_wdata and the rest. For an IP with its own registers — step 6.
adi_add_bus
Declares a custom interface from your port names — how util_cpack2 gets its single packed_fifo_wr bus.
packaging the IPrun from: firmware/src/hdl/library/util_rxscale/
cp ../util_axis_fifo/Makefile .   # a library at the SAME depth as yours
# then edit it down to:
#   LIBRARY_NAME := util_rxscale
#   GENERIC_DEPS += util_rxscale.v
#   XILINX_DEPS  += util_rxscale_ip.tcl
#   include ../scripts/library.mk
make                             # runs vivado -mode batch on the _ip.tcl
ls component.xml                 # this file IS the IP

The beginner's mistake

Copying the Makefile from util_pack/util_cpack2/, two directories below library/: its include ../../scripts/library.mk breaks one level up and make stops with No such file or directory. Copy from a neighbour at your own depth, such as util_axis_fifo.

Why dropping it in library/ is enough

adi_project_create sets ip_repo_paths to $ad_hdl_dir/library, so any directory there with a component.xml is in every project's catalog.

Step 3 — instantiate it

system_bd.tclTcl
ad_ip_instance util_rxscale rx_scale_i [list DATA_WIDTH 16]
ad_ip_instance util_rxscale rx_scale_q [list DATA_WIDTH 16]

No add_files: the IP carries its own sources.

Step 4 — cut it into the receive path

Insertion is always delete a connection, make two new ones — here between axi_ad9361 and rx_fir_decimator (or cpack, without the filter).

system_bd.tcl — channel 0, I and QTcl
# 1. break what ADI wired
ad_disconnect axi_ad9361/adc_data_i0  rx_fir_decimator/data_in_0
ad_disconnect axi_ad9361/adc_valid_i0 rx_fir_decimator/valid_in_0

# 2. clock and reset your block from the same domain as the data
ad_connect axi_ad9361/l_clk  rx_scale_i/clk
ad_connect sys_rstgen/peripheral_aresetn rx_scale_i/resetn

# 3. route through it
ad_connect axi_ad9361/adc_data_i0   rx_scale_i/data_in
ad_connect axi_ad9361/adc_valid_i0  rx_scale_i/valid_in
ad_connect axi_ad9361/adc_enable_i0 rx_scale_i/enable_in

ad_connect rx_scale_i/data_out   rx_fir_decimator/data_in_0
ad_connect rx_scale_i/valid_out  rx_fir_decimator/valid_in_0
ad_connect rx_scale_i/enable_out rx_fir_decimator/enable_in_0

Repeat for _q0 and — the part people skip — for _i1 and _q1.

Do all four channels, or you will rediscover this board's known defect

cpack/fifo_wr_en is driven by one channel's valid and captures every enabled channel on it. Add a cycle of latency to channel 0 only and the two channels are permanently one sample apart in the buffer, with no error anywhere — the asymmetry of both-receive-channels.md and lesson 15. Insert it in all four paths, with identical latency.

Step 5 — and the transmit path, which is fussier

Transmit runs the other way: tx_upack produces samples, which pass through tx_fir_interpolator to axi_ad9361. Cut in ahead of the interpolator, mirroring the receive side:

system_bd.tcl — transmit, channel 0 ITcl
ad_disconnect tx_upack/fifo_rd_data_0 tx_fir_interpolator/data_in_0

ad_connect tx_upack/fifo_rd_data_0  tx_scale_i/data_in
ad_connect tx_upack/fifo_rd_valid   tx_scale_i/valid_in
ad_connect axi_ad9361/dac_enable_i0 tx_scale_i/enable_in
ad_connect tx_scale_i/data_out      tx_fir_interpolator/data_in_0

Two transmit-side facts that have each cost a build here

The read enable is an OR, and it bites
tx_upack/fifo_rd_en is the OR of the interpolator's valid and channel 1's DAC valid, so on this 2R2T board channel 1 drags the packer along at full rate. A same-rate block is fine; a rate-changing one on transmit is not — engage the fabric ÷8 interpolator and, measured, TX1 emits nothing at all.
The DAC keeps the top 12 bits
It discards the low nibble, so a scaler that shifts right throws away bits the converter would never have used — and those four bits are the ones tx-gpio-bitmap.md routes to the header pins.

Step 6 — giving it a knob software can turn

The shift input has to come from somewhere:

Borrow a GPIO bit
As ADI did for the decimator's active bit: axi_ad9361's up_adc_gpio_out is a register of spare bits written from userspace, and an xlslice picks yours out. No new address; only a handful of bits.
Add your own AXI4-Lite slave
Name the ports s_axi_*, call adi_ip_properties instead of the _lite variant, then give it an address: ad_cpu_interconnect 0x7C44_0000 rx_scale_i. Real registers at a real address, reachable with devmem or a driver, at the cost of writing the register file — lesson 23.

Either way the value crosses from sys_cpu_clk to l_clk, so it needs lesson 22's treatment — and a constraint, or Vivado will quietly drop the path.

Step 7 — build it, and the one step everybody forgets

the whole looprun from: the repo root
# 1. package (only when the IP's own sources changed)
cd firmware/src/hdl/library/util_rxscale && make && cd -

# 2. DELETE THE PROJECT. build_hdl.tcl reuses an existing pluto.xpr and
#    will silently ignore your block-design change if you skip this.
rm -rf firmware/src/hdl/projects/pluto/pluto.{xpr,cache,gen,hw,ip_user_files,runs,sim,srcs,sdk}

# 3. build, check, flash
./devkit build --target factory --hdl-only
./devkit verify --target factory
./devkit flash --target factory --boot-only

Skip step 2 and the build succeeds, the board boots, and it runs your previous design.

Prove the insertion before you trust it

Set a shift of 3 (a clean −18 dB) and check a capture drops 18 dB on both channels and both I and Q; then set 0 and check the capture is bit-identical to one taken before your block existed. That catches a mis-wired channel, swapped I/Q, an off-by-one on valid, and a block not in the path at all.

Check yourself: your block adds one cycle of latency. What else in the design has to know?

On receive, nothing downstream cares about absolute latency: cpack captures on a strobe and the DMA stores what it is given. But latency differences matter, so the other three channels need the same one cycle or the four streams no longer line up.

Anything comparing the two receivers, such as lesson 46's direction finding, sees a one-cycle difference as a phase error that looks like a real measurement.

20

Pins and constraints

A signal at the edge of the fabric still has to be told which physical ball to leave by, and at what voltage.

Constraints live in an XDC file (Xilinx Design Constraints), system_constr.xdc, one line per pin:

system_constr.xdcXDC
set_property -dict {PACKAGE_PIN V10 IOSTANDARD LVCMOS33 PULLTYPE PULLDOWN} \
  [get_ports sample_gpio[0]]
PACKAGE_PIN
Which physical ball on the package; V10 is a grid reference.
IOSTANDARD
The electrical standard; it must match the voltage supplied to that bank. LVCMOS33 is 3.3 V logic.
PULLTYPE
An optional weak resistor holding the pin at a known level when undriven.
get_ports
The top-level signal this applies to.

The beginner's mistake

Naming the block-design port instead of the top-level one. Inside the block diagram the port is sample_gpio_o, with sample_gpio_t carrying tri-state control; the wrapper combines them into one inout port, sample_gpio, and only that exists at the edge of the chip.

Write sample_gpio_o[0] and Vivado says [Vivado 12-584] No ports matched — only a warning. The bitstream builds and the pin is never assigned. Grep the implementation log for 12-584 after any constraint change; it is the same class of silent drop as the missing -from in lesson 22.

The four pins verified on this board

JP5 pinBallBankStandard
7V1013LVCMOS33
9U913LVCMOS33
11U1013LVCMOS33
13T913LVCMOS33

Bank 13 is supplied from 3.3 V, hence LVCMOS33. An IOSTANDARD that does not match the bank's supply is a build error at best.

Do not invent pins from the schematic

Driving a ball that is an input, or tied elsewhere, can damage the hardware. The four above were traced and measured; anything else needs the schematic and care.

21

Driving Vivado, and reading what it tells you

You will barely click anything, but you must be able to read the report.

The trap that costs everyone one build

build_hdl.tcl reopens an existing Vivado project rather than re-running system_bd.tcl. Change the block design or a coefficient file without deleting the project and your change is silently ignored: you wait twenty minutes, flash, and debug logic that was never built.

before EVERY HDL or coefficient changeShell
# run from: firmware/src
rm -rf hdl/projects/pluto/pluto.{xpr,cache,gen,hw,ip_user_files,runs,sim,srcs,sdk}

The build runs synthesis (Verilog to a netlist of gates and flip-flops; catches syntax errors, infers latches), placement (which physical LUT and flip-flop each part becomes), routing (the wires between them, where timing is won or lost, because wire length is delay) and bitstream generation.

Reading timing

The number that matters is WNS, Worst Negative Slack, in nanoseconds. Slack is how much earlier than its deadline the slowest signal arrived.

  • WNS positive: timing met, with that margin. This repository's builds land near +0.2 ns, on either wiring.
  • WNS negative: some path is too slow. The bitstream still builds and may appear to work, but it is unreliable and temperature-dependent. Do not ship it.

Fixes, in order: a pipeline register to split a long combinational path; narrower arithmetic; a multiply moved onto a DSP slice; only then, constraints.

Your budget on this chip

ResourceDefault buildAvailableSpare
DSP slices94220126
LUTs12,52153,20040,679

More than half the multipliers and three-quarters of the logic are free (a STOCK_RX_FILTER=1 build, filtering only channel 0, uses 72 DSP slices and 11,896 LUTs). A 300-tap filter fits comfortably.

./devkit verify --target factory checks the five output files, that timing was met, and that the bitstream is compressed: an uncompressed one overflows the FSBL's on-chip memory and the board fails to boot with no message at all.

22

Crossing clock domains

Bugs that pass simulation and timing, then fail on hardware occasionally.

Linux writes your enable bit in the AXI clock domain; your datapath runs on l_clk, which follows the sample rate. The two have no fixed relationship.

A flip-flop needs its input stable for a short window around the clock edge. If the input changes then, it can enter metastability: neither 0 nor 1, resolving after an unpredictable delay, and different downstream logic may resolve it differently.

two-flop synchroniserVerilog
reg meta, sync;
always @(posedge dest_clk) begin
  meta <= src_signal;   // this one may go metastable
  sync <= meta;         // by now it has had a full cycle to settle
end
// use 'sync' everywhere. Never use 'meta'.

One bit only

Fine for slowly-changing control bits; wrong for a multi-bit value. Each bit settles independently, so you can read a number that never existed. Multi-bit crossings need a handshake or an asynchronous FIFO.

Telling the tools it is deliberate

Synthesis does not know the crossing is intentional, so say so in the XDC:

system_constr.xdcXDC
set_max_delay -datapath_only \
  -from [get_cells .../flag_reg] \
  -to   [get_cells .../flag_meta_reg] 4.000

A real bug from this repo's history

set_max_delay -datapath_only requires -from. Without it Vivado silently drops the constraint, with nothing in the log. That left the bit-map flag's crossing unconstrained through several releases. Patch 0009 fixed it, and CI now fails the build if any -datapath_only line lacks its -from.

23

Registers, and talking to Linux

Where the fabric and Linux meet.

ADI's cores expose AXI registers: addresses that, written from Linux, change signals in the fabric. GP_CONTROL, at offset 0xBC on the transmit core, is a general-purpose output whose bits you can use. The bit-map feature gets its enable there, without a new AXI device:

BitMeaning
0Interpolator bypass (ADI's own use)
1Sample-nibble GPIO enable (added by patch 0006)

Two features share one register, so every write must be read-modify-write: read, change only your bit, write back. Assigning the whole register clears the other feature.

Poking it by hand

terminalShell
# run on your HOST
iio_attr -u ip:192.168.2.1 -D cf-ad9361-dds-core-lpc direct_reg_access 0xBC
iio_attr -u ip:192.168.2.1 -D cf-ad9361-dds-core-lpc direct_reg_access

Bit 31 decides where the address goes

On cf-ad9361-lpc (the receive core) a plain address like 0xB8 goes to the AD9361 over SPI; only 0x800000B8 reaches the core's own register. The transmit core maps plain addresses to itself, so identical code "works" on one core and silently reads and writes radio chip registers on the other.

Giving it a proper name

Raw pokes are fine for bring-up, wrong for a shipped feature. A sysfs attribute in the driver makes the feature a named file, usable from anywhere including over the network (patch 0007, on both targets):

cf_axi_dds.cC
static ssize_t axidds_tx_sample_gpio_store(struct device *dev,
    struct device_attribute *attr, const char *buf, size_t len)
{
    /* read-modify-write: bit 0 belongs to someone else */
    cf_axi_dds_lock(st);
    reg = dds_read(st, ADI_REG_DAC_GP_CONTROL);
    if (enable) reg |=  ADI_TX_SAMPLE_GPIO_EN;
    else        reg &= ~ADI_TX_SAMPLE_GPIO_EN;
    dds_write(st, ADI_REG_DAC_GP_CONTROL, reg);
    cf_axi_dds_unlock(st);
    return len;
}
terminalShell
# run on your HOST - no ssh needed, it is a device attribute
iio_attr -u ip:192.168.2.1 -d cf-ad9361-dds-core-lpc tx_sample_gpio_en 1

Signals, before the fabric

24

The frequency domain, and what a spectrum really is

What a spectrum is, and the three settings that decide whether to trust one.

One signal, two descriptions

A signal can be described by what it does over time (a list of samples) or by which frequencies it is made of. They are two complete accounts of the same thing, and converting between them loses nothing.

The conversion is the Fourier transform; on a computer, the DFT (Discrete Fourier Transform), computed by the fast algorithm called the FFT. "4096-point FFT" means 4096 samples in one go.

The intuition

To ask "how much 1 MHz is in this signal?", multiply it by a 1 MHz reference wave and sum the products: if 1 MHz is there the sum grows, if not it cancels to near zero. Do that for every frequency and you have a spectrum.

What the picture is actually showing

An FFT of N samples returns N bins, each the energy in one narrow slice of frequency. Plotted in decibels, that is the spectrum. Because this board samples I and Q (lesson 11), the bins run from −fs/2 to +fs/2 around the tuned frequency; negative offsets mean "below the local oscillator".

Three settings decide what you see: the sample rate sets the span (2.083 to 61.44 MSPS here), the FFT length N sets the resolution, fs / N, and the window sets how far a strong signal smears over its neighbours.

Try it — what can this FFT actually resolve?

Why a window is needed

The FFT assumes your chunk repeats forever. Unless it holds a whole number of cycles, the end does not meet the start, and that step adds broadband energy, spectral leakage: skirts either side of a tone that bury anything small nearby. The fix is to multiply the chunk by a shape tapering to zero at both ends, a window. Hann is the default; Blackman-Harris leaks less but is wider; rectangular means none. The cost is a tone roughly 1.5× wider, almost always worth it.

The trade you cannot escape

Finer resolution needs a longer FFT, so a longer capture, so less ability to see fast change. Frequency and time resolution trade directly: at 61.44 MSPS a 4096-point FFT covers 66.7 µs and 15 kHz per bin; at 2.083 MSPS, 1.97 ms and 509 Hz.

Processing gain, and why a noise floor is not a number

Noise spreads across every bin; a tone lands in one. Double the FFT length and each bin collects half the noise, so the tone rises 3 dB above the floor with nothing about the signal changed.

So a noise floor means nothing without its FFT length; two measurements minutes apart can differ by 10 dB through this alone.

Check yourself: at 61.44 MSPS with a 4096-point FFT, can you separate two signals 10 kHz apart?

No. Resolution is 61.44 MHz / 4096 = 15 kHz per bin, so both fall in one bin. Either lengthen the FFT (65 536 points gives 937 Hz) or, usually better, drop the sample rate: at 2.083 MSPS the same FFT gives 509 Hz bins and the capture is thirty times smaller.

25

Noise, decibels, and where the floor comes from

Every measurement in this course is quoted in dB against a noise floor.

Decibels, once and for all

A decibel is a ratio on a logarithmic scale, so one page can hold a transmitter and thermal noise a hundred billion times weaker.

the two formulasdB
power ratio      dB = 10 × log10(P1 / P2)
amplitude ratio  dB = 20 × log10(A1 / A2)

Power goes as amplitude squared, hence the 20. Memorise: 3 dB doubles power, 6 dB doubles amplitude, 10 dB is ten times the power, 20 dB ten times the amplitude. Being logarithms, they add: a +19 dBm transmitter through a 20 dB attenuator arrives at −1 dBm.

UnitRatio againstWhere you meet it here
dBnothing — a bare ratio"20 dB of attenuation"
dBm1 milliwatt"+19 dBm output", an absolute power
dBFSthe converter's full scale"−20 dBFS", meaningful only on this converter
dBcthe carrier"71 dBc image rejection"
dBm/Hz1 mW, in one hertz of bandwidth"−174 dBm/Hz", a density: a power only once multiplied by a bandwidth

Where noise actually comes from

Three sources stack up, in this order of importance on this board:

  1. Thermal noise, from charge carriers jiggling above absolute zero, sets a floor no design beats: −174 dBm per hertz at room temperature. Over 5 MHz that is −174 + 10·log₁₀(5×10⁶) = −107 dBm.
  2. The receiver's own noise, its noise figure (NF): how many dB worse than that ideal the hardware is. The AD9361 is roughly 3–6 dB, depending on gain and band.
  3. Quantisation noise, the 6.02N + 1.76 dB limit from lesson 9; usually the smallest of the three here, which is the point of 12 bits.

Try it — what is the quietest signal this receiver could hear?

Narrow your view, gain SNR

The noise floor depends on bandwidth. Halve the bandwidth and you halve the noise power: 3 dB better signal-to-noise, with the signal unchanged. The FFT-length effect of lesson 24, this, and decimation's process gain (lesson 27) are one principle: noise is spread out, signal is not, so narrowing your view favours the signal. "Listen to less spectrum" is the first thing to try on a weak signal.

SNR is a number and a bandwidth

"The SNR is 30 dB" is incomplete without the bandwidth it was measured in. A tone in a 15 kHz FFT bin and the same tone across 5 MHz differ by 10·log₁₀(5 000 000 / 15 000) = 25 dB, with nothing about the radio changed.

Three noise numbers that get compared anyway

Tone SNR in an FFT bin, what tools/selftest/sdr_selftest.py reports, is flattering because the bin is narrow. SNR across the occupied bandwidth is what a demodulator experiences and predicts whether a link works. Noise figure belongs to the hardware alone. Quote the first where the second was meant and a link with "70 dB of SNR" fails to decode.

Reading your own board

Measured on this hardware: cable loopback at 900 MHz, 5 MSPS, TX2A through a 20 dB pad into RX2A:

QuantityValueMeaning
Signal−16.7 dBFSWell below clipping, well above the floor
Noise floor−53 dBFSIn a 4096-point FFT
Carrier SNR71 dBUsable dynamic range in that measurement
Thermal limit, 5 MHz−107 dBmNo receiver can beat it
Check yourself: you drop from 20 MSPS to 200 kSPS. What happens to your SNR, and why?

It improves by about 20 dB, 10·log₁₀(100), but only if the narrowing is a proper filter. Throwing samples away folds the out-of-band noise back in and gains nothing: the defect lesson 15 documents on channel 1.

DSP in the fabric

26

Filters, from first principles

Almost everything you build in the fabric is a filter or contains one.

A filter passes some frequencies and rejects others. Digitally, each output sample is a weighted sum of the most recent inputs.

a 4-tap FIR, conceptuallyVerilog
out[n] = c0*in[n] + c1*in[n-1] + c2*in[n-2] + c3*in[n-3];

That is a FIR filter, Finite Impulse Response: feed it a single spike and the output stops after a finite number of samples (four, here). The weights c0..c3 are taps or coefficients, and they are the entire design.

Why this filters anything at all

Averaging neighbours smooths, cancelling rapid wiggles: a low-pass filter. Subtracting neighbours emphasises change: a high-pass. Every other response is a more careful choice of weights.

What it costs in fabric

N taps need N multiplications per output. Multiplies are expensive in LUTs, which is why the chip has 220 dedicated DSP slices. A naive 100-tap filter would take 100 of them; the next lesson shows why that estimate is usually far too pessimistic.

Fixed point, and the two ways it goes wrong

The fabric has no floating point; coefficients are scaled integers. Overflow: a 16×16 multiply needs 32 bits and an accumulator more; truncate carelessly and a loud signal wraps into noise. Quantisation: rounding the coefficients fills in the stopband, so a filter designed for 80 dB of rejection may deliver 50 with 12-bit coefficients.

27

Decimation, and why taps are nearly free

The most useful trick in fabric DSP, and the reason this repo's channelizer is affordable.

Decimation produces one output for every D inputs, lowering the sample rate by D. Filter first, or the discarded bandwidth aliases back in (lesson 12).

The trick: one output every D inputs gives the hardware D input-sample periods per output, so one multiplier is reused D times. A 128-tap filter decimating by 8 needs roughly 16 multipliers, not 128. Taps are nearly free, so this repo's coefficient generator designs a simple Kaiser-windowed sinc rather than chase the roughly 30% tap saving of an equiripple design.

Why sample at 61 MSPS only to throw most of it away?

Capture 56 MHz, decimate by 307, keep a 200 kHz channel: 99.7% discarded. The AD9361 can sample at 200 kSPS directly, and for a fixed signal with no strong neighbours that is simpler and uses no fabric. Wide-then-decimate earns its complexity four ways.

1. About four extra bits of dynamic range

The converter's quantisation noise is roughly fixed in total power and spread across the whole sampled bandwidth. Filter to a narrow slice and you keep all the signal but only a fraction of the noise: a gain of 10·log₁₀(D) dB.

DecimationRate outProcessing gainWorth
415.36 MSPS6 dB1 bit
321.92 MSPS15 dB2.5 bits
307200 kSPS24.9 dB~4 bits

That is a 16-bit converter's dynamic range from a 12-bit one: oversampling.

2. A digital filter is far sharper than the analogue one

The analogue filter is a few poles with a corner that drifts with temperature. A 321-tap FIR gives 80 dB of stopband rejection, a transition band a few percent wide and exactly linear phase: with a strong transmitter 300 kHz away, only it saves you.

3. You can retune without touching the radio

Retuning the AD9361's local oscillator takes time, disturbs its calibration and breaks phase continuity. Retuning a fabric mixer (lesson 28) is one register write, phase preserved: the only workable approach for direction finding or coherent multi-channel work.

4. One capture, many channels

One capture can be split into as many narrow, simultaneous, phase-coherent channels as you have fabric for. That is a channelizer, and tuning cannot do it.

Try it — what does decimating buy you?

The worked example in this repo

FileRole
firmware/scripts/gen_fir_coe.pyDesigns and verifies the coefficients. Standard library only, no MATLAB or numpy.
coefile_wbfm_102100.coeIts output: 321 taps.
system_bd.tclWires the FIR IP in and points it at that file.
firmware/patches/optional/0003-wbfm-channelizer.patchThe whole change, opt-in. Factory tree only: it changes the FPGA, which the modern target takes ready-built as an --xsa.

It channelises wideband FM in the fabric, so the host receives a narrow, clean stream.

Coefficients count as an HDL change

Edit the .coe and you must delete the Vivado project, as for Verilog, or the FIR IP is regenerated from cache with the old taps.

Do not engage the FPGA's ÷8 transmit interpolator

It is in the stock design and does not work on this board: upstream's tx_upack read-enable ORs in channel 1's DAC valid, and this board runs 2R2T. Measured: TX1 emits nothing, within 1.2 dB of a muted transmitter.

Check "is it transmitting" against a muted reference in absolute dBFS; a normalised plot once made that silence look like a spray of components.

28

Mixers, oscillators and CORDIC

How to move a signal in frequency without touching the radio's tuning.

Multiplying a signal by a complex exponential shifts it in frequency; that is all a mixer is. Multiply by ej2πft and the spectrum slides up by f; a negative f slides it down.

The sine and cosine come from a numerically-controlled oscillator (NCO). The classic one is a phase accumulator: a counter that adds a fixed step every sample, ramping and wrapping like an angle, fed into a sine lookup table.

phase accumulatorVerilog
reg [31:0] phase;
always @(posedge clk)
  if (valid) phase <= phase + step;   // step sets the frequency

// frequency = step / 2^32 * sample_rate
// the accumulator wraps naturally, which is exactly what an angle does

A lookup table costs block RAM that grows with precision. CORDIC computes sine, cosine and rotation with only shifts and adds, one iteration per bit of precision, which pipelines well. For frequency shifting, rectangular-to-polar conversion or magnitude and phase, it is usually the right answer on an FPGA.

You already used one today

The transmit core's tone generator is a fabric NCO, so a full-rate transmit test costs no host bandwidth.

Building a radio link

29

What modulation actually is, and where to put it

The lesson that decides your architecture: stream the information, not the samples.

To send data, choose for each symbol period one point from a fixed set, a constellation, and transmit a pulse of that amplitude and phase.

SchemePointsBits/symbolTrade
BPSK21Most robust, slowest.
QPSK42The workhorse.
16-QAM164Twice the data, needs ~7 dB more SNR.
OFDMdozens of subcarriers at onceHandles echoes well; high peak-to-average ratio.

An abrupt step between symbols spreads energy across the spectrum, so each symbol is shaped by a pulse-shaping filter, usually root-raised-cosine (lesson 30).

The architecture question

The useful question is what you send down the wire to the board.

Stream bits, not samples

QPSK at 61.44 MSPS with 4 samples per symbol carries about 3.8 MB/s of information; as I/Q samples it is 245 MB/s, sixty-four times more. Put the modulator in the fabric, send it the 3.8 MB/s, and let the fabric do the fast, repetitive part: pulse shaping and rate conversion.

The three honest options

ApproachGood forLimit
Stream samples from the hostArbitrary, one-off waveforms. Easiest by far.The pipe: roughly 30 MB/s over the network with 64 Ksample buffers, so under 4 MSPS if you transmit and receive at once.
Cyclic bufferAnything periodic (tones, beacons, chirps): load once, the hardware repeats it at full rate, no HDL.No good for unique data.
Modulate in the fabricUnique data faster than the pipe; anything needing deterministic timing or microsecond reactions.You write and verify HDL, and a build is twenty minutes.

"Sophisticated" and "fast" are separate axes. For complex and fast, split it: coding, framing and adaptation on the processor; pulse shaping, interpolation and mixing in the fabric. Almost every real radio partitions it so.

Try it

Build a QPSK modulator in the fabric: two bits per symbol from an AXI register, mapped to one of four points, pulse-shaped by an interpolating FIR, fed into the transmit path.

30

Pulse shaping, and why root-raised-cosine

The shape given to each symbol decides how much spectrum you occupy and whether symbols smear into each other.

The obvious idea, and why it fails

Send lesson 29's QPSK symbols at 1 Msym/s by holding each steady for a microsecond: a train of rectangles. But a rectangle in time is a sinc in frequency, with skirts falling as 1/f that never end. A signal that ought to need about 1 MHz still radiates measurably 20 MHz away. Sharp edges in time are wide in frequency.

Two demands that fight

Be narrow in frequency, so you do not splatter over neighbours, and clean in time, so neighbouring symbols' tails contribute nothing at each sampling instant. Smearing between symbols is ISI, intersymbol interference, and it closes the eye as surely as noise. Narrowing a pulse in frequency lengthens it in time.

Nyquist's trick: zero at the sampling instants

A pulse need not be short, only zero at every other symbol's sampling instant. Such pulses are Nyquist pulses, and the usual one is the raised cosine, with one knob, the roll-off β, between 0 and 1:

βBandwidth neededTime-domain tailsIn practice
0exactly Rs, the minimumring forever, decay as 1/tunbuildable; brutally timing-sensitive
0.221.22 × Rsmodest3G/UMTS
0.351.35 × Rsshortcommon default; this repository's test waveforms
12 × Rsvery shortwasteful, very timing-tolerant

β buys timing tolerance with bandwidth. Occupied bandwidth = (1 + β) × symbol rate is the formula to keep.

Why root raised cosine, and why it is split in half

The Nyquist condition applies end to end: transmitter, channel and receiver together. So the transmitter gets a root raised cosine (RRC) and the receiver an identical one; the two square roots multiply back to the raised cosine.

The split is strictly better

The receiver's RRC is also the matched filter, shaped exactly like the transmitted pulse, which lesson 32 shows maximises SNR at the decision instant: zero ISI and the best receiver SNR. Every digital standard does it.

How you actually build one

Pulse shaping is upsampling followed by an FIR filter, lesson 27's decimator run backwards:

  1. Take one complex symbol per symbol period.
  2. Insert sps−1 zeros after each: the upsample step. sps is samples per symbol, usually 4.
  3. Run the result through the RRC filter, whose taps fill in the zeros with the pulse shape.

The filter's span is how many symbol periods of tail it keeps. Span s at sps samples per symbol is s×sps+1 taps; this repository's test waveforms use span 12 at 4 samples per symbol, 49 taps.

tools/modulation-gallery/waveforms.py — the shaper, in outlinePython
up = np.zeros(nsym*sps, dtype=complex)
up[::sps] = syms                  # one symbol, then sps-1 zeros
h  = rrc(0.35, 4, 12)             # alpha, sps, span: 49 taps
x  = np.convolve(up, h)           # the shaped waveform (the file shapes circularly)

In the fabric: a strobe once per symbol, a multiply-accumulate chain, and lesson 27's polyphase reuse so no multiplier is wasted on the zeros.

Try it — what will this shaping cost you?

The bandwidth you calculate is not the bandwidth you measure

The QPSK in docs/modulation-and-throughput.md runs at 61.44 MSPS, 4 samples per symbol, so Rs = 15.36 Msym/s and (1 + 0.35) × 15.36 predicts 20.7 MHz. The measurement says 17.96 MHz. The formula gives where the skirt reaches zero; the measurement is 99 % occupied bandwidth. A bandwidth figure is a number and a threshold; compare two with different thresholds and you conclude something false.

See the ISI for yourself

Generate QPSK with linear() in tools/modulation-gallery/waveforms.py, once with the RRC and once with a plain rectangle, and measure both with rx.py alongside it. The rectangle's points smear into radial streaks: that is ISI.

The gallery receives on a HackRF over the air, which needs a second radio and a band you may legally use. Without one, loop TX0 → 20 dB pad → RX0 on the board (affirm the port first: ./devkit tx-guard affirm 0); rx.py is data-aided and needs only the seed.

Check yourself: you need 2 Msym/s of 16-QAM inside a 2.5 MHz channel. What roll-off can you afford?

(1 + β) × 2 ≤ 2.5, so β ≤ 0.25. The price is longer tails, so timing recovery (lesson 31) works harder. The constellation does not enter: bandwidth is set by the symbol rate.

31

Synchronisation: finding the signal inside the samples

A receiver does not get symbols. It gets a stream of numbers with the symbols hidden at unknown times, phase and orientation. Recovering them is a whole discipline; here is enough to avoid the classic traps.

Three unknowns, in order

UnknownWhy it existsWhat it does if ignored
Timing — when is a symbol? Your sample clock and the transmitter's are unrelated, and the cable adds delay. You sample between symbols and get a smeared constellation.
Carrier phase — which way is up? The two oscillators have no agreed phase reference. The constellation is rotated by an arbitrary angle.
Carrier frequency — is it drifting? Two independent oscillators are never exactly equal. The constellation spins.

On a loopback, one of the three is free

Transmit and receive here share one 40 MHz reference, so their synthesisers produce equal frequencies. Measured here (QPSK raised to the fourth power shows a tone at four times the offset): 0.0 Hz.

Timing recovery

Matched-filter the stream, then decide which sample within each symbol period is the right one. The classic detectors are Gardner and Müller & Mueller, feedback loops that nudge the sampling instant until an error measure settles.

For an offline capture, try every candidate phase and pick the best. For a constant-envelope modulation like QPSK, the correct instant is the one with the least spread in magnitude:

brute-force timing searchPython
# z is the matched-filtered stream, sps samples per symbol
best = None
for phase in range(sps * OVERSAMPLE):
    s = z[phase::sps * OVERSAMPLE]
    # 1/kurtosis: 1.0 means perfectly constant magnitude
    q = mean(abs(s)**2)**2 / mean(abs(s)**4)
    if q > best: best, best_phase = q, phase

That number is diagnostic in itself. A clean lock reads 1.000; near 0.5 the symbols look Gaussian — the data is corrupted, not merely mistimed. That is how the DMA-starvation problem on this board was first identified.

Phase ambiguity, and the bug it causes

QPSK's four points are symmetric under 90° rotation, so the standard way to remove an unknown phase is to raise the symbols to the fourth power — which cancels the data — take the angle, and divide by four. The result can still be rotated by any multiple of 90°. That residue is phase ambiguity; real systems resolve it with a known preamble or by encoding data in phase changes.

The 45° version, which cost real time here — twice

Estimating phase as angle(mean(s⁴))/4 leaves the constellation at 0°, 90°, 180°, 270°, but a QPSK reference lattice conventionally sits at 45°, 135°, 225°, 315°. Every symbol is a half-quadrant off, and the error vector magnitude reads about 76% — which looks exactly like a broken transmitter. It was hit twice here, on two estimators, and both times the radio was blamed first.

The check: run your demodulator against the clean file you transmitted. If it does not read close to 0%, the bug is yours.

Check yourself: your EVM is 76% and the spectrum looks perfect. What do you suspect?

The analysis, not the radio. A clean spectrum means the signal arrived with its shape intact; 76% is the value a 45° lattice mismatch gives (|ej45° − 1| ≈ 0.765). Genuine corruption degrades the spectrum too.

32

Correlation, matched filters, and finding the packet at all

Lesson 31 assumed you knew a signal was there. This is the step before: deciding that something is there, and where it starts. It is also the operation this board's fabric is best at.

Correlation, in one sentence

Slide a known template along the received samples, and at each offset multiply the two point by point and add up the result. Where the template lines up with a real copy of itself, every product is positive and the sum shoots up; elsewhere it stays small. That is correlation — the Fourier transform of lesson 24 is the same operation with a sine wave as the template.

Why the answer is a filter, not a search

Correlating against a template is identical to running an FIR filter whose taps are that template, time-reversed and complex-conjugated. So you write the filter from lesson 26 and load different coefficients. That filter is the matched filter: of every possible filter, it gives the highest signal-to-noise ratio at the moment the template lines up — which is why lesson 30's receiver-side RRC is not arbitrary.

Where the gain comes from, and how much

Add N lined-up samples of signal and the amplitudes grow N times; add N samples of noise and they grow only as √N. The ratio improves by √N in amplitude — 10·log₁₀(N) dB in power. A 64-sample preamble buys 18 dB; a 1024-sample one 30 dB. That is how a signal below the noise floor is found: you accumulate it. It is the same trade as FFT length (lesson 24), noise bandwidth (lesson 25) and process gain (lesson 27).

Try it — how long must the preamble be?

What makes a good preamble

The template is usually a preamble, a known sequence at the front of every packet. It must look like itself at zero offset and like nothing at every other offset. That property is its autocorrelation, and the ideal is a single sharp spike — a thumbtack.

SequenceWhat it isWhy you would pick it
BarkerShort ±1 codes, lengths up to 13Off-peak never exceeds 1/N. Used by 802.11b at length 11.
m-sequence / PNOutput of a shift register with feedbackAny length, near-ideal thumbtack, and free in fabric — it is a shift register.
Zadoff–ChuA complex sequence of constant amplitudePerfect autocorrelation and a flat spectrum. LTE's synchronisation signal.
A repeated halfThe same block sent twiceThe receiver correlates the signal against itself — no template needed. See lesson 33.

Frequency offset eats your correlation length

Coherent accumulation assumes the phase stays put across the window. A frequency offset turns it by 2π·Δf·N/fs over N samples; past half a turn the second half of the window cancels the first, and a longer preamble makes detection worse. Keep the rotation under about a tenth of a turn: N < fs / (10·Δf). Untuned AD9361s can sit tens of kilohertz apart: at 5 MSPS and 10 kHz that is about 50 samples. Beyond that, correlate in shorter blocks and add magnitudes, losing several dB.

A correlation peak is not a detection

A raw peak grows with input level, so a strong interferer trips a fixed threshold before your packet does. Divide the correlator output by the energy in the same window: the normalised value runs 0 to 1 and lets a threshold survive a 40 dB change in level. Then set the threshold from the false-alarm rate you can live with, not from one capture that worked.

Why this belongs in the fabric

Detection is lesson 29's ideal fabric job: 61.44 MSPS in, a few events out, and fixed coefficients, so the multipliers can be specialised:

TemplateCost per tapA 64-tap complex correlator
Arbitrary complex taps4 real multiplies~256 DSP48s — will not fit on this board's 220
±1 taps (BPSK preamble)an add or a subtract0 DSP48s — an adder tree in LUTs
±1, ±j taps (QPSK)an add, a subtract and a swap0 DSP48s

A ±1 preamble is the difference between a correlator that fits in this XC7Z020 and one that does not.

The same filter is a radar

Matched filtering a chirp against itself is pulse compression. css() in tools/modulation-gallery/waveforms.py generates a chirp, and rx.py already correlates against the reference to find timing — project 4 in lesson 50.

A preamble detector you can run tonight: aircraft on 1090 MHz

Aircraft broadcast ADS-B messages on 1090 MHz: on/off pulses, each 1 µs bit carrying its pulse in the first half for a 1 and the second half for a 0 (pulse-position modulation). Every message opens with four pulses at 0, 1, 3.5 and 4.5 µs. ./devkit adsb finds them the way this lesson describes, with one twist: the receiver is tuned exactly to the carrier, so it correlates the magnitude against the pattern and the phase never matters. tools/adsb/demod.py scores every sample at once, as the four pulse windows against the twelve that must be quiet. Its checksum stage then plays the part of the decode that confirms a detection, which is how a correlator's false alarms are kept off the screen. Receive only; docs/adsb.md.

Check yourself: your link has −10 dB SNR and needs +8 dB to decode. How long a preamble, and what does that assume?

You need 18 dB of gain, so N = 101.8 ≈ 64 samples. That assumes the phase holds across all 64: at 5 MSPS, a frequency offset under fs/(10·N) = 7.8 kHz, which two free-running AD9361s will not reliably meet.

33

OFDM, and why this board finds it hard

Wi-Fi, LTE, 5G, DVB-T and DAB all use it. It is also the one waveform this board measurably struggles with, and the reason why is the most useful thing in this lesson.

The problem it solves

A signal arriving by two paths — direct, and bounced off a wall — arrives twice, slightly apart. That is multipath, and the delay between the first and last meaningful echo is the delay spread: tens to hundreds of nanoseconds indoors, microseconds outdoors. The echoes add in phase at some frequencies and cancel at others, so the channel becomes a comb with notches — a frequency-selective channel.

A single-carrier receiver needs an equaliser spanning the delay spread: at 20 Msym/s and 1 µs, a continuously retrained 20-tap adaptive filter.

The OFDM bargain

Instead of one carrier at 20 Msym/s, send 64 carriers at 312.5 ksym/s each. Each is so narrow that the channel across it is a single complex number, so equalisation collapses to one complex multiply per subcarrier. Everything else in OFDM is machinery to make that legal.

The FFT is the modulator

You do not build 64 oscillators. Write your 64 symbols into the bins of a frequency-domain array and take an inverse FFT: out comes the time-domain waveform with all 64 carriers on it. The receiver's forward FFT reads them back.

one OFDM symbol, 802.11a parametersPython
X      = np.zeros(64, dtype=complex)
X[idx] = qpsk_symbols          # 52 used bins; DC and the edges left empty
x      = np.fft.ifft(X) * np.sqrt(64)
out    = np.r_[x[-16:], x]     # cyclic prefix: the last 16 copied to the front

A 64-point FFT, 52 data subcarriers, a 16-sample cyclic prefix. The DC bin is empty because a direct-conversion receiver has its LO leakage there (lesson 11); the edges are a guard band. ofdm() in tools/modulation-gallery/waveforms.py uses the same 52 carriers on a 128-point FFT with a 32-sample prefix.

Orthogonality, and why the spacing is not negotiable

The subcarriers overlap but do not interfere, because each fits a whole number of cycles into the symbol period, so over that period every other subcarrier integrates to zero. That is orthogonality, and it forces Δf = 1 / Tsymbol. A timing error, frequency offset or sampling-clock mismatch breaks it and the subcarriers leak into each other — ICI (inter-carrier interference). OFDM is far more sensitive to frequency offset than single-carrier.

The cyclic prefix: the bit that looks like waste

Copy the last 16 samples of the symbol to the front and send 80 instead of 64 — 20 % of capacity. It buys two things:

  1. Echoes land in the guard, not in the next symbol. If the delay spread is shorter than the prefix, the tail of symbol n falls inside the prefix of symbol n+1, which the receiver discards.
  2. The channel becomes a multiply. The prefix makes the channel's linear convolution behave like a circular convolution over the FFT window, which is a plain multiplication in frequency. That makes the one-tap equaliser exact.

So CP duration > delay spread, and anything longer is capacity given away.

Try it — size an OFDM signal for this board

Equalisation, in the only place it is easy

Scatter a few pilot subcarriers of known value through the grid, or send one known symbol first. The channel at that subcarrier is H = Y / X; interpolate across the pilots, then recover every data subcarrier with X̂ = Y / H. One complex division per subcarrier per symbol. Lesson 34 is what a single-carrier receiver must do instead.

Why OFDM always arrives with error-correcting code attached

A channel notch does not degrade everything a little — it wipes out a few subcarriers, and dividing by a near-zero H amplifies their noise enormously. The fix is forward error correction plus interleaving: scramble the coded bits across subcarriers so a wiped-out group becomes scattered single-bit errors the code repairs. Hence COFDM — coded OFDM. Coding typically buys 4–6 dB, which a link budget (lesson 41) may count on; the uncoded test waveform here is not what any real system ships.

Measured on this board, and the honest explanation

At 61.44 MSPS over the 20 dB cable loopback, the test waveforms in docs/modulation-and-throughput.md give QPSK 2.17 % EVM, 16-QAM 2.24 % — and OFDM between 13 % and 51 %, run to run. That looks like a broken implementation. It is not:

Transmit backoffRX rmsOFDM EVM
0 dB−29.2 dBFS13.4 %
−6 dB−35.1 dBFS19.6 %
−12 dB−40.4 dBFS28.4 %
−18 dB−44.3 dBFS38.0 %

It gets steadily worse as the signal weakens: a noise-limited link. Clipping would have improved with backoff. OFDM simply delivers less average power.

PAPR: the price of adding 52 things together

Sum 52 independent subcarriers and the result is nearly Gaussian, with occasional large peaks. Measured here, the OFDM waveform's PAPR (peak-to-average power ratio) is 11.06 dB against 4.14 dB for QPSK. A transmitter is limited by its peak, so OFDM puts about 7 dB less average power on the link: same noise floor, less signal, worse EVM.

What was ruled out, and how

  • The analysis itself. Against the clean transmit file the demodulator reads 0.00 %. Always do this first.
  • Band-edge filter roll-off. Per-subcarrier EVM is only 1.2× worse at the edges; a filter problem would be strongly edge-weighted.
  • Cyclic prefix too short. Sweeping it from 16 to 128 samples barely moved the number; a cable has no delay spread.
  • The AD9361's tracking loops. Turning DC and quadrature tracking off made it worse.

If you wanted to build it in the fabric

Xilinx ships an FFT core; a 64-point pipelined-streaming complex FFT runs at 61.44 MSPS for a handful of DSP48s and one BRAM. Transmit: symbol mapper → write bins → IFFT → prepend prefix → the packer of lesson 15. Receive is that reversed, plus the synchroniser — which is where the work is. The standard trick is Schmidl & Cox: send a symbol whose two halves are identical and correlate the stream against a delayed copy of itself. The peak gives the symbol boundary, and its phase the frequency offset — lesson 32's machinery with no template.

Check yourself: indoors the delay spread is 200 ns. At 61.44 MSPS, is a 16-sample cyclic prefix enough?

16 / 61.44 MHz = 260 ns. Yes — with 60 ns of margin. The answer depends on the sample rate, not the FFT size: at 30.72 MSPS the same 16 samples give 521 ns.

34

Equalisation: undoing a channel that is not flat

A single-carrier receiver cannot make the channel one number per subcarrier, so it has to undo the channel directly — with a filter that designs itself.

What a channel does to your signal

Multipath (lesson 33) adds several delayed copies together. Written as samples, that is a convolution — the FIR filter of lesson 26, with coefficients nobody chose:

what arrivesthe channel, as a filter
y[n] = x[n]*h[0] + x[n-1]*h[1] + x[n-2]*h[2] + ... + noise
       |                |
       what you sent    the echo, half as strong, one sample late

The channel is an unwanted FIR filter, so the fix is another FIR filter that undoes it — plus three complications.

Three words before we go on

Tap
One coefficient of a filter. A "7-tap equaliser" remembers seven samples.
Pre-cursor / post-cursor
Energy from a symbol that lands before its own sampling instant, and after it. A symbol-spaced equaliser needs taps on both sides.
Convergence
An adaptive filter starts wrong and improves. Convergence is how long that takes, measured in symbols.

Complication one: you cannot simply invert it

The obvious equaliser is 1/H, the zero-forcing equaliser. In the notches H is nearly zero and 1/H enormous: it removes the ISI and multiplies the noise by a hundred. The standard answer is MMSE — minimum mean-square error — which minimises total error and so leaves a little ISI in deep notches rather than amplifying noise. Every practical equaliser is MMSE.

Complication two: you do not know the channel, and it changes

So the filter finds its own coefficients while running. The workhorse is LMS — least mean squares — in three lines:

LMS, per received samplethe whole algorithm
y = dot(w, x)          # filter: w is the taps, x the last N samples
e = d - y              # error: d is what the symbol should have been
w = w + mu * e * conj(x)   # nudge every tap toward reducing that error

After a few hundred symbols the taps settle into the MMSE solution on their own.

µ, the step size
Too large and the taps diverge; too small and the equaliser is still converging when the packet ends. Normalised LMS divides µ by the input power, so one choice works across a 40 dB range of levels — almost always what you want.
RLS
Recursive least squares: converges in tens of symbols, at N² arithmetic per sample.

Complication three: where does d come from?

ModeWhere d comes fromWhen
TrainingA known sequence sent at the start of the packet First. Reliable, but costs airtime.
Decision-directedThe nearest constellation point to what came out After training. Free, but only once the eye is open — feed it garbage and it converges to garbage.
Blind (CMA)Nothing. The constant-modulus algorithm pushes every output toward a fixed magnitude No training sequence and constant-amplitude modulation (PSK). Slow, and blind to phase.

The decision-feedback equaliser

A DFE uses a feed-forward filter for the pre-cursor ISI and a second filter that subtracts post-cursor ISI using symbols already decided — clean, noiseless points — so it cancels ISI without amplifying noise. The price is error propagation: one wrong decision helps produce the next. Excellent at high SNR, fragile at low SNR.

Try it — how big does the equaliser have to be, and where does it fit?

Where it goes on this board

An adaptive equaliser costs two complex multiply-accumulate chains per tap — one to filter, one to update — so an 11-tap complex equaliser is 88 real multiplies per input sample:

Running atMultiplies per secondDSP slices, time-shared on the 100 MHz clock
61.44 MSPS, in front of the decimator5.4 G ~55 of the 126 free
2 Msym/s, behind it176 M ~2

Equalisation belongs after decimation and timing recovery, at one or two samples per symbol — two DSP slices, or a software job on the ARM cores (lesson 29's rule).

Two ways an equaliser quietly destroys a working link

It adapts on noise
Between packets LMS converges to whatever minimises the error on noise. Gate adaptation on the detector from lesson 32: no correlation peak, no updating.
It fights the carrier recovery
A slowly rotating phase (lesson 31) looks like a slowly changing channel, so both loops chase the same error and can oscillate. Make the carrier loop much faster than the equaliser.

Make yourself a channel, because the cable has not got one

Coax is nearly a perfect channel. Convolve the QPSK test waveform with [1, 0.5] before transmitting and the EVM rx.py reports jumps. Then run a 5-tap LMS over the received symbols and watch it come back down.

Check yourself: why does an OFDM receiver need only one tap per subcarrier when a single-carrier receiver needs eleven?

The taps needed are set by delay spread measured in symbol periods. Split 20 Msym/s into 64 subcarriers and each symbol lasts 64 times longer, so 500 ns of echo is a small fraction of one symbol rather than ten.

35

Channel coding: buying decibels with redundancy

Lesson 33 said coding is worth 4 to 6 dB and lesson 41 spends them. This is where they come from and what they cost.

The idea, and the exchange rate

Send more bits than the message needs, arranged so the extra ones let the receiver find and repair wrong bits. The code rate is R = k/n: rate 1/2 sends every message bit as 2 transmitted bits. In return you get coding gain — the reduction in SNR needed for the same error rate. A rate-1/2, constraint-length-7 convolutional code with soft decisions buys about 5 dB, for a few thousand LUTs rather than a bigger amplifier and a licence.

Why there is a limit, and roughly where it is

Shannon's capacity formula says a channel of bandwidth B and signal-to-noise ratio S/N carries at most C = B · log₂(1 + S/N) bits per second, error-free, with a good enough code. Below about −1.6 dB of energy per bit against noise density, no code works; turbo and LDPC codes get within roughly 1 dB of that floor.

Soft decisions, and the free 2 dB most people throw away

Rounding the demodulator's output to the nearest symbol and handing the decoder a bit is a hard decision. Handing it the distance as well — "probably a 1, but only just" — is a soft decision, usually a log-likelihood ratio (LLR). Soft decisions are worth about 2 dB, for free.

  • Your demodulator must output LLRs, not bits. A slicer in the middle of the chain throws the information away permanently.
  • LLRs need the noise level scaled correctly (measure SNR, lesson 40).

The families, and which one to reach for

CodeWhat it isTypical gainWhere you meet it
CRCDetects errors; corrects nothing— Every packet. It tells the receiver to discard, which makes a retry protocol possible (lesson 37).
Hamming, BCHAlgebraic block codes over bits2–3 dB Headers, and anywhere short and cheap beats strong.
Reed–SolomonAlgebraic, over bytes3–5 dB Bursts. RS(255,223) repairs any 16 corrupted bytes. CDs, QR codes, DVB.
Convolutional + ViterbiA shift register and an optimal search back through its states~5 dB soft The workhorse. K=7, rate 1/2 is 802.11a, GPS and a hundred others.
Turbo, LDPCIterative: two decoders passing probabilities back and forth until they agreewithin ~1 dB of Shannon LTE, 5G, Wi-Fi, DVB-S2.
PolarProvably capacity-achieving, good at short lengths near Shannon5G control channels.

For a first link on this board: convolutional, rate 1/2, K=7, soft Viterbi. Best gain per unit effort, and Xilinx ships the decoder as IP.

Try it — what does the code cost, and what does it buy?

Interleaving, or the code does nothing

Every code in that table is designed against scattered errors. Real channels produce bursts — a fade, an interferer, a group of OFDM subcarriers in a notch — and 40 consecutive bad bits defeat a code that repairs 40 scattered ones easily. An interleaver writes the coded bits into a block in one order and reads them out in another, so neighbours in the codeword are far apart on the air and the burst is spread across many codewords. The code without the interleaver is close to useless.

The waterfall, and why a code can be worth nothing at all

Error rate against SNR for a coded link is flat and terrible, then falls off a cliff over about 1 dB — the waterfall. Above it the code is worth its full 5 dB; below it, slightly less than nothing, because you spent half your throughput on it. Coding does not rescue a link that is 10 dB short. It rescues one that is 3 dB short.

In the fabric

The encoder is a shift register and two XOR trees — a handful of LUTs, no DSP slices. The decoder is the work:

Viterbi, K=7
64 states, an add-compare-select per state per bit, and a traceback memory. A few thousand LUTs and a BRAM or two, easily fast enough at symbol rate.
Reed–Solomon
Finite-field arithmetic: awkward in software, natural in LUTs. Also available as IP.
LDPC
Hundreds of parallel messages iterating five to fifty times. Fits on this part only in small, slow configurations.

As always (lesson 29), put it at symbol rate behind the decimation.

Check yourself: your link is 3 dB short. Rate-1/2 coding gives 5 dB of gain — do you take it?

Usually, but rate 1/2 doubles the transmitted bits: either halve the data rate at the same bandwidth (2 dB ahead), or double the bandwidth — which raises the noise floor 3 dB (lesson 25) and occupies twice the spectrum. A rate-3/4 code (about 3.5 dB) is often the better trade.

36

Iterative decoding: how turbo and LDPC actually work

The mechanism behind codes within a decibel of Shannon is one idea — nodes exchanging opinions until they agree — and the three common ways to break it follow from one rule.

The currency: log-likelihood ratios

the log-likelihood ratioone number, two jobs
L(x) = ln[ P(x = 0 | y) / P(x = 1 | y) ]

  sign      the decision        positive means 0
  magnitude the confidence      0 means "no idea"

For BPSK in Gaussian noise, L = 2y/σ²: the received sample over the noise power. Gray-mapped QPSK is two independent BPSK channels. As log-ratios, independent evidence adds.

The scaling check worth writing into your test bench

For a rate-R code the channel LLRs should have variance σ²L = 8 · R · Eb/N0 and mean μL = σ²L/2 — the consistency condition, straight from L = 2y/σ². Histogram your LLRs once and check it.

LDPC: opinions on a graph

Draw the parity-check matrix as a Tanner graph: one variable node per coded bit, one check node per parity equation, an edge wherever the matrix has a 1. Every edge carries a number in both directions:

Variable node
Pools opinions: adds the channel LLR to every check node's message.
Check node
Enforces "these bits exclusive-or to zero": from how sure it is about the other bits in its equation, it says what the remaining one must be.

Iterate until the parity check passes — H·x̂ᵀ = 0 — or you run out of patience.

The one rule the whole field rests on: extrinsic information

A message sent out along an edge is computed from everything except what came in on that edge. Break that and a node hears its own opinion back as fresh evidence: confidence rises, the error stays, and the syndrome never clears — a bookkeeping bug that looks like an arithmetic one.

Turbo: two decoders, one interleaver

A turbo encoder is two small convolutional encoders seeing the same data, the second through an interleaver. Their soft-in soft-out decoders take turns, handing over only the part of their answer the other did not already know:

the handoffextrinsic information
L_in  = L_A + L_CH                 // what I was told, plus the channel
L_E   = L_out - L_in               // what I worked out that nobody told me
L(u)  = L_CH + L_E1 + deinterleave(L_E2)   // the final decision

LE is interleaved into the other decoder's prior, so it sees the errors in a different arrangement.

Polar: not iterative at all

Polar codes decode in one sweep, each decided bit removing its effect before the next — successive cancellation:

successive cancellationthe whole recursion
f(a, b) ~= sign(a) * sign(b) * min(|a|, |b|)    // a min-sum check node
g(a, b, s) = (-1)^s * a + b                     // a variable-node sum, sign-flipped
                                                // by the bits already decided

One bad early decision poisons the rest, so list decoding carries L candidate paths and lets a CRC pick the survivor — why 5G's polar codes include a CRC.

Sum-product, min-sum, and the one that matters in hardware

Check-node ruleWhat it computesCost
Sum-product2·atanh( ∏ tanh(L/2) ) — exacta transcendental function per edge
Min-sum∏sign · min|L| — an upper bounda comparator and a sign
Normalised min-summin-sum × αone multiply; α = 0.75 is a common default
Offset min-summax(|L| − β, 0)one subtract

Min-sum systematically overstates the check node's confidence, which is why scaling by α < 1 or subtracting an offset repairs it. One published 5G decoder in 28 nm reports an adjusted min-sum within 0.1 dB of floating-point sum-product.

Min-sum hides a bug that sum-product exposes

Scale every input LLR by a positive constant and min-sum gives the same decisions — min and + are positively homogeneous. Min-sum does not care what your noise-variance estimate is. Sum-product does, because tanh(L/2) is nonlinear, so a wrong σ² costs several tenths of a decibel the day you switch decoders. Over-scaling also fails: LLRs that saturate a 4-to-16-bit fixed-point datapath create an error floor that looks like a bad code.

How many iterations, and what stops you going further

MathWorks' 5G NR LDPC hardware decoder defaults to 8 iterations with a maximum of 63 (a six-bit field) and stops early when the syndrome clears. High-throughput LDPC chips use 3 to 5; DVB-S2X's performance tables assume 50.

More iterations stop helping at the error floor, where the curve flattens. Three different causes:

LDPC — trapping sets
Small groups of variable nodes whose local structure traps the decoder in a stable wrong answer. Richardson (2003) showed these, not low-weight codewords, dominate LDPC floors.
Turbo — genuine minimum distance
Small minimum distance that grows only logarithmically with interleaver length, so longer blocks do not lower the floor; interleaver design does, within that bound. LTE's quadratic permutation polynomial is that lever.
Yours — implementation
A mistuned α or β, or coarse quantisation, creates an artificial floor. The one you can fix, and the first to rule out.

EXIT charts: predicting the cliff without simulating it

Plot each constituent decoder's output mutual information against its input, one with axes swapped: decoding converges if and only if the two curves do not touch, so a code can be designed to a target SNR without simulating it (ten Brink, IEEE Transactions on Communications, 2001).

What the standards actually use

SystemCodeParameters worth knowing
5G NR dataQC-LDPC, two base graphs BG1 is 46×68 with K up to 8448; BG2 is 42×52 with K up to 3840. Lifting factor Z up to 384. BG2 for short or low-rate blocks.
5G NR controlPolar PDCCH, PBCH and uplink control — never the data channels. N ≤ 512 downlink, ≤ 1024 uplink.
LTE dataTurbo Two 8-state recursive encoders, mother rate 1/3, quadratic permutation polynomial interleaver, block sizes 40 to 6144.
LTE controlTail-biting convolutional Constraint length 7, generators 133/171/165 octal.
DVB-S2LDPC + outer BCH Frames of 64 800 or 16 200 bits — eleven code rates long, ten short. About 1 dB from the Shannon limit.
802.11n/acLDPC (optional) Twelve codes: N ∈ {648, 1296, 1944}, lifting 27/54/81, rates 1/2 to 5/6. The convolutional code is the mandatory one.

The puncturing that is not in the picture

5G's base graphs have 68 and 52 columns but transmit only 66·Z and 50·Z bits: the first two systematic columns are always punctured. The decoder must be handed 2·Z zero-valued LLRs at the front ("no information"). Forget them and it fails at every signal level — an off-by-2Z that looks like a broken code.

What this costs on this board

The XC7Z020 has 53 200 LUTs, 220 DSP slices and 140 block RAMs:

DecoderPublished costOn an XC7Z020
Viterbi, K=7, rate 1/2, soft
AMD's Viterbi Decoder IP, published for a Kintex-7 part
2208 LUT · 1720 FF · 0 DSP · 2 BRAM about 4 % of the part
802.11n LDPC, N=1944, at 420 Mb/s
published academic design, Kintex-7 XC7K410T
~45 800 LUT ~86 % of the part — nothing else fits beside it
5G NR LDPC, highly parallel
published academic design, Virtex-7
380 737 LUT 7.2× the whole device

An LDPC decoder's area scales with its throughput, not its block length — both LDPC rows are high-speed designs. A serial decoder for the same N=1944 code at a few megabits per second fits well; a fast one does not. AMD's SD-FEC hard block exists only on selected Zynq UltraScale+ RFSoC devices, and their soft-logic LDPC core does not support Zynq-7000.

So for this board: soft-decision Viterbi, K=7, about 5 dB. LDPC only if you can accept a slow decoder.

Try it — will the decoder keep up with the link?

Two more ways to lose a week

The sign convention is inverted
Symptom: the decoder converges to the bitwise complement of your message, or BER sits at 0.5 and L = -L fixes it. Cause: 3GPP, MATLAB and most vendor IP use positive ⇒ 0; plenty of textbooks and demodulators use the opposite, and nothing in the interface declares which.
You fed back the answer instead of the extrinsic part
Symptom: BER improves for one or two iterations, then freezes or gets worse. Cause: you passed Lout where you needed Lout − Lin.
Check yourself: your LDPC decoder's BER improves for two iterations and then stops. Where do you look?

At the extrinsic bookkeeping, first: "improves then freezes" is a node receiving its own message back. Then quantisation: a saturating LLR datapath produces the same shape; widen it and see whether the floor moves. Only then trapping sets — real, but almost never what is wrong with a decoder just written.

From a link to a network

37

Packets: framing, addressing, and everything above the symbols

So far every lesson has ended at "and now you have symbols". This one covers who they are for, where they start, whether they arrived intact, and what to do when they did not — and one number in it decides your whole architecture.

The layers, named once

Physical layer (PHY)
Symbols on and off the air. Lessons 29 to 35 are all PHY.
Media access (MAC)
Whose turn it is to transmit, framing, addressing, acknowledgements, retries. This lesson.
Everything above
Routing, ordering, congestion, applications. Usually somebody else's code.

The MAC/PHY boundary matters because it is also the boundary between "can live on the host" and "cannot".

What a frame is made of

a serviceable frame, in order of appearanceon the air
[ preamble ][ sync word ][ header ][ payload ................ ][ CRC ]
     |            |           |            |                      |
  AGC settles  "packet     length,     the actual bytes,      did any of
  timing and    starts     type,       scrambled and           this arrive
  carrier       HERE"      address     coded                   intact?
  recovery
Preamble
A known pattern long enough for gain control, timing recovery and carrier recovery (lesson 31) to converge before anything important arrives.
Sync word
The correlation template from lesson 32: it says exactly which sample the frame begins on.
Header
How long the payload is, what it contains, who it is for.
CRC
A checksum. It corrects nothing — it tells the receiver whether to believe the frame, which is what makes every retry scheme possible.

The header needs its own protection, and its own CRC

Corrupt one bit of the length field and the receiver reads the wrong number of symbols, then mis-frames everything that follows: one bit error becomes a lost sequence of frames. So every real standard codes the header more strongly than the payload and gives it a separate short CRC, checked before its values are used — 802.11's SIGNAL field is exactly this.

Scrambling: the step that looks pointless and is not

Payloads contain long runs of zeros. Sent literally, they give a waveform with no transitions, so lesson 31's timing recovery drifts and loses lock, and a constant symbol puts a spike in the spectrum and a DC offset where this receiver already has LO leakage (lesson 11).

The fix is a scrambler: XOR the data with a pseudo-random sequence from a shift register (lesson 32's m-sequence) before transmitting, and XOR with the same sequence at the far end. Nothing is hidden — the sequence is public — but the stream now looks random whatever the payload.

Whose turn is it? Media access on a shared medium

SchemeThe ruleWhat it needs
ALOHATransmit whenever. Retry after a random delay if unacknowledged. Almost nothing. Collapses above ~18 % utilisation.
CSMAListen first; transmit only if the channel is idle. A receiver that can report "busy" in microseconds.
TDMAEveryone gets a numbered slot. Shared time. Much easier than CSMA for one designer with two radios.
FDMAEveryone gets their own frequency. Spectrum. Trivial here — the transmit and receive local oscillators are independent, so the board can transmit on one frequency and listen on another.

The number that decides your architecture: turnaround time

CSMA and acknowledgements both need the radio to go from "heard the end of that frame" to "transmitting a reply" quickly. 802.11 allows 16 µs.

This board's host path: a capture buffer of 262 144 samples at 5 MSPS is 52 milliseconds of signal, and nothing in it can be examined until the buffer completes, with the network stack and scheduler still to come. That is over three orders of magnitude too slow.

So a latency-sensitive MAC cannot live on the host. Carrier sense, acknowledgement timing and slot boundaries belong in the fabric, where the answer is available the cycle after the samples arrive; the host gets the payloads.

Retries, and what makes them possible

Stop-and-wait
Send a frame, wait for an acknowledgement, send the next. Throughput is capped at one frame per round trip, however fast the link.
Sliding window
Keep several frames in flight and acknowledge by sequence number. Needed whenever the round trip is long compared with a frame — on this board's host path, always.
Sequence numbers
Not optional. A lost acknowledgement causes a re-send of a frame that did arrive, so without numbering the receiver silently duplicates data.

Try it — airtime, overhead and real throughput

What this board gives you, and what it does not

The transmit DMA can be cyclic (lesson 16): the hardware replays a buffer forever with no help from the host. That is perfect for a beacon — a frame repeating on a fixed schedule — and it is why the full-rate measurements in modulation-and-throughput.md could be taken at 61.44 MSPS when streaming gave up at 5.

It is useless for a conversation: different bytes each time means feeding the DMA from software, under the 31 MB/s plateau, with tens of milliseconds of latency.

The smallest useful thing to build

A one-way beacon: preamble, sync word, a 1-byte length, 32 bytes of payload, a CRC-16. Generate it in Python, shape it (lesson 30), load it once with iio_writedev -c and let the hardware repeat it. Then write the receiver: correlate for the sync word (lesson 32), slice, check the CRC, print the payload. No media access, no retries — and a complete link you understand every layer of.

Check yourself: why can a beacon run at 61.44 MSPS on this board while a two-way link struggles at 5?

A beacon's bytes never change, so cyclic mode replays one buffer with the host out of the loop — no samples cross the network once it is loaded.

A two-way link needs new bytes every frame and must react to what it hears, so every sample crosses the 31 MB/s bottleneck and every decision waits for a buffer to complete. The rate limit and the latency limit are the same constraint, and the way out of both is to move the reacting part into the fabric.

38

Beyond one link: protocols, routing, and what a network adds

A network means more than two nodes, more than one hop, and something above you that expects an ordered byte stream. Most of it you can inherit rather than write.

The layer model, honestly

The seven-layer OSI model (ITU-T X.200) is almost never implemented. What is deployed is the four layers of RFC 1122: application, transport, internet, link. And even those leak — RFC 3439's "Layering Considered Harmful": "multiplexing and segmentation both hide vital information that lower layers may need to optimize their performance."

What you write, and what you get for free

You write
The physical layer (lessons 29–36), framing and media access (lesson 37), and optionally link-layer retransmission.
Linux gives you
IP, ICMP, UDP, TCP, routing tables, sockets — free, the moment your program presents a network interface. The usual route is a TUN device (TUN carries IP packets, TAP Ethernet frames; a subnetwork under IP wants TUN). Your program reads packets out of it, transmits them, and writes received ones back in.

So you are building a subnetwork underneath IP. RFC 3819, "Advice for Internet Subnetwork Designers", is the most useful thing to read after this lesson.

Addressing: who, and where

A MAC address says who: flat, permanent, 48 bits, the top 24 the manufacturer's OUI. A network address says where, so prefixes can be aggregated (RFC 4632) instead of the routing table holding one entry per device.

For a small radio network, copy 802.15.4: a 16-bit short address plus a 16-bit network identifier — 65 534 usable nodes once 0xFFFF is broadcast and 0xFFFE "not assigned yet". Every byte of header is airtime.

Frame length: the trap that looks like a broken radio

A frame survives only if every bit in it survives:

packet error rate from bit error rateRFC 3819 §8.5.3
p = 1 - (1 - BER)^(FRAME_SIZE * 8)

and for BER * FRAME_SIZE * 8 << 1,   p ~= BER * FRAME_SIZE * 8
Bit error rate32-byte frame127-byte512-byte1500-byte
10−60.03 %0.10 %0.41 %1.19 %
10−50.26 %1.01 %4.01 %11.3 %
10−42.53 %9.66 %33.6 %69.9 %

Same radio, same noise — and a 1500-byte frame loses eleven percent where a 127-byte frame loses one. Frame length is a link-budget decision. The table assumes independent bit errors; on a fading link errors arrive in bursts, so these figures are upper bounds on loss — and bursts are why interleaving (lesson 35) exists.

The other way: a 1500-byte frame on a 19.2 kb/s link is 625 ms of serialisation delay (RFC 3819). Short frames cost header overhead; long frames cost loss and latency.

Fragmentation multiplies the loss instead of hiding it

Split a datagram into N fragments and it survives only if all of them do. At 5 % per-fragment loss, a 16-fragment datagram arrives 44 % of the time; in 6LoWPAN "the whole datagram fails when one fragment is not delivered" (RFC 8931). A node with "only enough memory for 1–3 reassembly buffers" (RFC 8930) also holds a buffer until timeout for each lost fragment, dropping unrelated traffic.

The black hole: small packets work, big ones vanish

Path MTU discovery (RFC 1191) relies on ICMP coming back. When it is filtered (RFC 2923) the symptom looks exactly like a radio fault: "pings and some interactive TCP connections to the destination host work. Bulk transfers fail with the first large packet." The fix is RFC 8899 — probe from the packetization layer instead of trusting ICMP.

Routing, when the nodes move

ProtocolStatusKindWorth knowing
OLSR (RFC 3626)ExperimentalProactive link-state HELLO 2 s, TC 5 s; multipoint relays cut flooding. OLSRv2 (RFC 7181) is Standards Track.
AODV (RFC 3561)ExperimentalReactive Finds a route only when needed; destination sequence numbers give loop-freedom.
Babel (RFC 8966)Standards TrackDistance-vector, loop-avoiding Hello every 4 s, ETX metric on wireless, detects an outage within 1.5 to 3.5 Hello intervals.
RPL (RFC 6550)Standards TrackProactive, tree-shaped Built for many-to-one collection; in non-storing mode every packet goes via the root.

For a small mesh of these boards, start with Babel. It keeps little state, ships in Linux distributions, and uses ETX — a metric that counts delivery attempts rather than hops, so it prefers a good three-hop path to a terrible one-hop one. Use RPL only for one collector, and OLSR or AODV only to interoperate.

Try it — what does an extra hop cost?

TCP over a radio link, and why it disappoints

TCP's congestion control uses loss as its signal (RFC 5681), and a bit error is indistinguishable from a congested queue — so every corrupted frame makes TCP slow down, precisely the wrong response. The Mathis formula (restated in RFC 3819) gives steady-state throughput under random loss:

the Mathis equationC = 0.93, the constant RFC 3819 uses
BW = C * MSS / (RTT * sqrt(p))

A hundredfold worse loss costs only tenfold in throughput — and RTT is in the denominator.

Put this board's own numbers in, and the result is sobering

A 262 144-sample buffer at 5 MSPS is 52.4 ms one way, so a round trip starts at about 105 ms. With a 1460-byte MSS:

Packet lossTCP throughput, Mathis
0.1 %3.28 Mbit/s
1 %1.04 Mbit/s
5 %463 kbit/s

The bottom two rows are optimistic (RFC 3819).

A second ceiling: without window scaling (RFC 7323) TCP has at most 64 KiB in flight — at 105 ms RTT that is 5.0 Mbit/s, full stop. Both limits come from buffer latency, not the radio: move work into the fabric, or stop expecting TCP to be the transport.

Retransmit, or code? Both, and it is called HARQ

  • FEC wins when feedback is expensive or impossible — broadcast, satellite, anything one-way (RFC 3453).
  • ARQ wins when the loop is short. Link-layer ARQ "has a faster control loop than TCP's acknowledgement control loop" (RFC 3366), so it repairs the error before TCP notices.
  • Hybrid ARQ does both. Type II sends incremental redundancy rather than repeats; in type III each retransmission is self-decodable (3GPP TR 25.848).

LTE reference values: a HARQ round trip of 8 ms, 8 processes in parallel so the link never idles, redundancy versions 0, 2, 3, 1. 5G NR uses 16 processes.

Two retransmission loops fighting each other

Link-layer ARQ under TCP means two loops reacting to one event: link retries raise latency, TCP retransmits a packet the link is still retrying, and "the link layer may even have multiple copies of the same packet in the same link queue" (RFC 3819). RFC 3366 calls 2 to 5 attempts low persistency, allowing more only where total transmission time is "much less than 100 ms" — and this board's 52 ms of one-way host buffering has spent half of that before you retry once.

Three stacks worth stealing from

LoRaWAN — the duty cycle is the design
In the 868.0–868.6 MHz sub-band the European regulator allows a 1 % duty cycle — 36 s per rolling hour (other sub-bands of 863–870 MHz get 0.1 % or 10 %). A 23-byte payload at SF12/125 kHz takes about 1483 ms of airtime, at SF7 61.7 ms: 24 uplinks per hour against 583, for one parameter. Class A devices open two receive windows after each uplink, at 1 s and 2 s; that is the entire downlink opportunity.
802.15.4 + 6LoWPAN — the octet budget
RFC 4944 §4: a 127-octet packet, minus up to 25 of MAC overhead, minus 21 for AES-CCM-128, minus a 40-octet IPv6 header, minus UDP's 8, leaves 33 octets for your application. Against IPv6's 1280-octet minimum MTU, that gap is why the 6LoWPAN adaptation layer exists; its header compression gets IPv6 down to two octets for link-local traffic.
Wi-SUN FAN — sub-GHz mesh, like this board
2-FSK at 50 to 300 kbit/s (FAN 1.0), OFDM up to 2.4 Mbit/s (FAN 1.1), in the 863–870 MHz and 902–928 MHz bands this board covers, with RPL non-storing mode mandatory and channel hopping.

Your CRC is weaker than the datasheet implies

A CRC's detection properties "diminish with increasing frame size", and a new subnetwork should be "at least as strong as the 32-bit CRC" (RFC 3819). A 16-bit CRC over a 1500-byte frame is not doing the job you think. Even a good one lets errors through, which is why end-to-end checksums sit on top of link-layer ones.

Check yourself: your link has a 10−5 bit error rate and you are sending 1500-byte frames over TCP. What do you change first?

Not the frame size — that is the trap. Shrinking frames cuts the loss rate (11.3 % at 1500 bytes, 1 % at 127), but the MSS shrinks with the frame. Throughput goes as MSS/√p and p roughly as the frame length, so throughput scales as √L:

FrameLossMSSTCP throughput
1500 B11.3 %1460308 kbit/s
512 B4.0 %472167 kbit/s
127 B1.0 %8761 kbit/s

Put error recovery below TCP. Link-layer ARQ or FEC keeps the 1460-byte segment and hands TCP a link that looks clean — what RFC 3819 recommends, and why cellular standards put HARQ under IP. Small frames still win on latency and single-message delivery odds, just not on TCP throughput.

39

Security: the part a working link still does not have

Everything built so far transmits in clear, accepts any frame that passes a CRC, and cannot tell your transmitter from anyone else's. This lesson is what has to be added on top.

Four properties, and what each one's absence looks like

PropertyWhat it meansWithout it, on your link
Confidentialitydata is not disclosed to anyone not authorised to know it anyone with an SDR in range reads your payload
Integritydata has not been changed in an unauthorised or accidental way bits are altered in flight and the receiver accepts the altered frame
Authenticity
(data origin authentication)
the source of the data really is who it claims to be any transmitter can inject frames your receiver treats as yours
Freshnessthis is not a replay of an earlier exchange a recorded valid frame, sent again later, is acted on again — no key required

Those four you can buy with cryptography. A fifth — availability — you largely cannot, and a radio is most exposed to it (see jamming, below).

Encryption without authentication is worse than it sounds

Counter-mode ciphertext (AES-CTR and similar) is malleable: flipping a ciphertext bit flips the same plaintext bit. An attacker who knows what a field says can change it without the key.

A CRC does not stop it. A CRC is linear over exclusive-or — "a general property of all CRC checksums" — so you can compute the CRC change that matches your data change. That is what killed WEP: CRCs "are only designed to protect against random bit errors, not intentional forgeries" (NIST SP 800-97 §3.2.3). Lesson 37's CRC is error detection, not integrity, and not authentication.

AEAD: one key, one call, both jobs

The modern answer is a single mode called AEAD — authenticated encryption with associated data. You hand it a key, a nonce, the payload to encrypt, and any header fields that must be authenticated but not hidden; it returns ciphertext plus an authentication tag.

AES-CCMAES-GCM
Specified inNIST SP 800-38CNIST SP 800-38D
Tag lengths32 to 128 bits, in 16-bit steps128, 120, 112, 104, 96 bits — 64 or 32 only under the restrictions in Appendix C
CharacterCTR + CBC-MAC; two passes; small and simpleCTR + GHASH; parallelisable; fast in hardware
Where you meet it802.11 CCMP, 802.15.4, BluetoothTLS, IPsec, 802.11 GCMP

Parameters worth copying: 802.11 CCMP-128 uses AES-128 with an 8-byte tag and a 48-bit packet number that is both the replay counter and the varying part of the nonce. 802.15.4 offers 4-, 8- or 16-byte tags; which suites are mandatory depends on the edition (2003 vs 2006 and later), so check yours.

The nonce rule is not a guideline

For GCM, the probability of ever using the same key and IV twice "shall be no greater than 2−32" — "in practice, this requirement is almost as important as the secrecy of the key" (NIST). Repeat one and the authentication key becomes recoverable, so authentication is lost and the malleability above comes straight back: one repeated nonce unravels the whole key. CCM has the same rule.

Replay protection is a separate thing you must add

AEAD does not give you replay protection. A replayed frame is a genuine frame with a genuine tag; GCM "does not inherently prevent" it (NIST). The fix is a counter, carried in the frame and authenticated:

IPsec ESP
A 32-bit sequence number (64-bit extended), a receive window of at least 32 packets (64 recommended), and the counter must not wrap — you rekey instead.
802.11
The 48-bit packet number, monotonic for the life of the temporal key.
The dependency nobody expects
ESP forbids anti-replay without integrity, because otherwise the sequence number is forgeable. Replay protection is built on authentication.

The counter must survive a power cut, and on this board that means flash

The most common way an embedded radio ends up insecure while appearing to work: counters reset to 0 at boot, so nonces are reused, and the product "appears to work but actually fails to secure communications" (Sastry and Wagner, 802.15.4). LoRaWAN 1.0.4 made it normative: "ABP end-devices SHALL store the frame counters persistently".

Writing flash every frame is slow and wears it, so use a lease: write a counter value well ahead of where you are, count from RAM below it, and on reboot skip past the whole leased block. You lose a few thousand values per power cycle and never reuse one.

On this board the persistent partition on the QSPI flash is /mnt/jffs2; reflashing the kernel, device tree and bitstream leaves it untouched, on either target. (On the modern target the Debian root on the SD card is writable too, but rewriting the card wipes it.)

Keys: the part that is actually hard

Pre-shared
One key, burned in. A single compromise is total, with no way to revoke. Fine for a closed experiment, never for a product.
Derived from a root key
What LoRaWAN does: root keys assigned at manufacture, a join exchange carrying nonces from both ends, session keys derived from both. Version 1.1 splits the root into network and application keys so the operator cannot read your payloads. The join nonce is a persistent counter, not random, because random nonces can be replayed unless the network remembers every one ever used.
Certificate-based
What enterprise Wi-Fi does. Real revocation and identity, and infrastructure that is its own project.

Forward secrecy, and where LoRaWAN does not have it

Forward secrecy means compromising the long-term key does not expose earlier session keys. LoRaWAN's session keys are a deterministic AES function of the root key and two nonces, so whoever records traffic and later obtains the root key decrypts all of it — a deliberate trade for small devices, but one to notice you are making.

Try it — what does the protection cost, and when does the counter wrap?

Jamming: the attack cryptography cannot answer

Encryption protects the content. Nothing protects the channel from someone transmitting into it.

KindWhat it doesWhat it looks like to you
Barragenoise-like energy across the whole occupied band, continuouslythe noise floor rises, flat
Partial-bandthe same total power concentrated into a fraction of the bandworse than barrage — it degrades error rate far more efficiently
Tonea single carrier, correlated rather than noise-likea spur that will not go away, and which your AGC obeys
Reactive / followerlistens, then transmits only when it hears you — and can follow a hopping signalthe link works until it matters
Direct sequence
Processing gain equals the spreading factor — lesson 32's correlation gain, pointed at an interferer. The cost is proportional occupied bandwidth, plus acquisition hardware.
Frequency hopping
Processing gain equals the number of hop channels, against the wrong jammer: 100 channels looks like 20 dB, yet one spot jammer can still force an error rate around 10−2, and a follower jammer negates it.
Coding plus interleaving
Lesson 35's pairing: interleaving spreads a partial-band burst so the code can repair it.

Spoofing, and the most instructive example in the world

The GPS civil signal is an unauthenticated broadcast: the C/A code is published, and the navigation message has only a Hamming parity code — error detection, not cryptography. Nothing short of cryptographic authentication stops a sophisticated spoofer, which is what Galileo's OSNMA now adds. Your link is the same until you add authentication: anything that receives it will believe anything that sounds like it.

Encrypted does not mean invisible

Traffic analysis infers presence, volume, timing and size "even if flows are encrypted" (RFC 6973), and on radio the transmission itself reveals that a transmitter exists and roughly where. The countermeasures — spreading, minimum power (lesson 41), directivity, traffic padding — all cost margin, throughput or energy.

Physical-layer security: what it claims, and whether to use it

Wyner's wiretap model gives a secrecy capacity when the eavesdropper's channel is worse, and channel reciprocity lets two ends derive a key from fading a third party (more than about half a wavelength away) does not see. It is not a substitute for cryptography:

  • Key generation needs the channel to change; in a static room a 256-bit key takes minutes.
  • Published active attacks on real hardware have recovered a large fraction of the key bits, and an adversary with more antennas can drive the secrecy rate to zero.
  • No standards body endorses it: 5G mandates AES, NIST requires approved random bit generators.

Legality and security are different regimes — and on this board they can conflict

Spectrum rules impose no duty to secure a link, and unlicensed operation is conditional: no claim to a frequency, interference must be accepted, and you stop when told. In the US amateur service, messages "encoded for the purpose of obscuring their meaning" are prohibited with narrow exceptions — so a legal ham-band link may not be legal to encrypt. Authentication does not obscure meaning and is the workable path. Check your own jurisdiction.

Three traps, all of them common

Inventing your own construction
Including combining standard primitives in your own order. Use a single standard AEAD mode where you need both encryption and authentication (NIST SP 800-175B).
Reusing a nonce across reboots
The product works perfectly while unprotected. There is no symptom.
Reusing one key in two contexts
Two independent counters under one key collide, and the XOR of two ciphertexts under one keystream breaks confidentiality. The nonce state should never be separated from the key.

Where the quotations in this lesson come from

ForRead
The four property definitionsRFC 4949, Internet Security Glossary
Counter-mode malleability; the nonce rule; "GCM does not prevent replay" NIST SP 800-38D, §8 and Appendices A and D
CCM tag lengths and the nonce/payload tradeoffNIST SP 800-38C
Why a CRC cannot protect integrity Borisov, Goldberg and Wagner, Intercepting Mobile Communications (MOBICOM 2001) — "a general property of all CRC checksums"
WEP's failure, and CCMP's parametersNIST SP 800-97
Sequence numbers, windows, and why replay protection needs integrityRFC 4303 (IPsec ESP)
Counters that must survive a reboot; the flash-lease pattern Sastry and Wagner, Security Considerations for IEEE 802.15.4 Networks (WiSe 2004)
Key hierarchy, OTAA vs ABP, persistent countersLoRaWAN L2 1.0.4 and 1.1
Jamming taxonomy; spreading and jamming margin Lichtman et al., A Communications Jamming Taxonomy (IEEE S&P 2016); Pickholtz, Schilling and Milstein (IEEE Trans. Comm. 1982)
That the GPS civil signal is unauthenticatedIS-GPS-200 — the word does not appear in it
Traffic analysis "even if flows are encrypted"RFC 6973 §3
Don't build your own constructionNIST SP 800-175B §4.3
Unlicensed operation; amateur encryption47 CFR §15.5 and §97.113(a)(4)
Check yourself: you add AES-GCM to your link. Which of the four properties do you now have?

Three. Confidentiality, integrity and authenticity — provided the tag is checked before the payload is used, and every nonce under that key is unique.

Not freshness. A replayed frame has a valid tag. You need an authenticated, monotonic counter with a receive window that survives a power cut — on this board, a lease in /mnt/jffs2.

And not availability: someone transmitting into your band stops your link whatever mode you chose; the answers there are spreading, coding and interleaving, not keys.

Measuring, and getting on the air

40

Measuring what you built

Six numbers describe an RF system. Knowing which one answers your question, and how to get it honestly from this board, separates a measurement from a screenshot.

The vocabulary, once

SNR
Signal to noise ratio. Wanted power over noise power, in dB.
THD
Total harmonic distortion: energy at multiples of your test tone. Measures non-linearity, not noise.
SINAD
Signal to noise and distortion: SNR and THD combined, because in practice both degrade you.
ENOB
Effective number of bits. SINAD expressed as converter bits, via the 6.02N + 1.76 relationship from the fixed-point lesson. What your 12-bit converter really delivers.
SFDR
Spurious-free dynamic range: the gap between your signal and the largest single unwanted spike. Decides whether a weak signal is findable next to a strong one.
EVM
Error vector magnitude. For modulated signals, the average distance from where symbols landed to where they should be, as a percentage. The summary figure for a link.

Which one answers which question

Your questionMeasure
Can I hear a weak signal at all?SNR, and the noise floor
Can I hear it next to a strong one?SFDR
Is my amplifier being driven too hard?THD, or a two-tone IMD3 test
What is my converter actually worth?ENOB
Will this modulation decode?EVM
Is my IQ balance any good?Image rejection

Measured on this board

Through a cable from TX2 to RX2 with a 20 dB attenuator, at 900 MHz:

FigureResultConditions
Carrier SNR71–90 dBCW tone, depending on rate
Image rejection43–76 dBcimproves at higher rates
IMD356 dBctwo-tone, 61.44 MSPS
EVM, QPSK1.3–2.2%5 to 61.44 MSPS
EVM, 16-QAM1.6–2.3%same

Three ways to measure a number that is not true

  • A test tone at a simple fraction of the sample rate. Quantisation error then correlates with the signal and piles into harmonics, so SFDR reads far worse than the hardware is. Use an awkward, ideally prime, frequency.
  • An unstated FFT length. Longer transforms lower the apparent floor; always say how long it was.
  • A normalised plot. Normalising hides absolute level. On this board a muted transmitter once looked like "a spray of components" purely because the plot was normalised. Compare against a muted reference in absolute dBFS.

Measuring it again, by script

A number measured once, by hand, is an anecdote. Measured by a script, it can be measured again after a firmware change, on a second board, or tomorrow, under the same conditions. The devkit's automation server is for that: a small server on the board (gRPC, port 7020) and a Python client on your PC. The script asks for the task, such as "868 MHz, 4.8 MSPS, play this tone on TX1 and record RX1 while it plays", and the server does the board's part, including every transmit-safety rule from the rules lesson. It refuses to raise a transmitter that nobody has vouched for with ./devkit tx-guard affirm, and it mutes before it lets go of the buffer.

# run from: tools/automation, as: .venv/bin/python tone.py
import numpy as np
from fishball_automation.client import Fishball
tone = 0.5 * 32767 * np.exp(2j * np.pi * 1e6 * np.arange(76_800) / 4_800_000)   # 1 MHz, 16 000 whole cycles
with Fishball("fishball.local") as board:
    board.configure(sample_rate_hz=4_800_000, rx_lo_hz=868_000_000, tx_lo_hz=868_000_000)
    w = board.upload_waveform(tone)            # once; played by its id
    rec = board.transmit_capture(w, 1 << 20, tx_channels=[1], rx_channels=[1],
                                 attenuation_db=-40, pad_db=20, path="tone")

Measured on this board with that call, through a 20 dB attenuator, the tone landed 0.12 Hz from where it was sent. A sweep of both loopbacks across 14 frequencies from 100 MHz to 5.8 GHz takes 15 seconds: the complete script and its output.

Two things a script finds that one measurement hides

  • Not every figure repeats. The loopback sweep, run twice a few minutes apart: the tone level moved by at most 1.2 dB, but the image moved by up to 14.5 dB at the same frequency. Measure image, LO leakage and spurs several times and report the worst.
  • Transmit and receive do not start together. This design has no shared start for the transmit and receive DMA, so where a pulse lands in a capture changes from call to call (samples 4295, 7372 and 4439 in three calls). For timing, record a reference: loop the second transmitter into the second receiver and measure against it. The difference between the two receivers held at −0.002 samples in all three.
Check yourself: SNR is excellent but EVM is terrible. What is wrong?

Something structural, not noise: a synchronisation or convention error in your demodulator, non-linearity distorting the constellation without raising the floor, or IQ imbalance skewing it. SNR only measures power ratios; EVM measures whether the symbols are where they should be, and plenty of impairments move symbols without adding noise.

41

Link budgets: will it actually work over the air?

Once an antenna is involved, one calculation decides whether the link exists at all, and because every term is in decibels it is a single column of addition.

The whole calculation

the link budgetall terms in dB
  received power   = TX power + TX antenna gain - cable loss
                     - path loss + RX antenna gain      [dBm]

  noise floor      = -174 + 10*log10(bandwidth_Hz) + noise figure   [dBm]

  SNR              = received power - noise floor       [dB]
  margin           = SNR - SNR the demodulator needs    [dB]

A positive margin means it works as assumed.

Path loss, and what it really is

In free space a wave spreads over an ever-larger sphere and a receiving antenna catches an ever-smaller share. Nothing is absorbed. That is free-space path loss:

free-space path lossdB
FSPL = 32.44 + 20*log10(distance_km) + 20*log10(frequency_MHz)

Double the distance and you lose 6 dB. Double the frequency and you lose another 6 dB. The air is not more absorbent at 2.4 GHz; a fixed-gain antenna is physically smaller at the higher frequency, so it catches less of the sphere.

Free space is the optimistic case, and you are rarely in it

FSPL assumes nothing between the antennas. Real environments obey a steeper law, distance raised to an exponent n:

EnvironmentExponent nLoss per doubling of distance
Free space2.06 dB
Open outdoor, ground reflection2.5–37.5–9 dB
Indoors, same floor3–49–12 dB
Indoors, through floors4–612–18 dB

At 100 m, an exponent of 3.5 instead of 2 costs an extra 30 dB. This is why budgets that look comfortable on paper fail in a building.

Antenna gain is not amplification

What it is
A statement about shape. 6 dBi means four times the power of an isotropic radiator in the favoured direction, by radiating less everywhere else.
dBi vs dBd
dBi is referenced to an ideal isotropic radiator; dBd to a half-wave dipole. dBd + 2.15 = dBi. Datasheets mix them, because dBi is the bigger number.
The consequence
Gain is directivity, so it comes with a beamwidth.

How much SNR does the demodulator actually need?

Roughly, for an uncoded link at a bit error rate around 10−5, measured across the occupied bandwidth:

ModulationBits per symbolSNR needed (uncoded)Rough EVM equivalent
BPSK1~10 dB30 %
QPSK2~13 dB22 %
16-QAM4~20 dB10 %
64-QAM6~26 dB5 %
256-QAM8~32 dB2.5 %

Each extra bit per symbol costs about 3 dB, not 6. Lesson 9's 6 dB is per bit per dimension; QAM spends each new bit across two, I and Q. Forward error correction (lesson 35) hands 4–6 dB back, which is why every real system uses it.

Try it — a full link budget for this board

A worked example on this hardware

900 MHz, 100 m of clear line of sight, a 2 dBi whip at each end, 5 MHz of bandwidth, QPSK:

TermValueWhere it came from
TX power+19 dBmThis board flat out — a capped estimate, never metered
Antenna gains+4 dB2 dBi each end
Free-space path loss−71.5 dB32.44 + 20log₁₀(0.1) + 20log₁₀(900)
Received power−48.5 dBmthe sum of the three above
Thermal noise in 5 MHz−107.0 dBm−174 + 10log₁₀(5×10⁶)
Noise figure+5 dBAD9361, typical
Noise floor−102.0 dBm
SNR53.5 dB
QPSK needs13 dBtable above
Margin+40.5 dBcomfortable — in free space

Indoors at an exponent of 3.5 you lose 30 dB of that, and a body in the way another 10. The budget tells you whether a link is plausible, not whether it works.

Fade margin, and why 10 dB is the smallest number worth planning for

Multipath makes the received level fade as things move. Practical designs carry 10–20 dB of fade margin, mobile systems more. If you cannot afford it: narrow the bandwidth (3 dB per halving), drop to a simpler modulation (3 dB per bit), add coding (4–6 dB), lengthen the preamble (lesson 32), or accept a shorter range.

Before the antenna goes on

An antenna makes your signal everybody's problem, and most of this board's tuning range belongs to somebody with a licence, including the FM broadcast band. The board reaches about +19 dBm. Test into a dummy load or a cable first, and check what you may transmit, where and at what power before anything radiates. The repository's docs/transmitter-safety.md protects your receiver; the law protects everybody else's.

The MCP server's transmit tools refuse frequencies outside the EU licence-free bands (433, 868, 2400 and 5800 MHz) or over a band's power limit, unless you give an override_reason or pass force=true. It only advises; you are the one transmitting.

Check yourself: the same link at 2.4 GHz instead of 900 MHz. What changes, and by how much?

Path loss rises by 20·log₁₀(2400/900) = 8.5 dB, so the margin falls from +40.5 to +32 dB. Nothing else moves. But antennas of the same physical size have more gain at higher frequency, so a real comparison often wins most of that back; fixed antenna gain is the assumption that makes frequency look like the enemy.

42

Antennas and the RF front end: what happens after the SMA

"Transmit power" and "antenna gain" are hardware, and on this board some of that hardware is missing. No amount of Verilog fixes this part of the chain.

Fifty ohms, and why anything has an impedance at all

Once the wavelength is comparable to the cable, a signal reaching the far end meets an impedance. If it does not match the cable's own characteristic impedance, part of the wave reflects. Radio standardises on 50 Ω throughout so that it does not.

Three names for one measurement

VSWR
Voltage standing wave ratio. 1:1 is perfect, 2:1 ordinary, 3:1 poor.
Return loss
The same in decibels: how far below the forward wave the reflected one is. Bigger is better. 2:1 VSWR is 9.5 dB.
S11
The same again, as a complex number from a vector network analyser. Its phase tells you which way the mismatch is, which is what lets you design the fix.

At 2:1 about 11 % of your power comes back, only 0.5 dB. At 3:1 it is 25 %, and at 6:1 half your transmit power heads back into the amplifier.

Try it — antenna dimensions and mismatch loss

The antenna, in the three facts that matter

It is a resonant length
A quarter-wave monopole is about a quarter of the wavelength, a few percent shorter: at 900 MHz about 78 mm. The wrong length moves the impedance off 50 Ω and power reflects.
A monopole needs a ground plane
It is half a dipole; the other half is its mirror image in the ground plane. A whip on a small board with no ground plane is a worse antenna than the datasheet's.
Small is bad, unavoidably
Much smaller than a quarter wave still matches, but only over a narrow band and with more loss. Bandwidth, size and efficiency trade by physical law, which is why a small device's antenna is nearly always the weakest part of the link.

Polarisation: 20 dB that is nowhere in the link budget

Turn one of two vertical whips horizontal and, in clean line of sight, coupling drops by 20 dB or more. If either end moves, use circular polarisation at one end (3 dB always, instead of 20 dB sometimes) or diversity (lesson 46). Indoors, scattering softens the effect, so the failure is worse outdoors.

The front end, and what this board has

From the parts list in docs/hardware.md:

this board, per channelthe RF side
receive    RX1A/RX2A  -->  balun (T1-T4)  -->  AD9361 differential RF input

transmit   AD9361  -->  balun  -->  PGA-102+ (U12/U13, ~15.7 dB)  -->  TX1A/TX2A

On transmit the balun sits before the amplifier, so it handles milliwatts; the TX1A_I / TX1A_O nets either side of U12 are that boundary. There is no external band filter in either direction. The AD9361's front end is wideband by design (70 MHz to 6 GHz), so nothing here protects a narrowband receiver.

Receiving: a strong signal you are not listening to still ruins your day

An FM broadcaster or nearby LTE base station arrives at the SMA at full strength whatever you tuned to. The front end sets its gain for the loudest thing present, pushing your wanted signal down too. This is desensitisation, or blocking, and it looks like a weak signal: the noise floor seems to rise for no reason. The fix is a band-pass filter at the antenna, the first accessory worth owning.

Transmitting: your harmonics leave the building too

The amplifier emits copies at twice and three times the frequency, measured on this board at −64 to −80 dBc (second) and −71 to −85 dBc (third). Into an antenna at +19 dBm, the second harmonic of 900 MHz is a real transmission at 1.8 GHz, in somebody else's band, at up to −45 dBm. This board has no transmit low-pass filter, so before anything radiates know what you may transmit, where, at what power, and at what harmonics.

Where the noise figure is decided

In a cascade, the first stage dominates. Friis's formula:

noise figure of a cascadelinear, not dB
F_total = F1 + (F2 - 1)/G1 + (F3 - 1)/(G1*G2) + ...
                     |
              divided by the first stage's gain

A low-noise amplifier with 15 dB of gain at the front makes the rest nearly irrelevant. Hence put the LNA at the antenna, not at the radio: coax with 1 dB of loss in front of the LNA costs a whole decibel of noise figure; behind it, almost nothing.

Cables, connectors, and the reason every measurement here says "exactly 20 dB"

  • Use a real attenuator. This board's receive input is rated to about +2.5 dBm and its transmitter reaches about +19 dBm. A loopback without at least 20 dB of pad destroys the receiver, once, permanently. Raising a port's output also needs a human on record: ./devkit tx-guard affirm 0 (TX1A) or 1 (TX2A) after you have looked at that port, and ./devkit selftest --loopback refuses to transmit without it.
  • Exactly 20 dB, not more. With a bigger pad the board's internal transmit-to-receive leakage (an equivalent 58 to 77 dB of isolation below 1 GHz, only 33 to 51 dB at 3 to 6 GHz) competes with the cable path, and you measure the board's crosstalk.
  • SMA connectors have a torque spec. A loose one is an intermittent mismatch that looks like a flaky radio.
Check yourself: your 900 MHz link works on the bench through a cable and fails on antennas at 30 m. Name four suspects, in order.
  1. Polarisation. Free to test, worth 20 dB.
  2. Path loss. 30 m indoors at an exponent of 3.5 is about 22 dB worse than free space.
  3. Blocking. No front-end filter; look at a wide spectrum capture first.
  4. The antennas. Wrong length, no ground plane, or a poor match, at both ends.
43

RF design: Smith charts, matching networks and layout

The practice behind lesson 42: measuring, matching, the copper, and the proof of this board's one real hardware gap.

S-parameters, and why RF uses them

At RF you cannot measure port voltage and current, so you measure waves: a going into a port, b coming out; the S-matrix relates them:

a two-port, completely describedS-parameters
b1 = S11*a1 + S12*a2          S11 = b1/a1 with a2 = 0   input reflection
b2 = S21*a1 + S22*a2          S21 = b2/a1 with a2 = 0   forward gain / loss
                              S12 = reverse transmission (isolation)
                              S22 = output reflection

Gamma = (Za - Z0)/(Za + Z0)   VSWR = (1+|Gamma|)/(1-|Gamma|)
Return loss (dB) = -20*log10(|Gamma|)

Two things about S-parameters that bite

"a₂ = 0" is a requirement
Port 2 must be terminated in a perfect Z₀. A badly matched port 2 corrupts your S11, not just S21.
The sign of return loss is not agreed
Conventionally positive, but many vendor documents call the negative 20·log|Γ| "return loss". State yours.

A sweep is linear, small-signal: nothing about noise figure, compression, intermodulation or power handling.

The Smith chart, explained rather than memorised

The Smith chart is the complex reflection-coefficient plane inside the unit circle, with an impedance grid drawn over it. Every point is a Γ; the curved lines say which impedance produced it.

Centre
Γ = 0. Perfectly matched: where you are trying to get to.
Far left
Γ = −1. A short circuit.
Far right
Γ = +1. An open circuit.
Top half / bottom half
Inductive / capacitive.
Distance from centre
|Γ|, so a circle around the centre is a constant-VSWR circle.

Why there are two grids, and what components do

The admittance grid is the impedance grid rotated 180°, because y = 1/z means Γ_y = −Γ_z. A series element moves you along a constant-resistance circle; a shunt element along a constant-conductance circle:

ElementMoves alongDirection
Series Lconstant-r circleclockwise
Series Cconstant-r circleanticlockwise
Shunt Cconstant-g circleclockwise
Shunt Lconstant-g circleanticlockwise

Matching is a maze: from your load to the centre, using only those four moves. A length of line is a fifth: it rotates you clockwise around the centre, half a wavelength per full turn.

The L network, and the bandwidth you do not get to choose

Two components, closed-form. Let Rsmall and Rlarge be the smaller and larger of source and load:

L-network design, completetwo elements
Q      = sqrt( R_large / R_small - 1 )

|X_series| = Q * R_small        // in series with the SMALLER resistance
|X_shunt|  = R_large / Q        // across the LARGER resistance

one of them is an inductor and the other a capacitor (opposite signs)
fractional 3 dB bandwidth = 1 / Q

Q is fixed by the resistance ratio alone, so the bandwidth is decided the moment you know what you match to what. 50 Ω to 10 Ω gives Q = 2 and about 50 % bandwidth.

Try it — design an L network

A third component does not widen the band — and a fourth might

A pi or T network lets you set Q, but only upward: Steer shows "it is not possible to have a lower Q with a three-element matching network than the Q of a two-element matching network", and adds "lower Q can be obtained with more than three elements." So pi and T buy harmonic rejection and realisable component values, not bandwidth. The derivation assumes a purely resistive source and load; for a reactive load such as an antenna, more elements do buy bandwidth, up to the Bode–Fano limit:

the bandwidth–match trade, for any lossless networkΓ_avg is the average |Γ| in the passband
Gamma_avg  >=  exp( -pi / (Q_load * FBW) )
                            ^^^^^^
                            the Q of the LOAD, not of your matching network

If the match is too narrow, the answer is a lower-Q load (a better antenna), not more components.

Copper: when a trace becomes a transmission line

A 50 Ω microstrip is set by trace width over height above ground, plus the dielectric constant. For FR-4 that ratio is about W/H = 1.9 to 2.0:

Ground plane below50 Ω trace widthComment
1.6 mm (a whole 2-layer board)≈ 3.0 mmwider than most 0402 pads — unusable in practice
0.254 mm≈ 0.45 mma normal 4-layer stack-up
0.20 mm prepreg≈ 0.35 mmwhat RF boards actually do

That table is the argument for ground on layer 2 rather than layer 4.

Why FR-4 runs out, with numbers

One construction (Isola 370HR core, 56 % resin, 0.0048 in), from the laminate's own table:

100 MHz1 GHz2 GHz10 GHz
Dielectric constant4.144.084.043.92
Loss tangent0.0160.0200.0210.025

Loss tangent rises 56 % to 10 GHz, and the dielectric constant is a property of the build: across the same vendor's constructions it spans 3.73 to 4.39 at 1 GHz, so a 50 Ω trace is ±8 % before anyone errs. Rogers RO4350B (3.48 ± 0.05 at 10 GHz, loss tangent 0.0037) has roughly seven times less loss; below about 1 GHz you usually do not need it.

Two layout rules. Stitch ground vias along RF traces, at most a quarter wavelength apart (3 mm at 12 GHz in FR-4), or the ground layers carry a parallel-plate mode. And treat a trace as a transmission line by rise time, not clock rate: Howard Johnson simulates anything longer than about a sixth of the rising edge; published thresholds range from a half to a twentieth, so err short.

The VNA, and the mistake everyone makes with it

A vector network analyser measures magnitude and phase. Calibration removes its systematic errors: a full two-port calibration solves twelve error terms; a one-port calibration removes three (directivity, source match, reflection tracking).

SOLT
Short, Open, Load, Thru. Bounded by how well the standards' models match the metal. Excellent in coax.
TRL
Thru, Reflect, Line. The reference impedance becomes that of the line standard, a piece of your own board, and the reflect need not be known. For PCB fixtures and on-wafer work. Thru and line must differ by 20° to 160°, so one pair covers about an 8:1 frequency range.

The single most common RF measurement error

Calibrated at the coaxial interface, the measurement still includes your connector, launch and feed line. For return loss magnitude that is survivable. For impedance it is fatal: the fixture rotates Γ around the chart, and you design a shunt capacitor where the antenna needed a series inductor.

Fixes, in order of rigour: de-embed a measured fixture model; TRL on your own board; or at least set the port extension against a short and an open at the feed point.

What a good antenna measurement looks like

VSWR 1.5 (return loss 14 dB) is a good match; VSWR 2.0 (9.5 dB) is where the matching network should be reviewed, and the usual threshold for quoting antenna bandwidth. At 2:1 the antenna still takes 88.9 % of the transmitter's power.

A deep null is not efficiency

S11 says how much power entered the antenna, not how much radiated. A 50 Ω resistor shows a magnificent S11 and radiates nothing; a lossy antenna measures better than a good one. Antenna work needs a chamber or a comparative range test.

Filters, and the gap in this board

The AD9361's receive filtering is baseband only: two programmable analogue low-pass filters after the mixer, then the converter and digital decimators. UG-570 describes no RF preselector, and the overload detector sits before all of it. ADI gives the diagnostic:

Analog Devices, UG-570

"If an LMT overload occurs but the ADC does not overload, it may indicate that an out-of-band interfering signal is resulting in the overload condition."

That is the missing filter's symptom: something you are not tuned to saturates the analogue front end while the converter sees nothing wrong. No baseband filtering helps. ADI's mitigation is to split the gain table (lesson 48). On transmit, the secondary filter (five times the baseband bandwidth) suppresses out-of-band noise but not RF harmonics.

So on an antenna, a front-end filter is the first accessory. The options, from datasheets:

TechnologyInsertion lossRejectionTrade
LTCC ceramic, 2.4 GHz2.2 dB max only 10 dB at 2.0 GHzcheapest, smallest, barely a filter close in
SAW, 2.4 GHz2.1 dB typ 25 dB at 1.7–2.2 GHzthe usual answer below ~2 GHz
BAW, 2.4 GHz1.1 dB typ 42 dB at 2.11–2.17 GHzbest performance, highest cost, ~10 mask layers
SAW, 902–928 MHz1.9 dB typ 35 dB below 800 MHz — but only 5 dB at 890–894 MHzread the close-in skirt, not the headline

Read the close-in skirt: the signal desensitising you is usually just outside the band, where every filter is weakest.

Simulating it before you build it

A circuit simulator is enough while the structure is electrically small; a planar (2.5D) solver suits a matching network on a PCB, a 3D one connectors and enclosures. Free tools: openEMS (GPL FDTD solver, Python and Octave), scikit-rf (BSD Python; Touchstone files, calibration and de-embedding including TRL) and Qucs-S (GUI over Ngspice with microstrip models and S-parameter analysis).

Legality has a number, and it is about the skirt too

For unlicensed US operation at 902–928 MHz and 2400–2483.5 MHz, out-of-band emissions must be at least 20 dB below the in-band peak in 100 kHz (30 dB if the in-band figure was RMS-averaged), plus absolute limits in restricted bands. This board's second harmonic passes into a cable and load; compliance belongs to the whole transmitter, including what is on the SMA.

Check yourself: your antenna measures S11 = −25 dB at the design frequency. Are you happy?

Suspicious. −25 dB is a VSWR of about 1.12, better than any real antenna needs. It may be an excellent match; your reference plane may still be at the SMA, so you measured a well-matched cable; or the antenna is lossy and its losses absorb what should have reflected. Only a comparative range test against a reference antenna tells them apart.

44

IQ files, and the metadata that turns them into measurements

A capture has no units, no frequency and no date unless you add them.

What is actually in the file

iio_readdev writes raw samples to stdout with no header: the packer's output from lesson 15, little-endian 16-bit signed integers, interleaved:

one receive channel enabled4 bytes per sample
I0 Q0  I1 Q1  I2 Q2  ...        # int16 LE, I then Q
both receive channels enabled8 bytes per sample instant
I0 Q0 I1 Q1   I0 Q0 I1 Q1   ...
|-- instant 0 --|-- instant 1 --|      # ch0 I, ch0 Q, ch1 I, ch1 Q

There are no markers. Enable channels in a different order, or forget you enabled two, and the file still opens and looks plausible; it is simply somebody else's signal.

The same int16 means two different things on this board

Receive
The converter is 12-bit, sign-extended into an int16. Full scale is ±2047, not ±32767.
Transmit
The DAC takes the top 12 bits, so you fill the whole ±32767 range and the hardware discards the low nibble, the same nibble docs/tx-gpio-bitmap.md routes to the header pins.

Divide a receive capture by 32768 instead of 2048 and every absolute level is 24 dB too low, consistently, so nothing looks wrong. The most common way to publish a confidently incorrect dBFS figure from this board.

How big is it going to be?

Four bytes per sample per channel, uncompressed.

Try it — how big is this capture, and can the link even carry it?

What the file does not say, and needs to

MissingWhy it matters
Sample rateEvery frequency axis you plot is wrong by the ratio you guessed
Centre frequencyOffsets in the file are relative to an LO you no longer know
Gain, and whether AGC was onNo absolute level can be reconstructed
Which channelRX1 and RX2 differ by 1.5 dB on this board, and by more at 3–6 GHz
Date and timeYou cannot correlate it with anything else that happened
Whether the fabric decimator was engagedChanges the rate by 8 and, on stock firmware, whether channel 1 is trustworthy at all (lesson 15)

SigMF: a sidecar file, and the end of the problem

SigMF, the Signal Metadata Format, is a convention, not a library. Rename the capture x.sigmf-data and write a small JSON file x.sigmf-meta beside it. The samples do not change, so every tool still reads them.

capture.sigmf-metaJSON
{
  "global": {
    "core:datatype":    "ci16_le",        # complex, int16, little-endian
    "core:sample_rate": 7680000,
    "core:version":     "1.0.0",
    "core:hw":          "Fishball7020 / PlutoSky, AD9361, RX2A",
    "core:description": "10 MHz DDS tone, fabric decimator engaged, 20 dB pad"
  },
  "captures": [
    { "core:sample_start": 0,
      "core:frequency":    900000000,
      "core:datetime":     "2026-09-23T04:20:00Z" }
  ],
  "annotations": [
    { "core:sample_start": 0, "core:sample_count": 262144,
      "core:freq_lower_edge": 2200000, "core:freq_upper_edge": 2450000,
      "core:label": "alias of the 10 MHz tone" }
  ]
}
global
Facts true of the whole file: number format, sample rate, what recorded it.
captures
One entry per retune or restart, each marking the sample index it begins at.
annotations
Labelled boxes in time and frequency, such as "the alias is here".

The repository's tools/sigmf-capture.py takes the capture and writes the sidecar in one go; --verify also checks it for dropped samples.

Record what you read back, not what you wrote

A value you wrote is an intention; a value you read back is a fact. The AD9361 quantises gain to its own table (lesson 48), rf_bandwidth snaps to what the filter design supports, and sampling_frequency lands on what the clock tree can produce. Build the metadata from an iio_attr read taken after configuration.

The two habits worth adopting today

  1. Always capture a muted reference. Same settings, transmitter at −89.75 dB, a second or two of samples. It is the only way to tell a real weak signal from something your own board is doing.
  2. Write the sidecar in the same script that takes the capture. Metadata added afterwards is metadata remembered.
Check yourself: a colleague sends you rx.bin, 400 MB, and says "it's the 900 MHz capture". What can you work out, and what can you not?

Can: 400 MB at 4 bytes per sample is 100 M samples if one channel was enabled, 50 M sample instants if two. Frequencies within the file are recoverable as fractions of fs ("the tone sits at 0.163 × fs").

Cannot: the sample rate, so no hertz and no duration; the gain, so no absolute level; which channel; whether the decimator was engaged; and whether "900 MHz" was the LO or the signal. All of that is three lines of JSON.

44A

MATLAB and Simulink, and three ways a radio program lies to you

MATLAB will talk to this board, show you one of its two receivers, offer to destroy its firmware, and hand you absolute levels 24 dB wrong. All four are fixable; none announces itself.

Words used here

System object — a MATLAB object you call like a function, which keeps state between calls. Simulink — MATLAB's block-diagram editor: wire blocks together and press run. Frame — one block of samples handed along the diagram in one go. Constellation — the received symbols plotted on the I/Q plane; for 16-QAM, sixteen tight clusters. AGC, automatic gain control — a loop that scales the signal to a target level. Matched filter — a receive filter shaped like the transmit pulse, which maximises signal against noise at the sampling instant.

Never accept MATLAB's offer to update the firmware

The ADALM-Pluto support package expects firmware v0.39. This board reports something else, so the hardware-setup wizard offers to “update” it with a stock Zynq-7010 ADALM-Pluto image. This board is a Zynq-7020 with an AD9361 rather than an AD9363; accepting costs you its firmware and bitstream. The runtime path only warns. Do not run the wizard; the helpers in matlab/+fishball/ route around it (./devkit matlab checks the setup).

MATLAB sees one receiver. This board has two.

Ask the stock support package for the second receiver and it refuses:

the error, on both sdrrx and sdrtxnot negotiable
ChannelMapping must be equal to 1

The package is written for a 1R1T radio; this board is 2R2T, and both receivers share one local oscillator and one sample clock (lesson 45). So the repository ships its own blocks, which reach the hardware through iio_readdev and iio_writedev:

MATLABboth receivers, one frame
rx = fishball.RxSource('ChannelMapping','RX1+RX2', ...
                       'CenterFrequency',868e6);
[iq, status] = rx();      # iq is N-by-2; status is [rssi1 rssi2 degC gain]
release(rx)

In Simulink, drop a MATLAB System block and point it at fishball.RxSource; fishball.TxSink is the transmit side.

Two settings that are not preferences

Simulate using
Must be Interpreted execution. These blocks call system(), which has no generated equivalent, so with the default “Code generation” the model fails with An error occurred in the block during compile, which names nothing.
Full scale
Receive is ±2047 (lesson 44), but OutputDataType int16 gives raw counts while double or single divide by 2048 and give ±1.0. Transmit is the full ±32767.

Three ways a radio program lies to you

1 — the register said yes, and the samples said no

Retune and read the frequency register back: it reads the new value immediately. But the reader process, the pipe, the socket and the board's DMA ring all hold samples captured before the change, and those come out first.

Measured over USB at 2.304 MSPS in 4096-sample frames: after a 500 kHz retune the tone stayed at the old offset for thirty-four more frames, moving on the thirty-fifth, while the register read the new frequency throughout. A scanner built on “write, read back, believe” is one step late and never errors. Rebuild the buffer after any change (pyadi-iio's rx_destroy_buffer()); the new frequency then arrives on the next frame.

2 — the setup ran when the model was compiled, not when it started

A Simulink System object's setupImpl runs when Simulink compiles the model as well as when it starts it. Put a transmitter's hardware setup there and it is started, torn down and started again, and a receiver in the same model captures the silence in between: the log read one count of 2047, a flat line, with no error. Open the radio lazily on the first step; keep only argument checking in setup.

3 — the EVM was fine and the picture was wrong

Scaling the received symbols to the reference's power before measuring tells you whether the clusters are tight, not whether they are in the right place. An AGC normalising a stream still at two samples per symbol delivers symbols at twice unit power after decimation, because the matched filter's peaks survive. Every point sits 1.42× too far out:

same capture, two ways of measuring it16-QAM over a cable
AGC target 1         mean power 2.013   amplitude 1.419x   EVM as plotted  42.3 %
AGC target 1/sps     mean power 1.068   amplitude 1.034x   EVM as plotted   6.8 %
                                        # rescaled-first EVM read 6.3 % in BOTH cases

Measure the constellation as drawn, and check the amplitude ratio as well as the scatter.

A register read confirms a register. Only the samples confirm the radio.

Try it — a live 16-QAM link over the board's own loopback

This transmits. It needs TX1 cabled to RX1 through at least a 20 dB attenuator (lesson 42). It never touches TX2.

MATLAB, from the repository rootpress run
open_system('examples/matlab/06-simulink/fishball_qam16.slx')

Sixteen points should settle onto the red markers within a second or two. Blobs mean noise; a rotating star, an unlocked carrier loop; a cross, unlocked symbol timing.

What the numbers should look like, and why the rate plan is the design

Measured at 900 MHz, TX1 at −30 dB through a 20 dB pad into RX1 at 20 dB: 6.7 % EVM as plotted, amplitude ratio 1.003, all sixteen decision regions populated 200–280 times against an expected 256, and a peak of 324 counts of 2047 so nothing clips.

The converter runs at 2.304 MSPS and the FPGA's ÷8 decimator (lesson 15) brings the host rate down to 288 kHz: 144 ksym/s, 576 kbit/s at four bits a symbol. Without it MATLAB cannot keep up; the buffers stay full and what you read is about thirty-four frames old, fatal for a link because the receiver's first frames predate the transmitter. At 288 kHz the buffer stays shallow.

The transmit side is a Constant block: the sink runs the hardware buffer cyclically, so one buffer loops for ever and later frames are ignored by design. Its waveform is built with a circular convolution, because a cyclic buffer wraps from its last sample to its first; filter it normally and the seam splatters across the band once per repeat.

Two receivers, and the chip that feeds them

45

Two coherent receivers: what this board can do that most cannot

The shared local oscillator looked like a limitation in lesson 15. It is also this board's most interesting capability.

Both receivers run from one synthesiser, sample on one clock, and are captured on one strobe. They are therefore coherent: the phase relationship between them is stable and meaningful — one measurement from two viewpoints, not two recordings.

examples/03-coherent-receivers shows the phase on a dial whose radius is the coherence, and avoids the trap at the end of this lesson.

What the phase difference tells you

A wave arriving at an angle reaches one antenna slightly before the other. That delay is a phase difference between the channels, and from it you can compute the direction the signal came from.

direction from phasePython
# rx1, rx2: simultaneous captures from the two receivers
phase_diff = np.angle(np.mean(rx2 * np.conj(rx1)))
# d = antenna spacing, lam = wavelength
angle_of_arrival = np.arcsin(phase_diff * lam / (2 * np.pi * d))

With antennas half a wavelength apart this is unambiguous across a useful arc: the basis of direction finding, and of beamforming, where you add the two channels with a deliberate phase shift to steer sensitivity.

Coherent does not mean calibrated

Each chain has its own amplifiers, cables and gain settings, so there is a fixed phase and amplitude offset between them unrelated to the signal. On this board the two receivers differ by about 1.5 dB in sensitivity before correction. Calibrate first: feed both inputs one signal through a splitter, measure the offset, subtract it.

And do not engage the fabric decimator on stock firmware

All of this needs the two channels sample-aligned. On upstream's wiring, engaging the ÷8 decimator filters channel 0 and not channel 1, offsetting them by the filter's group delay.

A bitstream built from this repository is already fine: patch 0021 filters both channels in lockstep and is applied by default (lesson 15). The warning is for factory firmware and for a build made with STOCK_RX_FILTER=1; on those, leave the decimator bypassed.

Try it

Split one signal into both receive ports with equal-length cables. Compute angle(mean(rx2 · conj(rx1))) and confirm it is stable over time; that stability is the coherence. Then lengthen one cable by a known amount and watch the phase shift by what the extra delay predicts.

46

MIMO and beamforming: what more than one antenna buys

Finding a direction from the phase between two receivers is one of three different things people mean by "multiple antennas". Know which one you are asking for.

Three things, one name

What it doesWhat it needsWhat it gives
DiversityTwo antennas see independent fades; use whichever is better, or combine themAntennas far enough apart to fade independently Up to 3 dB of gain, and — far more valuable — most of the fade margin back
BeamformingCombine with deliberate phase shifts so the array listens or shouts in one directionKnown geometry and calibrated phase 3 dB per doubling of elements, plus rejection of interference from other directions
Spatial multiplexingSend different data from each antenna at the same time on the same frequencyA rich scattering channel, and N×N antennasN times the throughput, with no extra bandwidth or power

Only the third is "MIMO" in the strict sense. All three are available here in some form, and they want opposite antenna spacings.

Why the spacing is the design decision

Diversity wants the antennas far apart — several wavelengths — so their fades are uncorrelated. Beamforming wants them close and exact — half a wavelength, so the phase difference maps to one angle. At 900 MHz that is 167 mm.

Wider than half a wavelength and several angles give the same phase difference: the array develops grating lobes. Much narrower and the phase difference shrinks into the noise. No spacing is good at both jobs.

Diversity, and the thing that actually rescues links

Selection combining
Take whichever branch is stronger. Nearly free, and most of the benefit.
Maximal ratio combining (MRC)
Co-phase the branches and add them, weighted by their own signal-to-noise. Optimal: 3 dB of plain gain with two equal branches, but worth 10 to 20 dB of fade margin, because both branches being deeply faded at once is the square of the probability that one is.

Beamforming, in the only maths you need

Two elements d apart, a wave arriving at angle θ from broadside. The far element is d·sin θ further away, so its signal is late by that much — in phase:

the whole of array processing, twicetwo elements
receive (direction finding)   phase difference = 2*pi * d * sin(theta) / lambda

transmit (steering a beam)    apply that same phase difference deliberately,
                              and the two waves add in phase toward theta
                              and cancel elsewhere

At d = λ/2 that is φ = π·sin θ: broadside gives 0°, endfire 180°. Two elements give a broad beam and one ambiguity: 30° in front of the array and 30° behind it give the same φ; a third or directional element resolves it. Scanning φ across all angles is a beamscan; MUSIC and ESPRIT do better (PySDR chapters 19 to 21).

Try it — spacing, angle and ambiguity

Spatial multiplexing, and why it is not free here

If the 2×2 channel matrix H is invertible, the receiver can solve for two streams sent at once on one frequency (802.11n onward). But H must be well-conditioned: two whips side by side in free space give a near-singular matrix whose inverse amplifies noise enormously. Multipath, everywhere else the enemy, is what makes spatial multiplexing work.

What this board genuinely has, and what it does not

  • Two receivers on one RX_LO and two transmitters on one TX_LO. The chains are coherent and share phase noise, so it cancels in the difference — unusual at this price.
  • Two is not many. Serious direction finding wants four or eight elements, which means several boards locked to one clock.
  • Nothing is calibrated. The chains differ by about 1.5 dB in receive and 0.1 to 0.25 dB in transmit on the measured unit, each with its own fixed phase offset — easily tens of degrees, and different at every frequency. Measure it with a splitter (lesson 45) and re-measure after every retune.
  • Transmit calibration drifts. The AD9361's transmit quadrature calibration varies by up to 10 dB run to run here, so a transmit beamformer needs re-calibrating far more often than a receive one.

Four elements from two boards

Two boards whose EXT_CLK inputs share one reference (a GPS-disciplined oscillator with one output per board) make a four-element line. The shared reference makes their LOs run at exactly the same frequency, and that is all it does. Each board's LO still lands at an unknown phase after every retune, and the two boards' captures start milliseconds apart, because nothing starts them together. So a calibration with a source straight ahead comes first, and each element's phase is read where it does not depend on when its capture started: at the peak of a matched filter, against a chirp that sweeps symmetrically across the LO.

The devkit's beamformer example does that through the automation server, and starts with a lock check: an element whose phase rotates against the beacon within one capture is on a different reference. Tried on one board, with TX2's phase standing in for the arrival angle, it found five directions from −60° to +60° within 0.3°. It gained nothing in SNR, though, and the reason is the first bullet above turned round: noise the two chains share cancels in their difference, and for the same reason adds up in step in their sum, where averaging cannot remove it. Array gain needs noise that differs from element to element.

Check yourself: you want diversity and direction finding from one pair of antennas. Can you?

Not well: diversity needs several wavelengths of spacing, direction finding half a wavelength or less. At a wide spacing the phase difference maps to several possible angles, so you need another constraint — a third antenna, a prior, or movement. With two chains, pick the job; if you need both, add elements rather than compromise the spacing.

47

The AD9361 itself: the chip in front of your fabric

Every sample your logic has seen came out of this chip already filtered, decimated and gain-controlled by something you did not write. Time to open it.

The receive path, stage by stage

inside the AD9361, receiveantenna to your fabric
RF in -> LNA -> mixer -> baseband filters -> ADC -> HB3 -> HB2 -> HB1 -> FIR -> LVDS/CMOS
                  |            |             |       \________________/      |
              RX_LO, shared  analogue     very fast   fixed halving stages  programmable,
              by BOTH        anti-alias   sigma-delta  bringing the rate     up to 128 taps
              receivers                                down in powers of 2

The mixer uses one RX_LO for both receivers, which is why lessons 45 and 46 work and why the two channels cannot be tuned separately. And the converter runs far faster than your sample rate, with halving filters behind it, which is why sampling_frequency will not accept arbitrary values.

Zero-IF, and the two artefacts it gives you for free

What it is
The mixer brings the wanted band straight down to zero, centred on DC, as I and Q: no intermediate frequency, very few parts.
Artefact one: the DC spike
LO leakage into its own mixer gives a constant offset at exactly 0 Hz — the bump at DC in every spectrum, which is not a signal.
Artefact two: the image
Any I/Q gain or phase mismatch turns a tone at +2 MHz into a ghost at −2 MHz. Its depth is the image rejection of lesson 40: 44 to 60 dBc here after a fresh calibration, varying by up to 10 dB run to run.

The rate chain, and why the driver says no

Ask for 5 MSPS and the driver picks a converter rate, a path through HB3/HB2/HB1 and FIR coefficients whose product lands on it, or on the nearest rate it can reach.

Below 2.083 MSPS
The half-bands run out, so the driver enables the chip's own 128-tap FIR. Leave its coefficients to the driver: a hand-written set that does not match the rate gives a quietly wrong receiver.
Above that
The FIR is bypassed.
With the fabric decimator engaged
sampling_frequency_available reports exactly {converter rate, converter rate / 8}: the chip's decimators and lesson 27's are in series, and only the fabric one is yours.

Try it — what does asking for this rate actually do?

Gain is not in decibels, whatever the units say

The receive gain slope is within 1.7 % of 1.000 dB/dB across 56 measured slopes on this board, but underneath, gain is a table index: each step selects an LNA, mixer and baseband amplifier combination, chosen by ADI per frequency band. So some steps change noise figure or linearity far more than gain, and a calibration at 900 MHz does not transfer to 2.4 GHz. Measure gain where you will use it (the table format is in lesson 48).

The calibrations, and the loops that never stop

CalibrationWhat it removesWhen it runs
Baseband DCOffset in the analogue basebandOn initialisation
RF DCThe LO-leakage spike at 0 HzOn initialisation and on retune
RX quadratureI/Q imbalance on receive — the imageOn retune, then tracked
TX quadratureI/Q imbalance on transmitOn request; this is the one that varies

The DC and quadrature tracking loops keep correcting while you receive. Switching them off made the OFDM link (lesson 33) worse; leave them on.

BIST: measuring the radio without any radio

The chip can inject a tone into its own receive path, with no RF involved:

a known tone, entirely inside the chiprun on your HOST
iio_attr -u ip:192.168.2.1 -D ad9361-phy bist_tone "2 7680000 0 0"   # on
# ... capture ...
iio_attr -u ip:192.168.2.1 -D ad9361-phy bist_tone "0 0 0 0"         # off

It separates a fault in the radio from one after it: modulation-and-throughput.md's sample drops appeared with no RF at all, so they were in capture and transport.

How it is configured, and by whom

Not by your fabric. The control bus is the processor's own SPI0, routed out through EMIO (lesson 13), not the axi_spi block in the block design. The Linux driver owns every register; gain, bandwidth and LO are changed by asking it.

The one operational rule that has cost the most time here

The board mutes its transmitters when no DMA stream is running and restores a cached attenuation when a stream starts. So an attenuation written before opening a buffer guarantees nothing about what happens during it.

Always: open the buffer, then set the attenuation, then read it back and assert it. The repository's tools now do this, and check that both channels return to the −89.75 dB floor — a check added after a buffer enable was measured raising one by 28 dB. The one exception is a single one-shot buffer, which has finished playing before you could write anything.

Also: the transmit side comes up energised at power-on, before any software runs. See docs/transmitter-safety.md, and do not attach an antenna to a board you are about to power up.

Read the chip's own opinion of itself

what the chip will tell yourun on your HOST
iio_attr -u ip:192.168.2.1 -d ad9361-phy            # every device attribute
iio_attr -u ip:192.168.2.1 -c ad9361-phy voltage0   # the receive channel's
iio_attr -u ip:192.168.2.1 -c ad9361-phy temp0 input   # die temperature, millidegrees

Then ./devkit selftest --ssh checks supply rails, die temperatures, the digital interface eye (157 of 256 delay positions pass on the measured board) and the internal loopback, without transmitting.

Check yourself: you want RX1 at 900 MHz and RX2 at 2.4 GHz, simultaneously. What happens?

You cannot: both receivers share one RX_LO, and rf_bandwidth too; only gain is per-channel. Signals within one receive bandwidth (up to 56 MHz) can be separated in the fabric with two digital down-converters (lesson 28); 900 MHz and 2.4 GHz at once takes two boards, plus a shared clock for coherence.

48

The AD9361, register by register

The layer under lesson 47: the actual SPI words, the actual addresses, and the places where the driver does something to your radio that no IIO attribute admits to.

Everything below was read out of the driver source — drivers/iio/adc/ad9361.c and ad9361_regs.h under firmware/src/linux/ (factory) or firmware-modern/src/linux/ (modern) — not UG-570. The manual wins for the silicon; the driver wins for your board.

One SPI transaction

The whole protocol is four macros:

drivers/iio/adc/ad9361_regs.hC
#define AD_READ    (0 << 15)
#define AD_WRITE   (1 << 15)
#define AD_CNT(x)  ((((x) - 1) & 0x7) << 12)
#define AD_ADDR(x) ((x) & 0x3FF)

A 16-bit header, MSB first, then the data bytes, so a single-register access is 24 bits on the wire:

the header word16 bits
 15   14 13 12   11 10   9 . . . . . . . . 0
  W   count-1    unused        address

  bit 15   1 = write, 0 = read
  14:12    bytes to transfer, minus one (1 to 8)
   9:0     10-bit address, 0x000 to 0x3FF
On this board
The bus is the Zynq PS's SPI0, routed out through EMIO (lesson 13); the device tree sets spi-max-frequency = <0x989680> — 10 MHz. The driver prints the rate it achieved at probe.
A burst counts downwards
Ask for 8 bytes and the second comes from addr−1, the third from addr−2; both ad9361_spi_readm and ad9361_spi_writem decrement. Read eight bytes from 0x100 and the last is 0x0F9, not 0x107 — plausible data, read backwards.
Register 0x000 is mirrored
Soft reset, 3-wire mode and LSB-first each appear twice in the byte — SOFT_RESET (1<<7) and _SOFT_RESET (1<<0), and so on — so a write lands correctly whichever bit order the chip is in.

Try it — build the SPI header word

The map, in blocks

525 register definitions across the 10-bit space, grouped here in the header file's own order:

RangeWhat lives there
0x000–0x03FSPI config, multichip sync, enable and filter control, clocks, BBPLL, temperature sensor, parallel port, ENSM, calibration control, AuxDAC/AuxADC, product ID, LVDS
0x040–0x05FBBPLL fractional word, VCO programming
0x060–0x065TX FIR — coefficient address, data, config
0x070–0x0CFTX attenuation, TX quadrature-cal offsets, baseband filter trim
0x0F0–0x0F6RX FIR and RX filter gain
0x0F8–0x12FAGC, manual gain, overload thresholds
0x130–0x137the gain-table access port
0x140–0x16FRSSI, calibration config, RX quadrature gain and tracking
0x170–0x1AFDC-offset configuration and tracking words
0x1B0–0x22FRX analogue trim — LNA bias, TIA caps, filter tuning, ADC
0x230–0x29FRX then TX RF PLL: integer and fractional words, charge pump, VCO, fast lock

The first register the driver reads is 0x037, the product ID. Probe refuses the part unless (value & 0xF8) == 0x08; the low three bits are the silicon revision, so a Rev 2 part reads 0x0A. If that read fails you have a wiring problem, not a radio problem.

The enable state machine, concretely

Read 0x017; bits 3:0 are the ENSM state:

CodeStateCodeState
0x0Sleep / Wait0x8RX
0x5Alert0x9RX flush
0x6TX0xAFDD
0x7TX flush0xBFDD flush

Drive it either by writing 0x014 — FORCE_TX_ON (1<<5), FORCE_RX_ON (1<<6), FORCE_ALERT_STATE (1<<2) — or by setting ENABLE_ENSM_PIN_CTRL (1<<4) and driving the chip's ENABLE and TXNRX pins from the fabric, for sample-accurate switching.

Why everything goes through Alert

In TDD, ad9361_ensm_set_state returns -EINVAL if you force TX or RX from anything but Alert, so RX to TX is always RX → Alert → TX. In FDD only FDD and Alert are reachable. The driver also parks the chip in Alert for FIR loading, bandwidth changes and calibrations; clocks and synthesisers stay up there, so returning costs no PLL relock.

Gain tables, as bytes

A gain table row is three bytes, written through an access port:

ByteWritten toContents
00x131external LNA control, internal LNA gain (2 bits), mixer/GM gain (5 bits)
10x132TIA gain (1 bit), LPF gain (5 bits)
20x133RF DC-cal flag, digital gain (5 bits)

Set the row index in 0x130, write the three bytes, pulse the write bit in 0x137. The driver holds 77 rows in full-table mode and 41 in split-table mode (chosen with AGC_USE_FULL_GAIN_TABLE in 0x0FB), with three tables per mode, for 0–1300 MHz, 1300–4000 MHz and 4000–6000 MHz; each row also carries its absolute gain in dB.

Retuning across 1300 or 4000 MHz silently changes what your gain setting means

When the RX LO changes band, ad9361_load_gt rewrites all 77 rows and remaps your current index: old index to dB via the old table, then that dB looked up in the new one, clamping to the top if there is no match. An index set at 900 MHz is a different physical gain — different LNA/mixer/TIA mix, noise figure and compression point — at 2.4 GHz, and nothing reports it. Read gain back after a retune.

The 128-tap FIR, and its rules

Coefficients are signed 16-bit, written low byte then high byte through 0x061/0x062 on transmit and 0x0F1/0x0F2 on receive. The constraints, all in ad9361_load_fir_filter_coef:

  • Tap count must be a multiple of 16, and at most 128 (ntaps > 128 || ntaps % 16 is rejected).
  • The FIR does its own rate change of 1, 2 or 4; 4 is written as 3, and 0 means bypass, not ÷1.
  • At interpolation 1, transmit is capped at 64 taps. In general max_taps = (converter_rate / sample_rate) × 16: at full rate there are not enough clock cycles per sample for 128 coefficients.
  • Gain is quantised. Receive offers −12, −6, 0 or +6 dB; transmit only 0 or −6 dB.

The tap limit is where lesson 47's 2.083 MSPS comes from: libad9361 tests rate <= 25000000 / 12 — 2 083 333 Hz — and steps the chip through an intermediate 3 MSPS before toggling the FIR, because enabling 128 taps directly at the final low rate would violate it. Custom coefficients go in through the filter_fir_config attribute as a .ftr text file.

What the driver does that you did not ask for

Probe resets the chip, checks the product ID and runs ad9361_setup, the calibration sequence: BBPLL, synthesiser charge pumps, both RF PLLs, the baseband filters, then baseband DC offset, RF DC offset, TX quadrature, the tracking loops, and finally the ENSM mode and transmit attenuation. Afterwards, on a retune:

RX LO changes
The gain table is reloaded if the band changed. No calibration runs — the driver leaves it to the tracking loops.
TX LO changes
A transmit quadrature calibration runs only if the frequency moved more than 100 MHz (cal_threshold_freq = 100000000ULL). Small retunes reuse the old calibration — part of why image rejection wanders by up to 10 dB between runs.

debugfs, and what it is really for

every debugfs entry the driver creates/sys/kernel/debug/iio/iio:deviceN/
initialize   loopback   bist_prbs   bist_tone   gpo_set
bist_timing_analysis   gaininfo_rx1   gaininfo_rx2
multichip_sync   calibration_switch_control   digital_tune

Beside those, every adi,* device-tree property also appears as a debugfs file — more dangerous than it looks.

Two things that will cost you an afternoon

Writing an adi,* file changes nothing — until it changes everything
Those files edit the driver's in-memory copy of the device tree; nothing reaches the chip. Then echo 1 > initialize does a full reset and re-setup: both RF PLLs, every calibration, and the transmit attenuation from the device tree. The vendor's tree says 10 dB — an ungated jump from the −89.75 dB floor to roughly +9 dBm at the connector. This repo's trees say 89750 mdB, maximum attenuation. But on the factory kernel initialize also wipes the cached attenuation to zero, so the next transmit buffer opened restores full output (fixed on the modern target by firmware-modern/patches/0019). Treat initialize as a transmit command, and on the factory kernel re-mute and read both attenuations back after it.
The SPI soft reset does not work, and the driver says so
Verbatim from ad9361_reset: "SPI Soft Reset was removed from the register map, since it doesn't work reliably. Without a prober HW reset randomness may happen. Please specify a RESET GPIO." Without reset-gpios it logs "this may cause unpredicted behavior!" and returns -ENODEV — and probe ignores the return value. You get a half-reset chip and a probe that reports success.

Read one register yourself

Reading the product ID through debugfs changes nothing and proves the whole path works:

the first register the driver ever readsrun on the BOARD
cd /sys/kernel/debug/iio/iio:device0        # ad9361-phy; check its name file, never assume the index
echo 0x37 > direct_reg_access
cat direct_reg_access                      # 0x8 or 0xA - product ID and revision

Then read 0x017 and watch the state change from 0x5 to 0xA as a stream starts. Write nothing until you have a reason and a reset GPIO.

Check yourself: you set RX gain to index 40 at 900 MHz, then retune to 2.4 GHz. Same gain?

No. The frequencies are in different gain-table bands (0–1300 and 1300–4000 MHz), so index 40 is remapped through dB to a different index and amplifier mix — or clamped to the top of the table. An index is not a gain.

Onward

49

The theory underneath: detection, estimation, information

The matched filter is optimal. Correlation gain is 10·log₁₀(N). MMSE beats zero-forcing. Capacity is B·log₂(1+S/N). Here is why each is true, and where each stops being true.

Detection is a hypothesis test

"Is there a packet here?" has two hypotheses — H₀, only noise; H₁, signal plus noise — and two ways to be wrong:

False alarm
You declare a packet that is not there. Costs you a wasted decode.
Miss
A real packet goes unnoticed. Costs you the packet.

The optimal rule is the likelihood ratio test: form Λ(x) = p₁(x)/p₀(x) and compare it to a threshold. The Neyman–Pearson lemma says that among all tests with a false-alarm rate at most α, it has the highest probability of detection.

Sweep the threshold and you trace the ROC curve — detection probability against false-alarm probability. For a known signal in Gaussian noise it collapses to one number:

the entire ROC, in one parameterdeflection
P_D = Q( Q^-1(P_FA) - d )      d = sqrt( N * A^2 / sigma^2 )

Everything about your data enters through d, which grows as √N: lesson 32's correlation gain, from the statistics side.

Why the matched filter is optimal, in one inequality

Write the filter and the signal as vectors; the output SNR at time T is a ratio of an inner product to a norm. Cauchy–Schwarz — |⟨g,s⟩|² ≤ ⟨g,g⟩·⟨s,s⟩, with equality if and only if g = c·s — gives:

the bound, and when it is metAWGN
SNR(T)  <=  2E / N0            E = the signal's energy

equality iff  h(t) = c * conj( s(T - t) )  // time-reversed and conjugated: the matched filter

So the peak SNR depends only on the signal's energy, not its shape: any waveform of the same energy reaches 2E/N₀. That is why lesson 30 could choose the pulse shape on bandwidth grounds alone.

Two things the matched filter does not do

It is not optimal in coloured noise
The proof assumes white noise. Against a narrowband interferer, or after any filter that shaped the noise, whiten first.
It does not minimise intersymbol interference
Matched filtering is optimal detection; ISI-freedom is the Nyquist criterion on the end-to-end pulse. With ISI the matched filter's samples still keep all the information, but symbol-by-symbol decisions on them are no longer optimal — that needs equalisation (lesson 34) or sequence detection. Root-raised-cosine at each end (lesson 30) satisfies both conditions by design.

The error probabilities, exactly

bit error rate in AWGNQ(x) = 0.5·erfc(x/√2)
BPSK        Pb = Q( sqrt(2*Eb/N0) )
QPSK, Gray  Pb = Q( sqrt(2*Eb/N0) )        // the same curve, in Eb/N0

square M-QAM, Gray, standard approximation:
            Pb ~= (4/k)*(1 - 1/sqrt(M)) * Q( sqrt( 3*k/(M-1) * Eb/N0 ) )     k = log2(M)

At a bit error rate of 10−5 they give the exact version of lesson 41's table, which is rounded to whole decibels and reads about half a decibel high for the larger constellations:

SchemeBits/symbolEb/N0SNRCost of the extra bits
BPSK19.59 dB9.59 dB—
QPSK29.59 dB12.60 dB+3.01 dB
16-QAM413.43 dB19.46 dB+6.86 dB for 2
64-QAM617.79 dB25.57 dB+6.11 dB for 2
256-QAM822.50 dB31.53 dB+5.97 dB for 2

Three different "6 dB per bit" rules, and how to keep them apart

  1. Converter resolution — SNR = 6.02·N + 1.76 dB. One more ADC bit buys 6 dB. Lesson 9. Correct.
  2. Capacity per real dimension — C = ½·log₂(1+SNR), so one more bit per dimension needs four times the SNR: 6.02 dB. Correct.
  3. QAM per symbol — a complex symbol is two dimensions, so one more bit per symbol needs only twice the SNR: 3.01 dB (Forney: in the bandwidth-limited regime, 3 dB more SNR buys one more bit per two dimensions).

The table above is the third case: 3.0 to 3.4 dB per bit. Rule 1 or 2 overpredicts a QAM step by a factor of two in decibels.

Estimation: how well can you possibly know a number?

The Cramér–Rao lower bound: an unbiased estimator's variance is at least the reciprocal of the Fisher information, which measures how sharply the likelihood peaks. For the frequency of a complex tone from N samples at SNR ρ, exactly at every N:

frequency estimation CRLBf in cycles per sample
var(f_hat)  >=  6 / ( (2*pi)^2 * rho * N * (N^2 - 1) )

Note the N³: the standard deviation falls as N1.5, so doubling the preamble buys 9 dB of frequency accuracy, not 3 — a longer observation gives the phase more time to rotate, and the rotation carries the frequency. At 61.44 MSPS and 10 dB of SNR:

PreambleBest possible frequency accuracy
64 samples14.8 kHz
256 samples1.85 kHz
1024 samples231 Hz
4096 samples28.9 Hz

A 64-sample preamble leaves about 15 kHz of uncertainty, only 5.6° of rotation across those 64 samples; it reaches a quarter turn at around 1040 samples. The estimate improves with correlation length, the residual offset (lesson 32's trap) punishes it, and the preamble you want is where the two cross.

The bound is a bound, not a promise — and it has a cliff

The CRLB applies to unbiased estimators only, and may be unattainable at any finite N. Frequency estimation also has a threshold effect: below some SNR the estimate lands in a wrong part of the spectrum, and the bound says nothing about that regime.

Why MMSE beats zero-forcing, in one term

the only differencelinear equalisers, schematically
zero forcing   W  ~  1 / H
MMSE           W  ~  1 / ( H + 1/SNR_mfb )
                              ^^^^^^^^^^^

At a channel null zero-forcing divides by nearly zero, amplifying noise without limit; the extra term (the reciprocal of the matched-filter-bound SNR; exact form in Cioffi's Stanford notes) keeps the denominator away from zero. So the unbiased MMSE equaliser performs at least as well as zero-forcing at every SNR — but its output is biased, which must be removed before slicing or generating LLRs, and it needs an SNR estimate, failing as quietly as lesson 36's sum-product decoder when that estimate is wrong.

Information theory, and the number everybody quotes wrong

Capacity is the mutual information — how much the output tells you about the input — of the best input distribution. Shannon (1948) proved that below capacity a code with arbitrarily few errors exists, by averaging over random codes; it took until turbo codes in 1993 to build one that came close (lesson 36). His AWGN capacity, C = W log((P+N)/N), rewritten in energy per bit and spectral efficiency η = Rb/B, is the condition every link must satisfy:

the real Shannon limitη = bits per second per hertz
Eb/N0  >=  (2^eta - 1) / eta

as eta -> 0:   -> ln 2 = 0.693  ->  10*log10(0.693) = -1.59 dB

−1.59 dB is not your limit, and it is not close

That number is the limit as spectral efficiency goes to zero. At the efficiency you actually run at, it is much higher:

Spectral efficiencyShannon limitUncoded needsThe gap
η → 0−1.59 dB——
η = 2 (QPSK)1.76 dB9.59 dB7.83 dB
η = 4 (16-QAM)5.74 dB13.43 dB7.69 dB
η = 6 (64-QAM)10.21 dB17.79 dB7.58 dB

Against −1.59 dB a 64-QAM link looks 11.8 dB worse than it is. Between 2 and 6 bits per hertz an uncoded link sits 7.6 to 7.8 dB from its limit (BPSK, at 1 bit per hertz: 9.6 dB). That gap is all coding can win, so lesson 35's 5 dB is most of it.

Try it — error probability, exactly

What none of this promises

Capacity says nothing about latency or complexity: approaching it needs long blocks. All of it is about N → ∞, and at a packet radio's short blocks the finite-length penalty is large. All of it assumes white Gaussian noise, which multipath, phase noise and amplifier non-linearity are not. And Neyman–Pearson optimality needs both distributions fully known; with unknown amplitude, phase and timing there is generally no uniformly best test. Finally, Eb/N0 is not SNR: they differ by 10·log₁₀(k), 6 dB for 16-QAM — state the bandwidth with every ratio (lesson 40).

Check yourself: you double your preamble from 512 to 1024 samples. What improves, and by how much?

Detection improves by 3 dB (10·log₁₀(N)); frequency estimation by 9 dB (variance as 1/N³). Past a point a longer coherent correlation stops helping detection, because the residual offset rotates the phase across the window.

50

Projects, in order of difficulty

Each one uses the board for something software cannot do as well.

First run something that already works: examples/ has three graded GNU Radio showcases — dynamic range and how to lose it, a QPSK link you can watch end to end, and the coherent receivers of lesson 45. Every control is wired to a number, so you can break the measurement on purpose and see what it cost.

  1. A sample-locked trigger. Divide the sample stream and pulse a header pin: a scope trigger with a fixed, known relationship to the transmitted RF. Lessons 13–16.
  2. A power meter. Accumulate I² + Q² over a window in the fabric and expose the total in a register, so the processor reads one number instead of a megabyte of samples. Your first real use of a DSP slice.
  3. A digital downconverter. NCO plus mixer plus decimating filter: deliver one signal within the captured band at a low rate. Lessons 26–28 combined.
  4. A matched filter / correlator. Detect a known preamble in hardware and raise a flag. The gateway to radar, ranging and packet detection, and the first design where latency, not throughput, is the point. tools/adsb/demod.py is a working software model to port: the ADS-B preamble detector of lesson 32, with a test bench (tools/adsb/test_adsb.py) that already has the synthetic signals.
  5. A modulator. The exercise from lesson 29.
  6. Hardware timestamping. Count l_clk edges and tag each buffer — the missing piece that makes cellular-class stacks work on AD936x boards. Hard, and genuinely valuable.
51

The rules worth taping to the wall

Every one of these was learned the expensive way on this exact board.

  • Delete the Vivado project before any HDL or coefficient change, or your change is silently ignored.
  • Simulate before you synthesise. One second against twenty minutes.
  • Gate on the valid strobe, never on l_clk alone — this board is 2R2T, so a sample arrives every second edge.
  • Capture on fifo_rd_valid | fifo_rd_underflow, never on fifo_rd_en, which is the request and arrives a cycle early.
  • Synchronise every control bit that crosses a clock domain, and constrain the crossing with an explicit -from.
  • Verify before you flash, and ./devkit verify --board after — it is the only thing that proves the board runs what you built.
  • Never flash with DFU. Use ./devkit flash over the network, or write the SD card.
  • Set TX attenuation after the buffer opens, then read it back. Writing it before a stream starts guarantees nothing.
  • Never loop transmit back to receive without at least 20 dB of attenuation. The receive port survives about +2.5 dBm; the transmitter reaches about +19 dBm.
  • Look at the port, then affirm it: ./devkit tx-guard affirm 0 (TX1A) or 1 (TX2A) before anything raises output. A reboot withdraws it.
  • Do not trust a cyclic transmit to stop by itself. It outlives the program that started it; the modern (Debian) target bounds it at 60 s, the factory target not at all.
  • A guarantee you cannot reproduce on the bench is not a guarantee. Killing a transmitting program was supposed to mute the radio; measured, the port sat 12.6 dB hotter than muted with the program gone. The fix keys off a state, not an event: no data reaching the converter for 250 ms means mute.
  • Zero is not a safe default. A reset path that memsets the cached transmit attenuation turns it into 0 dB — full output — on the next stream. Fixed on the modern target; still live on the factory kernel after a debugfs initialize.
  • When the radio misbehaves, check /mnt/jffs2 first. It is writable, it survives reflashing, and a script there can rewrite settings underneath your application.

Measured figures throughout come from one physical board. Treat them as indicative rather than specification.

Appendix

A

Where the numbers came from, and what is still not here

Every measured figure in these lessons came off one board or out of a primary source. This appendix says which, points at the books worth owning, and names what the course does not cover.

The two books to have open

SDR4E
Software-Defined Radio for Engineers — Collins, Getz, Pu and Wyglinski, Artech House 2018. Free from Analog Devices; uses the Pluto — the same AD9361 and Zynq — as its instrument.
PySDR
PySDR: A Guide to SDR and DSP using Python — Marc Lichtman, pysdr.org. Free online, and the friendliest first read.

Neither has an FPGA chapter. That gap is why this course exists.

Lesson by lesson

TopicTaught inGo deeper
What an SDR is at all0SDR4E Ch 1 · PySDR Ch 1
Fixed point and quantisation9SDR4E §2.5.2–2.5.3
IQ samples, sampling, aliasing11, 12SDR4E §2.2–2.3 · PySDR Ch 2, 3
Packaging logic as IP, splicing the datapath19AMD UG994 (IP Integrator), UG1118 (packaging custom IP)
Frequency domain, FFTs, windows24PySDR Ch 7
Noise, decibels, the floor25PySDR Ch 10 · SDR4E §3.5–3.7
Filters, decimation, mixers26–28PySDR Ch 11 · SDR4E §2.6
Modulation, pulse shaping, synchronisation29–31SDR4E Ch 4, 6, 7 · PySDR Ch 16, 17
Correlation, matched filters, detection32PySDR Ch 24 · Kay, Detection Theory
OFDM and equalisation33, 34SDR4E Ch 9, 10 · Cioffi, Stanford EE379 Ch 3
Channel coding and iterative decoding35, 363GPP TS 38.212 §5.3 · ten Brink on EXIT charts
Framing, protocols, routing37, 38RFC 3819 (BCP 89) — read this one
Security39NIST SP 800-38C/38D, SP 800-175B
Measuring, link budgets, antennas, RF design40–43Steer, Microwave and RF Design (free) · Keysight AN 154
Measuring by script: the automation server40the repo's docs/automation.md and tools/automation/examples/
IQ metadata44PySDR Ch 14 · the SigMF specification
MATLAB and Simulink, and verifying what a radio actually did44AMathWorks Communications Toolbox · the repo's examples/matlab/
Coherent receivers, MIMO, beamforming45, 46PySDR Ch 19–21
The AD9361, system and registers47, 48ADI UG-570 · drivers/iio/adc/ad9361.c
Detection, estimation, information theory49Kay Vol I · Cover & Thomas · Shannon 1948

Lessons 36, 38, 39, 48 and 49 were checked against the primary sources in the right-hand column (lesson 36's FPGA utilisation figures are AMD's published numbers; lesson 48's are the driver source). A figure that could not be verified is absent or flagged.

What this course still does not teach

Making it a product (EMC certification, environmental and production test); designing the analogue blocks inside the chip; verification at scale (constrained-random, UVM, formal); implementing cryptography safely (constant time, side channels, key storage, entropy); operating a deployed network (provisioning, over-the-air update, key rotation); and high-speed digital design such as DDR and SerDes.

Also worth knowing

  • "Process gain" is the standard name for lesson 27's decimation bonus.
  • Choose an awkward test frequency. A tone harmonically related to the sample clock costs SFDR (11.4 dB in SDR4E); this repository's full-rate sweep used exactly fs/8, so its SFDR figures are pessimistic.
  • ADI's Pluto wiki — wiki.analog.com/university/tools/pluto.
  • scikit-rf — Python for touchstone files, calibration and de-embedding.
  • This repository's docs/ — block-design.md is the reference this course summarises; hardware.md is the parts list behind lessons 42 and 43; measured-performance.md, modulation-and-throughput.md and both-receive-channels.md hold the measured numbers with their conditions; transmitter-safety.md is what to do before transmitting.