Plutoradio Ug
Plutoradio Ug
R2025a
How to Contact MathWorks
Phone: 508-647-7000
iii
Radio Configuration
3
Baseband Sampling Rate and Filter Chains . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Filter Design with Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Filter Design with System Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Radio I/O
4
Channel I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Transmit Data Using ADALM-PLUTO Radio Block . . . . . . . . . . . . . . . . . . . 4-2
Receive Data Using ADALM-PLUTO Radio Block . . . . . . . . . . . . . . . . . . . . 4-2
Transmit Data Using ADALM-PLUTO Radio System Object . . . . . . . . . . . . 4-3
Receive Data Using ADALM-PLUTO Radio System Object . . . . . . . . . . . . . 4-3
Performance
5
Simulink Performance Improvements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Model Tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
iv Contents
MATLAB Performance Improvements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Vector-Based Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Troubleshooting
6
Common Problems and Fixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Host Not Communicating with ADALM-PLUTO Radio . . . . . . . . . . . . . . . . 6-2
Host USB Port to ADALM-PLUTO Radio Communication Unreliable . . . . . 6-3
Input Must Be Complex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Overruns or Underruns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Firmware Version Warning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4
Hardware Setup on Windows 7 — Test ADALM-PLUTO Radio Connection
Failure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5
Hardware Setup on Linux — Configure ADALM-PLUTO Radio Failure . . . . 6-5
Unable to Assign IP Address Radio Identity . . . . . . . . . . . . . . . . . . . . . . . . 6-6
ADALM-PLUTO Radio Is Busy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6
No Data from Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7
Examples
7
Capture RF Data to Baseband File Using ADALM-PLUTO Radio . . . . . . . . 7-2
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN
Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-41
v
Automatic Meter Reading in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-94
vi Contents
1
• Explore and experiment with the Support Package for ADALM-PLUTO radio featured examples.
• Examine radio waves in your vicinity using “Spectrum Analysis of Signals” on page 7-64
• Make a standalone FM receiver using “FM Broadcast Receiver”
• Make a standalone RBDS receiver using “RDS/RBDS and RadioText Plus (RT+) FM Receiver”
• Check out the topics in “Radio Configuration”, which explain how to create blocks and System
objects, and adjust radio settings.
• Tweak performance of your model with “Performance” optimizations.
See Also
Related Examples
• “Common Problems and Fixes” on page 6-2
1-2
Supported Hardware and Required Software
Supported Hardware
Analog Devices ADALM-PLUTO Radio
For more information about this hardware, visit the ADALM-PLUTO radio Quick Start Guide site at
Analog Devices.
• MATLAB
• Communications Toolbox
• Simulink
Recommended Software
• Simulink
See Also
Related Examples
• “Install Support Package for Analog Devices ADALM-PLUTO Radio” on page 2-2
• “Guided Host-Radio Hardware Setup” on page 2-3
1-3
2
• “Install Support Package for Analog Devices ADALM-PLUTO Radio” on page 2-2
• “Guided Host-Radio Hardware Setup” on page 2-3
• “Manual Host-Radio Hardware Setup” on page 2-6
• “Setup for Two Radios Connecting to One Host” on page 2-10
• “Uninstall Support Packages” on page 2-13
2 Setup and Installation
Add-On Explorer
1 On the MATLAB Home tab, in the Environment section, click Add-Ons > Get Hardware
Support Packages.
2 In the Add-On Explorer window, browse or search for the Communications Toolbox Support
Package for Analog Devices ADALM-Pluto Radio.
3 Select the support package and then click Install.
File Exchange
Download and install the support package from File Exchange by clicking Download and then
running the installer.
When the support package installation is complete, you will be prompted to configure your radio.
Click Setup Now to open the hardware setup window. Alternatively, click the setup button in
the Add-Ons panel window. For more information on hardware configuration process, see “Guided
Host-Radio Hardware Setup” on page 2-3.
See Also
Hardware Manager
See Also
More About
• “Manual Host-Radio Hardware Setup” on page 2-6
• “Setup for Two Radios Connecting to One Host” on page 2-10
• “Supported Hardware and Required Software” on page 1-3
• “Get and Manage Add-Ons”
2-2
Guided Host-Radio Hardware Setup
This topic describes the automatic guided host-radio hardware setup process for Windows®, Linux®,
and OS X operating systems.
Third-party tools required by the I/O mode features are automatically downloaded and installed
during the support package installation.
To complete the setup process manually, see “Manual Host-Radio Hardware Setup” on page 2-6.
Note Because the setup process runs operating system commands for installing USB drivers, you
must have administrator privileges for the radio hardware setup. Start MATLAB using Run as
administrator.
The automatic hardware setup process guides you through several steps. If you have to cancel the
setup process, you can open it again from the Add-Ons panel window. To confirm that you have the
correct configuration for your the host machine, the correct radio hardware, and all required
accessories, complete these checklists.
• Administrator privileges — Because the software runs operating system commands for installing
USB drivers, you must have administrator privileges for the guided radio hardware setup. If you
see the User Account Control window, click Yes to continue with the setup process.
• USB connection between ADALM-PLUTO radio and host computer — This connection is necessary
for sending and receiving signals to and from the radio. It is also used for updating the AD936x
SDR configuration from the host computer.
• ADALM-PLUTO radio
• USB communication cable
• USB power cable (optional)
• Antennas or a loopback cable
In the Add-Ons panel window, select the Communications Toolbox Support Package for Analog
Devices ADALM-Pluto Radio, and click Install.
2-3
2 Setup and Installation
During the installation, you might be required to acknowledge and accept software licensing
agreements from MathWorks and third-parties.
The Download and Installation Progress window provides a list of the installation steps and progress
status. After the support package software installation completes, you might be asked to configure
your radio for use with MATLAB. Click Setup Now to open the Hardware Setup window.
In the Hardware Setup window, click Next and you are guided through these pages to setup your
radio.
1 Connect Hardware
Confirm that all connections for the ADALM-PLUTO radio are complete.
• Connect the USB communication cable from the host computer to the radio.
• Connect the antennas to the transmit and receive antenna ports. Alternatively, connect a
loopback cable connecting the transmit port to the receive port.
• (Optional) Connect a USB power cable to a USB power hub of the ADALM-PLUTO radio. This
step is recommended if:
• You plan to operate the radio at or near maximum gain settings continuously.
• PlutoSDR is unresponsive or commands fail especially when the radio is connected to an
unpowered USB hub.
Wait until you see the Ready indicator LED lit steady and LED1 flashing.
•
After the connection test completes, green check marks ( ) indicate successful completion
of the connection testing. Click Next to continue.
•
A red X mark ( ) next a test step indicates a failure occurred during the radio connection
test. To continue installation, follow the What to Consider instructions.
If you still get an error you cannot resolve, see “Common Problems and Fixes” on page 6-2.
3 Hardware Setup Complete
When the hardware setup is successfully completed, click Finish to begin using your ADALM-
PLUTO radio.
2-4
Guided Host-Radio Hardware Setup
See Also
Related Examples
• “What to Do After Installation” on page 1-2
• “Setup for Two Radios Connecting to One Host” on page 2-10
• “Install Support Package for Analog Devices ADALM-PLUTO Radio” on page 2-2
• “Manual Host-Radio Hardware Setup” on page 2-6
2-5
2 Setup and Installation
• ADALM-PLUTO radio
• USB communication cable
• USB power cable (optional)
• Antennas or a loopback cable
dev = sdrdev('Pluto');
sdrdev also sets up architecture-specific environment variables for the radio hardware. These
variables enable communication between MATLAB or Simulink and the radio hardware.
1 Confirm that all connections for the ADALM-PLUTO radio are complete. Specific connections are
shown in this image.
• Connect the USB communication cable from the host computer to the radio.
• Connect the antennas to the transmit and receive antenna ports. Alternatively, connect a
loopback cable connecting the transmit port to the receive port.
2-6
Manual Host-Radio Hardware Setup
• (Optional) Connect a USB power cable to a USB power hub of the ADALM-PLUTO radio. This
step is recommended if:
• You plan to operate the radio at or near maximum gain settings continuously.
• PlutoSDR is unresponsive or commands fail especially when the radio is connected to an
unpowered USB hub.
2 Wait until you see the Ready indicator LED lit steady and LED1 flashing.
3 After you connect the ADALM-PLUTO radio to the host computer via a USB communication cable,
you will see a PlutoSDR drive as a removable disk on the host computer.
• config.txt — Enables you to change the network address assigned to the PlutoSDR.
• info.html — Provides the current configuration for the connected PlutoSDR, along with
background information from Analog Devices.
Note Because the setup process runs operating system commands for installing the USB drivers,
you must have administrator privileges for the radio hardware setup. If you see the User Account
Control window, click Yes to continue.
Check the radio connection, using the radio object you created with the sdrdev function.
dev = sdrdev('Pluto')
dev =
2-7
2 Setup and Installation
RadioID: 'usb:0'
DeviceName: 'Pluto'
If you are unable to verify the radio hardware setup, see “Common Problems and Fixes” on page 6-
2.
Radio Identity
• (Recommended) Identify the ADALM-PLUTO radio by the USB identity.
Note When working with multiple radios, if devices are inserted or removed, the host computer
assignment of USB addresses might change. Any time an SDR device is inserted or removed from
a USB port, the host computer polls all USB ports and assigns or reassigns the radio addresses
associated with connected devices.
• When running multiple radios on the same host in separate MATLAB sessions, for each
MATLAB session the first radio is assigned usb:0, and the ID number increments by one for
subsequent radios.
• Radios that are being used by one MATLAB are not seen by other MATLAB sessions. Use
findPlutoRadio and check the reported serial number to identify the radios seen in a
particular MATLAB session.
To ensure that all assigned radio identities remain static, do not connect or disconnect radios after
SDR objects have been created. The best practice is to connect radios and create SDR objects in
this order:
1 Clear all SDR objects.
2 Connect all radios.
3 Check to confirm that the connected radios are recognized by running this command:
findPlutoRadio
2-8
Manual Host-Radio Hardware Setup
To interface with the radio hardware, the RadioID property of the radio object must match the
radio ID of the radio hardware. Update the RadioID property, if necessary.
When running multiple radios on the same host, the host assigns each radio a different radio ID.
When identifying the radio by USB ID, the first radio is assigned usb:0, and the ID number
increments by one for subsequent radios. For example, to assign IDs to two radios connected on
the same host computer, at the MATLAB command prompt, enter:
rx = sdrrx('Pluto','RadioID','usb:0');
tx = sdrtx('Pluto','RadioID','usb:1');
• Optionally, you can identify the radio by the IP address. The default IP address for the radio
hardware is 192.168.2.1. If you have no other connected device with this IP address, you can
leave the address as is. If needed, you can manually change the IP address.
• Navigate to the PlutoSDR drive, and open the config.txt file in a text editor.
• Change the desired settings in config.txt. Save and close the file.
• Eject the PlutoSDR drive.
• Disconnect and reconnect the ADALM-PLUTO radio.
• Confirm the changes by viewing the settings in the info.html file for that PlutoSDR.
• In Windows and most Linux distributions, the IP address of the ADALM-PLUTO radio is
reachable by the host computer. Attempt assigning an IP address ID to the ADALM-PLUTO
radio by entering this command (using the desired IP address) at the MATLAB command
prompt:
rx = sdrrx('Pluto','RadioID','ip:192.168.2.4');
If this command fails and you are unable to assign the IP address radio identity, you receive
an error. For more information, see “Common Problems and Fixes” on page 6-2.
See Also
Related Examples
• “What to Do After Installation” on page 1-2
• “Setup for Two Radios Connecting to One Host” on page 2-10
• “Install Support Package for Analog Devices ADALM-PLUTO Radio” on page 2-2
• “Guided Host-Radio Hardware Setup” on page 2-3
2-9
2 Setup and Installation
Note The two ADALM-PLUTO radios must be set up with different radio IDs.
• Set up the first radio following the steps in “Guided Host-Radio Hardware Setup” on page 2-3.
• Set up the second radio following the same steps.
Note When working with multiple radios, if devices are inserted or removed, the host computer
assignment of USB addresses might change. Any time an SDR device is inserted or removed from a
USB port, the host computer polls all USB ports and assigns or reassigns the radio addresses
associated with connected devices.
• When running multiple radios on the same host in separate MATLAB sessions, for each MATLAB
session the first radio is assigned usb:0, and the ID number increments by one for subsequent
radios.
• Radios that are being used by one MATLAB are not seen by other MATLAB sessions. Use
findPlutoRadio and check the reported serial number to identify the radios seen in a particular
MATLAB session.
To ensure that all assigned radio identities remain static, do not connect or disconnect radios after
SDR objects have been created. The best practice is to connect radios and create SDR objects in this
order:
2-10
Setup for Two Radios Connecting to One Host
findPlutoRadio
4 Create SDR objects.
To interface with the radio hardware, the RadioID property of the radio object must match the radio
ID of the radio hardware. Update the RadioID property, if necessary.
When running multiple radios on the same host, the host assigns each radio a different radio ID.
When identifying the radio by USB ID, the first radio is assigned usb:0, and the ID number
increments by one for subsequent radios. For example, to assign IDs to two radios connected on the
same host computer, at the MATLAB command prompt, enter:
rx = sdrrx('Pluto','RadioID','usb:0');
tx = sdrtx('Pluto','RadioID','usb:1');
In these examples, the first radio, acting as a receiver, is assigned usb:0. The second radio, acting as
a transmitter, is assigned usb:1.
Tip Run two instances of MATLAB on the host: one for the receiver and one for the transmitter.
• When running multiple radios on the same host in separate MATLAB sessions, for each MATLAB
session the first radio is assigned usb:0, and the ID number increments by one for subsequent
radios.
• Radios that are being used by one MATLAB are not seen by other MATLAB sessions. Use
findPlutoRadio and check the reported serial number to identify the radios seen in a particular
MATLAB session.
Radio Objects
Create a radio object for interacting with the receiver, and a radio object for interacting with the
transmitter. In both objects, update the RadioID properties with the assigned radio ID.
RxDevice = sdrdev('Pluto');
RxDevice.RadioID = 'usb:0';
TxDevice = sdrdev('Pluto');
TxDevice.RadioID = 'usb:1';
2-11
2 Setup and Installation
Create a System object for interacting with the receiver, and a System object for interacting with the
transmitter. When you create both System objects, set the corresponding RadioID property.
rx = sdrrx('Pluto','RadioID','usb:0');
tx = sdrtx('Pluto','RadioID','usb:1');
Radio Blocks
Create a block for interacting with the receiver, and a block for interacting with the transmitter. In
both blocks, update the corresponding block with the matching RadioID parameter.
See Also
Related Examples
• “Install Support Package for Analog Devices ADALM-PLUTO Radio” on page 2-2
• “Guided Host-Radio Hardware Setup” on page 2-3
• “Manual Host-Radio Hardware Setup” on page 2-6
• “Frequency Correction for ADALM-PLUTO Radio in Simulink” on page 7-101
• “Frequency Correction for ADALM-PLUTO Radio” on page 7-22
2-12
Uninstall Support Packages
See Also
More About
• “Get and Manage Add-Ons”
2-13
3
Radio Configuration
The options you choose depend on how much control you want over the design of the filters in the
transmit or receive chains. You can have the software design the filter chain automatically, or you can
manually design the filter chain according to your own specification.
When you set the baseband sampling rate on a transmitter or receiver System object or block,
MATLAB applies the default filter design to the filter chains. The default filters are applied according
to the baseband sample rate to provide the necessary decimation to achieve specific clock settings
and data rates.
You can modify the default filter design by invoking the AD9361 Filter Design Wizard from Analog
Devices.
Tip If the gain or bandwidth characteristics of the default filter does not satisfy the requirements for
your application, use the ADI filter wizard to design a custom filter that meets your specific
requirements.
The AD9361 Filter Design Wizard requires the following MathWorks products:
• MATLAB
• Signal Processing Toolbox™
• DSP System Toolbox™
For instructions on operating the filter wizard, see MATLAB Filter Design Wizard for AD9361 of the
Analog Devices website.
3-2
Baseband Sampling Rate and Filter Chains
To open the AD9361 Filter Design Wizard, on the Filter tab of the Pluto Transmitter or Pluto
Receiver block masks, click Launch filter wizard. The initial settings are the default filter design
settings.
When applying a custom filter to the Pluto Transmitter or Pluto Receiver blocks using the AD9361
Filter Design Wizard, the Use custom filter parameter of the block is automatically selected. To
switch between the default and your custom filter design, on the Filter tab of the block mask, clear
or select Use custom filter, respectively. Then click Apply.
1 Create a transmitter or receiver System object. Open the AD9361 Filter Design Wizard by calling
designCustomFilter. For example:
tx = sdrtx('Pluto','BasebandSampleRate',10e6)
designCustomFilter(tx)
2 In the filter wizard:
1 Create a name-value cell array that represents all the necessary settings for the filter design
based on the System object, then save it.
filtnv = { ...
'BasebandSampleRate',tx.BasebandSampleRate, ...
'filtPathRates',tx.filtPathRates, ...
'filtCoefficients',tx.filtCoefficients, ...
'filtCoefficientSize',tx.filtCoefficientSize, ...
'filtDecimInterpFactor',tx.filtDecimInterpFactor, ...
'filtGain',tx.filtGain, ...
3-3
3 Radio Configuration
'filtRFBandwidth',tx.filtRFBandwidth, ...
'filterConfigStruct',tx.filterConfigStruct ...
};
save 'mycustomfilter' 'filtnv'
2 Restore custom filter to a new object.
clear all
load mycustomfilter
See Also
Functions
sdrrx | sdrtx
Blocks
Pluto Receiver | Pluto Transmitter
Objects
comm.SDRRxPluto | comm.SDRTxPluto
External Websites
• MATLAB Filter Design Wizard for AD9361
3-4
DC Offset Tracking
DC Offset Tracking
Direct conversion receivers often impose a direct current (DC) bias on the in-phase and quadrature
components of the signal. DC bias can degrade BER performance for QAM and PSK systems. By
enabling DC offset tracking, you can reduce DC bias in the I/Q channels of a received complex signal.
The reduced DC bias better enables robust receiver processing. In addition, this reduction enables
you to focus on designing the baseband algorithm without worrying about DC bias that is introduced
by the analog front end. DC offset tracking for the AD936x RF chipset takes place on the RF
transceiver and can be implemented at baseband or RF. For more information, see Baseband DC
Offset Calibration and Baseband DC Offset Tracking in Analog Devices AD9364 Reference Manual -
UG-673.
rx = sdrrx('Pluto');
rx.ShowAdvancedProperties = true;
rx.EnableRFDCCorrection = false;
rx.EnableBasebandDCCorrection = false;
See Also
Functions
sdrrx
Objects
comm.SDRRxPluto
Blocks
Pluto Receiver
References
[1] Analog Devices AD9364 Reference Manual - UG-673.
3-5
3 Radio Configuration
Quadrature Tracking
In the AD936x, quadrature tracking is on always on for the transmitter and on by default for the
receiver. The tracking algorithm expects a complex quadrature signal at the input.
Direct conversion receivers often impose an I/Q imbalance on the in-phase and quadrature
components of the signal. I/Q imbalance, can degrade the BER performance for QAM and PSK
systems. By enabling quadrature tracking, you can reduce I/Q imbalance in the I/Q channels of a
received complex signal. The reduced I/Q imbalance enables more robust receiver processing. In
addition, this reduction allows you to focus on designing the baseband algorithm without worrying
about I/Q imbalance that is introduced by the analog front end. Quadrature tracking for the AD936x
RF chipset takes place on the RF receiver and can be implemented at baseband or RF.
For more information, see IQ Correction section in [1] and Rx Quadrature Tracking Calibration in [2].
With the receiver block, quadrature tracking at RF and baseband is on by default. To disable
quadrature tracking, on the Advanced tab of the receiver block, clear the Enable quadrature
correction parameter.
With the receiver System object, quadrature tracking at RF and baseband is on by default. To disable
quadrature tracking, show the advanced properties by setting the ShowAdvancedProperties
property to true. Then set the EnableQuadratureCorrection property to false.
rx = sdrrx('Pluto');
rx.ShowAdvancedProperties = true;
rx.EnableQuadratureCorrection = false;
See Also
Functions
sdrrx
Blocks
Pluto Receiver
Objects
comm.SDRRxPluto
3-6
Quadrature Tracking
References
[1] Analog Devices Wiki 'AD9361, AD9364 and AD9363 > IQ Correction', https://wiki.analog.com/
resources/eval/user-guides/ad-fmcomms2-ebz/ad9361#iq_correction
3-7
4
Radio I/O
Channel I/O
In this section...
“Transmit Data Using ADALM-PLUTO Radio Block” on page 4-2
“Receive Data Using ADALM-PLUTO Radio Block” on page 4-2
“Transmit Data Using ADALM-PLUTO Radio System Object” on page 4-3
“Receive Data Using ADALM-PLUTO Radio System Object” on page 4-3
The ADALM-PLUTO radio contains a single channel for either sending or receiving.
Example
Use the ADALM-PLUTO transmitter block to transmit data input from a GSMK modulator block.
Connect a GMSK modulator to the ADALM-PLUTO transmitter input and to indicate when transmitted
data is lost use the underflow output. Here a counter and a display output indicate a running total of
data underflows. No data has been lost if the display shows 0.
Use the ADALM-PLUTO receiver block to process data received over the air by an ADALM-PLUTO
radio.
4-2
Channel I/O
In this example clear the Enable output port for overflow indicator to hide that output. Connect a
constant block and a slider block to specify the center frequency for signal to reception. At the output
connect an FM broadcast demodulator an enable input.
tx = sdrtx('Pluto', ...
'RadioID','usb:0', ...
'CenterFrequency',2.4e9, ...
'BasebandSampleRate',1e6);
dpskMod = comm.DPSKModulator('BitInput',true);
Transmit data.
release(tx);
rx = sdrrx('Pluto');
4-3
4 Radio I/O
Receive data.
data = rx();
release(rx);
See Also
Related Examples
• “Radio Configuration”
4-4
Repeated Waveform Transmitter
You can download any signal waveform to the hardware and transmit repeatedly over the air using
one of the SDR transmitter System objects for ADALM-PLUTO radio. This feature enables you to use
SDR System objects together with the hardware as an RF signal generator. You can create any
arbitrary waveform at the baseband in MATLAB and transmit repeatedly from the hardware. You are
not limited by the USB connection or the processing speed of the host computer for signal
transmission over the air.
To call the repeated waveform transmitter, use the transmitRepeat method, found on System
objects for ADALM-PLUTO radios.
Generate a waveform.
fs = 1e6;
sw = dsp.SineWave;
sw.Amplitude = 0.5;
sw.Frequency = 100e3;
sw.ComplexOutput = true;
sw.SampleRate = fs;
sw.SamplesPerFrame = 5000; % to meet waveform size requirements
tx_waveform = sw();
Create a System object for the ADALM-PLUTO radio and set desired radio settings.
radio = sdrtx('Pluto');
radio.CenterFrequency = 2.415e9;
radio.BasebandSampleRate = fs;
radio.Gain = 0;
Send the waveform to the radio and repeatedly transmit it for 10 seconds.
runtime = tic;
while toc(runtime) < 10
transmitRepeat(radio,tx_waveform);
end
4-5
4 Radio I/O
release(radio);
To see this feature applied, look at and run “Image Transmission and Reception Using 802.11
Waveform and SDR” (WLAN Toolbox). You can examine the code in the example for ways to receive
WLAN signals.
See Also
sdrtx
Related Examples
• “Image Transmission and Reception Using 802.11 Waveform and SDR” (WLAN Toolbox)
4-6
Detect Underruns and Overruns
• On the ADALM-PLUTO radio transmitter block, clear the Enable output port for underflow
indicator parameter.
To detect underflow during the transmission of radio signals, check the underflow output port on the
SDR transmitter block.
During the simulation, check the underflow output port of the transmitter:
• On the ADALM-PLUTO radio receiver block, clear the Enable output port for overflow
indicator parameter.
To detect overflows during the reception of radio signals, check the overflow output port on the SDR
block.
4-7
4 Radio I/O
During the simulation, check the overflow output port of the receiver:
tx = sdrtx('Pluto')
txData = zeros(1000,1);
Transmit the data with tx, and return underflow as an output argument.
for counter = 1:20
underflow = tx(txData);
if (underflow)
display('### Warning transmitter underflow occurred, data has been lost.')
end
end
rx = sdrrx('Pluto')
rxData = zeros(1000,1);
Receive the data with rx, and return overflow as an output argument.
for counter = 1:20
[data,datavalid,overflow] = rx(rxData);
if (overflow)
display('### Warning receiver overflow occurred, data has been lost.')
end
end
4-8
Detect Underruns and Overruns
See Also
Functions
sdrtx | sdrtx
Blocks
Pluto Receiver | Pluto Transmitter
Objects
comm.SDRRxPluto | comm.SDRTxPluto
More About
• “Burst Mode” on page 4-10
4-9
4 Radio I/O
Burst Mode
In this section...
“Determine If You Need Burst Mode” on page 4-10
“Enable Burst Mode” on page 4-10
“Limitations” on page 4-10
If an SDR receiver block or System object cannot keep up with the radio hardware, then the model or
code is not processing data in real time. Burst mode enables you to buffer a set of contiguous samples
without losing samples by setting the number of frames in a burst.
To determine if you need burst mode, see “Detect Underruns and Overruns” on page 4-7.
The Pluto Receiver block has an Enable burst mode parameter. When you select this parameter, the
block produces a set of contiguous frames without an overrun to the radio hardware. Enable burst
mode to simulate models that cannot run in real time. Specify the amount of contiguous data using
the Frames in burst parameter.
The comm.SDRRxPluto System object has an EnableBurstMode property. When you set this
property to true, the System object produces a set of contiguous frames without an overrun to the
radio hardware. This setting can help simulate models that cannot run in real time. Specify the
amount of contiguous data using the NumFramesInBurst property.
rx.EnableBurstMode=true
EnableBurstMode: true
NumFramesInBurst: 20
Limitations
Burst mode requires a fresh set of samples from the hardware. Therefore, when you call a receiver
System object for the first time with burst mode enabled, the overflow output argument is 1.
Likewise, the first time-step of a receiver block with burst mode enabled asserts the overflow port.
4-10
Burst Mode
See Also
Functions
sdrtx | sdrrx
Blocks
Pluto Receiver | Pluto Transmitter
Objects
comm.SDRRxPluto | comm.SDRTxPluto
More About
• “Detect Underruns and Overruns” on page 4-7
4-11
5
Performance
5 Performance
Model Tuning
• Use frame-based processing. With frame-based processing, the model processes multiple samples
during a single execution call to a block. Consider using frame sizes from roughly 100 to several
thousand.
• In Model Configuration Parameters > Data Import/Export, turn off all logging.
• Make your model single rate. If the model requires resampling, then choose rational coefficients
that keep the model single rate.
• Do not add any Buffer blocks to the model. Create convenient frame sizes in your data sources.
Buffer blocks typically degrade performance.
• Avoid feedback loops. Typically, such loops imply scalar processing, which slows down the model
considerably.
• Avoid using scopes. To visualize your data, send it to a workspace variable and postprocess it.
• If your model has Constant blocks with values that do not change during simulation, make sure
that the sample time is set to Inf (default).
See Also
More About
• “MATLAB Performance Improvements” on page 5-3
• “Optimizations for Computing Environment” on page 5-4
5-2
MATLAB Performance Improvements
Vector-Based Processing
With vector-based processing, the program processes multiple samples during a single execution call
to a System object. Use large vectors of data to minimize function call overhead.
See Also
More About
• “Simulink Performance Improvements” on page 5-2
• “Optimizations for Computing Environment” on page 5-4
5-3
5 Performance
See Also
More About
• “Simulink Performance Improvements” on page 5-2
• “MATLAB Performance Improvements” on page 5-3
5-4
6
Troubleshooting
6 Troubleshooting
In this section...
“Host Not Communicating with ADALM-PLUTO Radio” on page 6-2
“Host USB Port to ADALM-PLUTO Radio Communication Unreliable” on page 6-3
“Input Must Be Complex” on page 6-3
“Overruns or Underruns” on page 6-3
“Firmware Version Warning” on page 6-4
“Hardware Setup on Windows 7 — Test ADALM-PLUTO Radio Connection Failure” on page 6-5
“Hardware Setup on Linux — Configure ADALM-PLUTO Radio Failure” on page 6-5
“Unable to Assign IP Address Radio Identity” on page 6-6
“ADALM-PLUTO Radio Is Busy” on page 6-6
“No Data from Hardware” on page 6-7
Resolve issues encountered during installation or while using the I/O mode features of the support
package.
Possible Solutions
• See “Host USB Port to ADALM-PLUTO Radio Communication Unreliable” on page 6-3
• Unplug ADALM-PLUTO radio, reboot host computer, plugin ADALM-PLUTO radio, open MATLAB
and at the command line execute:
cd(fullfile(matlab.internal.get3pInstallLocation('libiio.instrset'),'win64','MS64'))
system('iio_info -s')
• If the host can communicate with the ADALM-PLUTO radio, the radio is ready to use. In this
case, you will see an output that lists the radio serial number and USB port information similar
to the following:
...
Available contexts:
0: 0456:b673 (Analog Devices Inc. PlutoSDR (ADALM-PLUTO)), ...
serial=104473222a870010050020009db5d52277 [usb:2.11.5]
• If the host cannot communicate with the ADALM-PLUTO radio, replace the radio. In this case,
you will see an output similar to the following:
...
No contexts found.
6-2
Common Problems and Fixes
ADALM-PLUTO radio is unresponsive or commands fail especially when the radio is connected to an
unpowered USB hub.
Possible Solutions
• Plug in both USB ports on the PlutoSDR. In addition to connecting the USB communication
connector port, also connect a dedicated power source to the USB power connector port on the
PlutoSDR.
The PlutoSDR transmitter input must be complex. This is enforced due to potential for corruption of
input signal by the radio hardware IQ imbalance correction when the input transmission signal is
real-valued.
1 PlutoSDR is used in a loopback configurations (LOs for Tx and Rx are locked) and a real signal is
transmitted.
2 Two separate radios are used and the LO frequency offset is less than ~100Hz.
Possible Solutions
Overruns or Underruns
Problem
6-3
6 Troubleshooting
Possible Solutions
When using PlutoSDR with Communications Toolbox Support Package for Analog Devices ADALM-
Pluto Radio, you see this message:
The support package issues this warning to alert you when the firmware version installed on your
PlutoSDR is not recommended for use with the support package release you are running. If the
firmware version on the PlutoSDR is older than the recommended version, you must upgrade your
firmware. If the firmware version on the PlutoSDR is newer than the recommended version, you can
continue using your PlutoSDR without installing the recommended firmware.
Note MathWorks has not tested the stability or performance of PlutoSDR devices with firmware
versions newer than the recommended firmware version.
Possible Solutions
• In MATLAB on the HOME tab, select Manage Add-Ons from Add-Ons in the Environment
section.
• At the right end of the entry for Communications Toolbox Support Package for Analog Devices
ADALM-Pluto Radio, click the setup gear button
. Clicking the setup
gear button opens the Hardware Setup app to update the firmware. Complete the firmware
update by following instructions in the app.
• Continue using a firmware version that is newer than the recommended version.
• When using a newer than recommended firmware version, a warning message is occasionally
printed in the command window noting the mismatch between support package and firmware
version. The warning can be suppressed by entering the following code at the command line or
by adding it to the startup.m file where you “Specify Startup Options”.
warning('off','plutoradio:sysobj:FirmwareIncompatible');
6-4
Common Problems and Fixes
Possible Solution
Run the installer as administrator. Exit the installer and MATLAB. Start MATLAB as administrator
and start the installer again. To run as administrator, right-mouse click the MATLAB icon and select
Run as administrator.
Problem
Failure during configuration of ADALM-PLUTO radio on Linux caused by inability to change the
frequency band via the serial port. On certain Linux distributions, such as Ubuntu®, you are not able
to communicate with the radio via the serial port to configure the frequency band.
Possible Solution
analog
Welcome to:
______ _ _ _________________
6-5
6 Troubleshooting
http://wiki.analog.com/university/tools/pluto
Possible Solution
If you cannot successfully assign an IP address RadioID, and you are using Linux, these additional
steps are required to configure and identify the ADALM-PLUTO radio via IP address:
• To determine the IP and MAC addresses assigned the host computer and the IP address assigned
to the ADALM-PLUTO radio, look in info.html. For example, use the command:
grep -A 1 'IP Address (\|MAC Address (HOST)' /media/PlutoSDR*/info.html
• Determine the Ethernet port assigned to the HW address. For example, use the command:
ping -c 3 192.168.2.1
MATLAB returns this warning message from a call to the info method:
info(dev)
Warning: Cannot create a driver for the specified address. The address
6-6
Common Problems and Fixes
This message means that the radio hardware is in use by another MATLAB or Simulink session.
ADALM-PLUTO radios can become busy when any of the following conditions occur:
Possible Solution
Release the radio hardware by stopping the simulation, closing the block, or calling the release
method of the System object.
You are not receiving data from the radio hardware after streaming starts.
Possible Solutions
Reestablish Connection
If you do not have a connection, it is possible that a radio identity conflict, a bad cable, or a loss of
power is causing the problem. To reestablish connectivity:
6-7
7
Examples
7 Examples
Use the capture function and an ADALM-PLUTO radio to record RF signals for post-capture
processing in MATLAB®. Save an FM broadcast signal to a file as baseband samples. Read the file
containing the recorded signal and demodulate the baseband samples.
To configure your ADALM-PLUTO radio for host-radio communication, see “Guided Host-Radio
Hardware Setup” on page 2-3.
Attach an antenna suitable for the 88-108 MHz band to the first RX channel. The FM radio band is
outside the default tuning range for the ADALM-PLUTO radio. The configurePlutoRadio function
enables you to extend the frequency range and use your ADALM-PLUTO radio outside the qualified
tuning range. The extended frequency range includes the full FM radio band.
configurePlutoRadio('AD9364');
Create an SDR receiver System object with the specified properties. The specified center frequency
corresponds to a local FM station.
deviceName = 'Pluto';
samplerate = 528e3;
fmStationFrequency = 88.9e6; % Adjust to select an FM station nearby
rx = sdrrx(deviceName,'BasebandSampleRate',samplerate, ...
'CenterFrequency',fmStationFrequency,'OutputDataType','double');
Call the capture function, specifying the receiver object, capture duration, and file name. After
capturing the FM signal, unlock the receiver object using the release function.
capture(rx,5,'Seconds','Filename','FMRecording.bb');
release(rx);
Demodulate FM Recording
Create a comm.BasebandFileReader System object to read the captured signal and extract frames
of data from the file. Set baseband file reader to take 4400 samples per frame when reading the
saved baseband signal.
bbr = comm.BasebandFileReader('FMRecording.bb');
bbr.SamplesPerFrame = 4400;
Use the BasebandSampleRate field of the baseband file reader object to set the SampleRate
property of the demodulator. Find the BasebandSampleRate field in the MetaData structure.
Create a comm.FMBroadcastDemodulator System object. Demodulate and play back each frame of
the FM data. Use a while loop to read all frames of the captured data.
7-2
Capture RF Data to Baseband File Using ADALM-PLUTO Radio
7-3
7 Examples
This example shows how to track planes by processing automatic dependent surveillance-broadcast
(ADS-B) signals. You can use previously captured signals or receive signals in real time using an RTL-
SDR radio, ADALM-PLUTO radio or USRP™ radio. You can also visualize the tracked planes on a map
using Mapping Toolbox™.
By default, this example runs using previously captured data. Optionally, you can receive signals over-
the-air. For this, you also need one of the following:
• RTL-SDR radio and Communications Toolbox Support Package for RTL-SDR Radio.
• Pluto radio and Communications Toolbox Support Package for Analog Devices® ADALM-PLUTO
Radio.
• USRP N2xx or B2xx series radio and Communications Toolbox Support Package for USRP Radio.
For information on supported radios, see “Supported Hardware and Required Software”.
• USRP E3xx, N3xx, or X3xx series radio and Wireless Testbench Support Package for NI USRP
Radios. For information on supported radios, see “Supported Radio Devices” (Wireless Testbench).
Introduction
ADS-B is a cooperative surveillance technology for tracking aircraft. This technology enables an
aircraft to periodically broadcast its position information such as altitude, GPS coordinates, and
heading, using the Mode-S signaling scheme.
Mode-S signaling scheme uses squitter messages, which are defined as a non-solicited messages used
in aviation radio systems. Mode-S has these attributes:
Extended squitter (ADS-B) messages contain all the information in a short squitter and one of these
values:
7-4
Airplane Tracking Using ADS-B Signals
• Altitude
• Position
• Heading
• Horizontal and Vertical Velocity
The signal format of Mode-S has a sync pulse that is 8 microseconds long followed by 56 or 112
microseconds of data, as this figure shows.
Receiver Structure
This block diagram summarizes the receiver code structure. The processing has four main parts:
signal source, physical layer, message parser, and data viewer.
Signal Source
• ''Captured Signal'' - Over-the-air signals written to a file and sourced from a Baseband File
Reader object at 2.4 Msps
• ''RTL-SDR Radio'' - RTL-SDR radio at 2.4 Msps
• ''ADALM-PLUTO Radio'' - ADALM-PLUTO radio at 12 Msps
• ''USRP Radio'' - USRP radio at 20 Msps for all radios, except N310/N300 series that uses 2.4
Msps
If you set ''RTL-SDR'' or ''ADALM-PLUTO'' or ''USRP Radio'' as the signal source, the
example searches your computer for the radio an RTL-SDR radio at radio address '0' or an ADALM-
PLUTO radio at radio address 'usb:0' and uses it as the signal source.
The extended squitter message is 120 micro seconds long, so the signal source is configured to
process enough samples to contain 180 extended squitter messages simultaneously, and set
SamplesPerFrame of the signal property accordingly. The rest of the algorithm searches for Mode-S
packets in this frame of data and returns all correctly identified packets. This type of processing is
7-5
7 Examples
reffered to as batch processing. An alternative approach is to process one extended squitter message
at a time. This single packet processing approach incurs 180 times more overhead than the batch
processing, while it has 180 times less delay. Since the ADS-B receiver is delay tolerant, you use
batch processing in this example.
Physical Layer
The physical layer (PHY) processes the baseband samples from the signal source to produce packets
that contain the PHY layer header information and raw message bits. This diagram shows the
physical layer structure.
The RTL-SDR radio can use a sampling rate in the range [200e3, 2.8e6] Hz. When the source is an
RTL-SDR radio, the example uses a sampling rate of 2.4 MHz and interpolates by a factor of 5 to a
practical sampling rate of 12 MHz.
The ADALM-PLUTO radio can use a sampling rate in the range [520e3, 61.44e6] Hz. When the source
is an ADALM-PLUTO, the example samples the input directly at 12 MHz.
The USRP radios are capable of using different sampling rates. When the USRP radio is the source,
the example samples the input directly at 20 MHz sample rate for most of the radios. For the N310/
N300 radio the data is received at 2.4 MHz sample rate and interpolates by a factor of 5 to a practical
sampling rate of 12e6.
For example, if the data rate is 1 Mbit/s and the effective sampling rate is 12 MHz, the signal contains
12 samples per symbol. The receive processing chain uses the magnitude of the complex symbols.
The packet synchronizer works on subframes of data equivalent to two extended squitter packets,
that is, 1440 samples at 12 MHz or 120 micro seconds. This subframe length ensures that the
subframe contains whole extended squitter. The packet synchronizer first correlates the received
signal with the 8 microsecond preamble and finds the peak value. The synchronizer then validates the
synchronization point by checking if it matches the preamble sequence, [1 0 0 0 0 0 1 0 1 0 0 0 0 0 0],
where a value of 1 represents a high value and a value of 0 represents a low value.
The Mode-S PPM scheme defines two symbols. Each symbol has two chips, where one has a high
value and the other has a low value. If the first chip is high and the subsequent chip is low, the symbol
is 1. Alternatively, if the first chip is low and the subsequent chip is high chip, then the symbol is 0.
The bit parser demodulates the received chips and creates a binary message. A CRC checker then
validates the binary message. The output of the bit parser is a vector of Mode-S physical layer header
packets that contain these fields:
7-6
Airplane Tracking Using ADS-B Signals
Message Parser
The message parser extracts data from the raw bits based on the packet type described in [ 2 ]. This
example can parse short squitter packets and extended squitter packets that contain airborne
velocity, identification, and airborne position data.
Data Viewer
The data viewer shows the received messages on a graphical user interface (GUI). For each packet
type, the data viewer shows the number of detected packets, the number of correctly decoded
packets, and the packet error rate (PER). As the radio captures data, the application lists information
decoded from these messages in a table.
The receiver prompts you for user input and initializes variables. After you set the input values call
the signal source, physical layer, message parser, and data viewer in a loop. The loop keeps track of
the radio time using the frame duration.
% The default configuration runs using captured data. You can set
% |cmdlineInput| to |1|, then run the example to optionally change these
% configuration settings:
% # Reception duration in seconds,
% # Signal source (captured data or RTL-SDR radio or ADALM-PLUTO radio or USRP radio),
% # Optional output methods (map and/or text file).
% Create the data viewer object and configure based on user input
viewer = helperAdsbViewer('LogFileName',userInput.LogFilename, ...
'SignalSourceType',userInput.SignalSourceType);
if userInput.LogData
startDataLog(viewer);
end
if userInput.LaunchMap
startMapUpdate(viewer);
end
7-7
7 Examples
% Main loop
while radioTime < userInput.Duration
if adsbParam.isSourceRadio
if adsbParam.isSourcePlutoSDR
[rcv,~,lostFlag] = sigSrc();
else
[rcv,~,lost] = sigSrc();
lostFlag = logical(lost);
end
else
rcv = sigSrc();
lostFlag = false;
end
7-8
Airplane Tracking Using ADS-B Signals
7-9
7 Examples
You can also observe the airplanes on a map if you have a Mapping Toolbox license.
7-10
Airplane Tracking Using ADS-B Signals
Further Exploration
You can investigate ADS-B signals using the ADSBExampleApp app. Use this app to select the signal
source and change the duration. To launch the app, enter ADSBExampleApp in the MATLAB
Command Window.
References
1 International Civil Aviation Organization, Annex 10, Volume 4. Surveillance and Collision
Avoidance Systems.
2 Technical Provisions For Mode S Services and Extended Squitter (Doc 9871)
7-11
7 Examples
This example shows you how to use Communications Toolbox™ to read utility meters by processing
Standard Consumption Message (SCM) signals and Interval Data Message (IDM) signals which are
emitted by Encoder-Receiver-Transmitter (ERT) compatible meters. You can either use recorded data
from a file, or receive over-the-air signals in real time using an RTL-SDR or ADALM-PLUTO radio.
In Simulink®, you can explore the “Automatic Meter Reading in Simulink” example.
To run this example using recorded data from a file, you need Communications Toolbox™.
To receive signals in real time, you also need one of these SDR devices and the corresponding
software add-on:
• RTL-SDR radio and the Communications Toolbox Support Package for RTL-SDR Radio add-on
• ADALM-PLUTO radio and the Communications Toolbox Support Package for Analog Devices®
ADALM-PLUTO Radio add-on
For more information, see the Software Defined Radio (SDR) discovery page.
Background
Automatic Meter Reading (AMR) is a technology that autonomously collects the consumption and
status data from utility meters (such as electric, gas, or water meters) and delivers the data to utility
providers for billing or analysis purposes. The AMR system utilizes low power radio frequency (RF)
communication to transmit meter readings to a remote receiver. The RF transmission properties
include:
The SCM and IDM are two types of the conventional message types that the meters send out. The
SCM packets are used with a fixed length of 96 bits, whereas IDM packets are used with a fixed
length of 736 bits. These tables show the packet format of the SCM and IDM messages:
7-12
Automatic Meter Reading
Meters capable of sending both SCM and IDM messages transmit them on the same channel with
separation of roughly 275 msec. Each meter transmits the SCM and IDM messages over multiple
frequencies using a hopping pattern. The actual transmission frequencies, the frequency hopping
pattern, and the time interval between transmissions are random to avoid interference from other
transmissions. For more information, see reference [ 1 ].
Run Example
• The receiver initializes the simulation parameters and calculates the AMR parameters.
• A data viewer display shows the meter ID, consumption information, and commodity type.
• The simulation loop calls the signal source, physical layer, message parser, and data viewer.
• The processing loop keeps track of the radio time using the frame duration.
• The display updates for each data capture, showing unique meter IDs with the latest consumption
information.
Initialize Parameters
The default signal source is 'File', which runs the example using the recorded baseband signal file
amr_capture_01.bb. To run the example using your RTL or ADALM-PLUTO SDR, change the
setting for signalSource when you call the helperAMRInit.m file. Valid options for
signalSource are 'File', 'RTL-SDR', and 'ADALM-PLUTO'.
signalSource = 'File';
initParam = helperAMRInit(signalSource);
7-13
7 Examples
start(viewer);
radioTime = 0; % Initialize the radio time
The flow chart summarizes the receiver code structure. The processing has four main parts: Signal
Source, Physical Layer, Message Parser and Data Viewer.
Signal Source
7-14
Automatic Meter Reading
1 ''File'': Over-the-air signals written to a file and read using a Baseband File Reader object at 1.0
Msps
2 ''RTL-SDR'': RTL-SDR radio at a sample rate of 1.0 Msps
3 ''ADALM-PLUTO'': ADALM-PLUTO radio at a sample rate of 1.0 Msps
If you assign ''RTL-SDR'' or ''ADALM-PLUTO'' as the signal source, the example searches your
computer for the radio you specified, either an RTL-SDR radio at radio address '0' or an ADALM-
PLUTO radio at radio address 'usb:0' and uses it as the signal source.
Physical Layer
The baseband samples received from the signal source are processed by the physical layer (PHY) to
produce packets that contain the SCM or IDM information. This diagram shows the physical layer
receive processing.
The RTL-SDR radio is capable of using a sampling rate in the range of 225-300 kHz or 900-2560 kHz.
The ADALM-PLUTO radio is capable of using a sampling rate in the range of 520 kHz-61.44 MHz. A
sampling rate of 1.0 Msps is used to produce a sufficient number of samples per Manchester encoded
data bit. For each frequency in the hopping pattern, every AMR data packet is transmitted. The
frequency hopping allows for increased reliability over time. Since every packet is transmitted on
each frequency hop, it is sufficient to monitor only one frequency for this example. The radio is tuned
to a center frequency of 915 MHz for the entire simulation runtime.
The received complex samples are amplitude demodulated by extracting their magnitude. The on-off
keyed Manchester coding implies the bit selection block includes clock recovery. This block outputs
bit sequences (ignoring the idle times in the transmission) which are subsequently checked for the
known preamble. If the preamble matches, the bit sequence is further decoded, otherwise, it is
discarded and the next sequence is processed.
When the known SCM preamble is found for a bit sequence, the received message bits are decoded
using a shortened (255,239) BCH code which can correct up to two bit errors. In the case where the
known IDM preamble is found, the receiver performs a cyclic redundancy check (CRC) of the meter
serial number and of the whole packet starting at the Packet type (the 5th byte) to determine if the
packet is valid. Valid, corrected messages are passed onto the AMR message parser.
Message Parser
For a valid message, the bits are then parsed into the specific fields of the SCM or the IDM format.
Data Viewer
7-15
7 Examples
The data viewer shows the decoded packets on a separate MATLAB® figure. For each successfully
decoded packet, the meter ID, commodity type, AMR packet type, consumption information and the
capture time is shown. As data is captured and decoded, the application lists the information decoded
from these messages in a tabular form. The table lists only the unique meter IDs with their latest
consumption information.
You can also change the meter ID and start text file logging using the data viewer.
• Meter ID - Change the meter ID from 0, which is the default value and is reserved for displaying
all detected meters, to a specific meter ID which you would like to be displayed.
• Log data to file - Save the decoded messages in a TXT file. You can use the saved data for post
processing.
Further Exploration
The data file accompanying the example has only one meter reading and has been captured at center
frequency of 915 MHz. Using RTL-SDR or ADALM-PLUTO, the example will display readings from
multiple meters when it is run for a longer period in a residential neighborhood.
You can further explore AMR signals using the AMRExampleApp user interface. This app allows you
to select the signal source and change the center frequency of the RTL-SDR or ADALM-PLUTO. This
link launches the AMRExampleApp app shown here.
You can also explore the following functions for details of the physical layer, AMR message formats:
• helperAMRRxPHY.m
• helperAMRRxDiscreteEvent.m
• helperAMRRxBitParser.m
• helperAMRMessageParser.m
7-16
Automatic Meter Reading
For a version of the example that works with multiple radios, see AMRMultipleRadios.m. The
multiple radio version allows you to examine the frequency hop patterns for a meter by setting
different center frequencies per radio device available. The script is set for two radios, but can be
extended for any number.
Selected Bibliography
7-17
7 Examples
FM Broadcast Receiver
This example shows how to build an FM mono or stereo receiver. You can either use recorded data
from a file, or receive signals in real time using the RTL-SDR Radio, ADALM-PLUTO Radio, or USRP™
Radio.
By default, this example runs using recorded data from a file. Optionally, you can receive signals over-
the-air. For this, you also need one of the following:
Background
FM broadcasting uses frequency modulation (FM) to provide high-fidelity sound transmission over
broadcast radio channels. Pre-emphasis and de-emphasis filters are used to reduce the effect of noise
on high audio frequencies. Stereo encoding enables simultaneous transmission of both left and right
audio channels over the same FM channel [ 1 ].
To and run the example, you need to enter the following information:
The example plays the received audio over your computer's speakers.
NOTE: This example utilizes a center frequency that is outside the default PlutoSDR tuning range. To
use your ADALM-PLUTO radio outside the qualified tuning range, at the MATLAB® command line,
run configurePlutoRadio using 'AD9364' as the input argument.
Receiver Structure
The FM Broadcast Demodulator Baseband System object™ converts the input sampling rate of the
228 kHz to 45.6 kHz, the sampling rate for your host computer's audio device. According to the FM
broadcast standard in the United States, the de-emphasis lowpass filter time constant is set to 75
microseconds. This example processes the received mono signals. The demodulator can also process
stereo signals.
To perform stereo decoding, the FM Broadcast Demodulator Baseband object uses a peaking filter
which picks out the 19 kHz pilot tone from which the 38 kHz carrier is created. Using the resulting
carrier signal, the FM Broadcast Demodulator Baseband block downconverts the L-R signal, centered
at 38 kHz, to baseband. Afterwards, the L-R and L+R signals pass through a 75 microsecond de-
7-18
FM Broadcast Receiver
emphasis filter. The FM Broadcast Demodulator Baseband block separates the L and R signals and
converts them to the 45.6 kHz audio signal.
Example Code
The receiver asks for user input and initializes variables. Then, it calls the signal source and FM
broadcast receiver in a loop. The loop also keeps track of the radio time using the frame duration and
lost samples reported by the signal source.
The latency output of the signal source is an indication of when the samples were actually received
and can be used to determine how close to real time the receiver is running. A latency value of 1 and
a lost samples value of 0 indicates that the system is running in real time. A latency value of greater
than one indicates that the receiver was not able to process the samples in real time. Latency is
reported in terms of the number of frames. It can be between 1 and 128. If latency is greater than
128, then samples are lost.
% Main loop
while radioTime < userInput.Duration
% Receive baseband samples (Signal Source)
if fmRxParams.isSourceRadio
if fmRxParams.isSourcePlutoSDR
rcv = sigSrc();
lost = 0;
late = 1;
elseif fmRxParams.isSourceUsrpRadio
rcv= sigSrc();
lost = 0;
else
[rcv,~,lost,late] = sigSrc();
end
7-19
7 Examples
else
rcv = sigSrc();
lost = 0;
late = 1;
end
% Update radio time. If there were lost samples, add those too.
radioTime = radioTime + fmRxParams.FrontEndFrameTime + ...
double(lost)/fmRxParams.FrontEndSampleRate;
end
Further Exploration
To further explore the example, you can vary the center frequency of the RTL-SDR radio, ADALM-
PLUTO radio or USRP radio and listen to other radio stations.
You can set the Stereo property of the FM demodulator object to true to process the signals in stereo
fashion and compare the sound quality.
You can explore following function for details of the system parameters:
• helperFMConfig.m
You can further explore the FM signals using FMReceiverExampleApp user interface. This app allows
you to select the signal source and change the center frequency of the RTL-SDR radio, ADALM-
PLUTO radio or USRP radio. To launch the app, type FMReceiverExampleApp in the MATLAB
Command Window. This user interface is shown in the following figure
7-20
FM Broadcast Receiver
Selected Bibliography
1 https://en.wikipedia.org/wiki/FM_broadcasting
7-21
7 Examples
This example shows how to synchronize both the baseband sample rate and the center frequency of
two PlutoSDRs by using the FrequencyCorrection property of comm.SDRRxPluto and
comm.SDRTxPluto.
The baseband sample rate and the center frequency of a PlutoSDR are physically derived from the
same oscillator. Although each PlutoSDR is factory-calibrated to use appropriate PLL settings to
digitally compensate for component variations of the oscillator, the compensation is imperfect
because of quantization effects and changes in operating conditions (temperature in particular).
Consequently, two PlutoSDRs will operate at slightly different baseband sample rates and center
frequencies even if the corresponding System objects for the two PlutoSDRs use the same values for
the BasebandSampleRate and CenterFrequency properties. To solve this problem, the
FrequencyCorrection property of comm.SDRRxPluto and comm.SDRTxPluto can be used.
The FrequencyCorrection property specifies the parts-per-million change to the baseband sample rate
and the center frequency. The default value is 0, which means that the radio will use its factory-
calibrated PLL settings. In this example, we treat one PlutoSDR, the transmitter, as a source with
accurate baseband sample rate and center frequency. We use the signal received by another
PlutoSDR, the receiver, to estimate the right value of FrequencyCorrection for the receiver System
object, and show that when FrequencyCorrection is set appropriately, the frequency offset between
the transmitter and the receiver will be removed almost completely.
Refer to the “Guided Host-Radio Hardware Setup” on page 2-3 documentation for details on
configuring your host computer to work with the PlutoSDR.
Consider a signal transmitted from one PlutoSDR to another PlutoSDR. Let and be the center
frequency and the baseband sample rate of the transmitter. Let and be the center frequency and
the baseband sample rate of the receiver. Assume that the oscillator of the transmitter has not drifted
and the oscillator of the receiver has drifted by a factor , i.e. and where
is a number very close to 1.
A tone at baseband frequency in the transmitted signal will appear as a tone at baseband
To remove the frequency offset between the transmitter and the receiver, we need to scale the
baseband sample rate and the center frequency of the receiver by a factor of . Let be the parts-
per-million change to the baseband sample rate and the center frequency of the receiver. Then
. Therefore .
7-22
Frequency Correction for ADALM-PLUTO Radio
We use one PlutoSDR to transmit three tones at 20, 40, and 80 kHz. The tone at 80 kHz is used to
estimate the value for FrequencyCorrection for the receiver. The tones at 20 and 40 kHz are only
used to help visualize the spectrum.
txRadioInfo =
7-23
7 Examples
rxRadioInfo =
7-24
Frequency Correction for ADALM-PLUTO Radio
Based on the tone detected at 60.093 kHz, FrequencyCorrection of the receiver should be set to -8
rxRadioInfo =
7-25
7 Examples
EnableRFDCTracking: 1
EnableBasebandDCTracking: 1
FrequencyCorrection: -8.2250
% Capture 10 frames, but only use the last frame to skip the transient
% effects due to changing FrequencyCorrection
disp(['Capture signal and verify frequency correction' newline])
for i = 1:10
receivedSig = rx();
end
7-26
Frequency Correction for ADALM-PLUTO Radio
Now we change the FrequencyCorrection property of the transmitter to simulate the effect that the
transmitter's oscillator has drifted.
Change the FrequencyCorrection property of the transmitter to 1 to simulate the effect that the t
txRadioInfo =
7-27
7 Examples
% Capture 10 frames, but use the last frame only to skip the transient
% effects due to changing FrequencyCorrection
disp(['Capture signal and observe the frequency offset' newline])
for i = 1:10
receivedSig = rx();
end
7-28
Frequency Correction for ADALM-PLUTO Radio
We use the same method to estimate the required parts-per-million change to the baseband sample
rate and the center frequency of the receiver. However, the estimated value needs to be combined
appropriately with the current setting of FrequencyCorrection, which is nonzero. Since
, applying two changes and
successively is equivalent to applying a single change of with respect to the
factory-calibrated condition.
rxRadioInfo = info(rx);
currentPPM = rxRadioInfo.FrequencyCorrection;
ppmToAdd = (fReceived3 - fRef) / (centerFreq + fRef) * 1e6;
rx.FrequencyCorrection = currentPPM + ppmToAdd + currentPPM*ppmToAdd/1e6;
msg = sprintf(['Based on the tone detected at %.3f kHz, ' ...
'FrequencyCorrection of the receiver should be changed from %.4f to %.4f'], ...
fReceived3/1000, currentPPM, rx.FrequencyCorrection);
disp(msg);
rxRadioInfo = info(rx)
Based on the tone detected at 82.309 kHz, FrequencyCorrection of the receiver should be changed f
rxRadioInfo =
7-29
7 Examples
CenterFrequency: 2.4200e+09
BasebandSampleRate: 200000
SerialNum: '1044734c9605001118000d00408f4fdca4'
GainControlMode: 'AGC Slow Attack'
RadioFirmwareVersion: "0.31"
ExpectedFirmwareVersion: "0.34"
HardwareVersion: "B0"
EnableQuadratureTracking: 1
EnableRFDCTracking: 1
EnableBasebandDCTracking: 1
FrequencyCorrection: -7.2750
% Capture 10 frames, but use the last frame only to skip the transient
% effects due to changing FrequencyCorrection
disp(['Capture signal and verify frequency correction' newline])
for i = 1:10
receivedSig = rx();
end
7-30
Frequency Correction for ADALM-PLUTO Radio
7-31
7 Examples
This example shows how to extract program or song information from FM radio stations using the
RDS or RBDS standard and, optionally, the RadioText Plus (RT+) standard. You can use a previously
captured signal, or receive signals over-the-air in real time using an RTL-SDR radio, an ADALM-
PLUTO radio, or a USRP™ radio.
By default, this example runs using recorded data from a file. Optionally, you can receive signals over-
the-air using a device that supports the required sample rate of 228 ksps. For this, you also need one
of the following:
• RTL-SDR radio and Communications Toolbox Support Package for RTL-SDR Radio.
• ADALM-PLUTO radio and Communications Toolbox Support Package for ADALM-PLUTO Radio.
• USRP B2xx series radio and Communications Toolbox Support Package for USRP Radio. For
information on supported radios, see “Supported Hardware and Required Software”.
• USRP E3xx series radio and Wireless Testbench Support Package for NI USRP Radios. For
information on supported radios, see “Supported Radio Devices” (Wireless Testbench).
Background
RBDS and RDS are very similar standards specifying how to supplement FM radio signals with
additional information. RBDS is used in North America, while RDS was originally used in Europe and
evolved to an international standard. RBDS and RDS comprise 3 layers:
The RBDSPhyDecoder helper receives the captured signal from a file or the live signal from the radio
and performs these steps:
• FM demodulation: Once the FM signal is demodulated, the RDS/RBDS signal resides at the 57
kHz +/- 2.4 kHz band. Be aware that the RDS/RBDS signal is transmitted with relatively low
power, so it is not always visible in the FM spectrum as shown in this figure.
7-32
RDS/RBDS and RadioText Plus (RT+) FM Receiver
FM signals contain a pilot tone at 19 kHz, which can be used as a phase and frequency reference for
coherent demodulation of the RDS/RBDS signal at 57 kHz and the stereo audio at 38 kHz. Pilot tones
at 38 kHz and 57 kHz can be generated by doubling and tripling the frequency of the 19 kHz pilot
tone [ 2 ] on page 7-40.
• Bandpass filtering: The PHY receiver conducts bandpass filtering at 19 kHz and 57 kHz, to
isolate the pilot tone and the RDS/RBDS signal, respectively.
• Frequency tripling: Raise the complex representation of the 19 kHz pilot tone to the 3rd power
to triple its frequency and obtain a 57 kHz pilot tone.
• AM Demodulation: RDS and RBDS symbols are generated at an 1187.5 Hz rate and are AM-
modulated to a 57 kHz carrier. The 57 kHz RDS/RBDS signal can be coherently demodulated with
a 57 kHz carrier that is locked in frequency and phase. Typically, the frequency-tripled 19 kHz
pilot tone suffices for coherent demodulation. The next figures show the 19 kHz and 57 kHz pilot
tones, the 57 kHz RDS/RBDS signal, and the AM-demodulated baseband RDS/RBDS signal.
7-33
7 Examples
At the same time, there exist several FM stations whose 57 kHz RDS/RBDS signal exhibits a time-
varying phase offset from the 19 kHz pilot tone and its frequency-tripled version. The PHY receiver
contains a Costas loop to compensate for such time-varying phase offsets.
• Costas loop: The Costas loop performs 2 orthogonal AM demodulations, one demodulation with a
57 kHz sine and another with a 57 kHz cosine. The sampling rate of the received signal is
carefully chosen as 228 kHz, which provides 4 samples per 57 kHz cycle. Therefore, a one sample
delay of the 57 kHz pilot tone results to a one quarter wavelength phase offset, and allows us to
generate a cosine wave from a sine wave. The sine-demodulated signal corresponds to the
coherent demodulation output. The cosine-demodulated signal is used for detection of phase error.
The products of the 57 kHz RDS/RBDS signal with the sine/cosine waves are low-pass filtered with
the filter specified in Sec. 1.7 of [ 1 ] on page 7-40. The product of the two filter outputs is an
error signal. The larger it is, the more the 19 kHz pilot tone is delayed to behave more like the
cosine-based demodulator.
• Clock extraction: To perform biphase symbol decoding, a clock matching the RDS/RBDS symbol
rate of 1187.5 Hz is extracted from the 19 kHz pilot tone. Note, 1187.5 Hz x 16 = 19 kHz. To
account for frequency offsets, frequency division is used to extract the clock from the 19 kHz pilot
tone. Since the frequency division operation provides multiple correct answers, the baseband
RDS/RBDS signal serves as training data that aid in the determination of the desired output.
7-34
RDS/RBDS and RadioText Plus (RT+) FM Receiver
• Biphase symbol decoder: RDS and RBDS use bi-phase-level (bi- ϕ -L) coding, which is commonly
known as Manchester coding. In each clock cycle, the RDS/RBDS symbol takes two opposite
amplitude values, either a positive followed by a negative, or a negative followed by a positive.
The biphase symbol decoder negates the second amplitude level, so that each symbol holds the
same amplitude level throughout the entire clock cycle. The new clock-wide amplitude level
corresponds to the symbol's bit representation. These plots correspond to the waveforms #1-6 in
Figure 2 of [ 1 ] on page 7-40.
To obtain each symbol's bit value, the waveform is integrated over each clock cycle, and the outcome
is compared to zero (slicer).
7-35
7 Examples
• Differential decoding: Finally, the bits are differentially decoded to revert the differential
encoding at the transmitter.
Layer 2 is implemented using the RBDSDataLinkDecoder helper. This layer is responsible for
synchronization and error correction.
The bit output of the PHY layer is logically organized in 104-bit groups comprising four 26-bit blocks.
Each block contains a 16-bit information word and 10 parity bits (see Figure 8 in [ 1 ] on page 7-40).
A distinct 10-bit offset word is modulo-2 added to the parity bits of each block.
• Synchronization: Initially, block and group boundaries are sought exhaustively using a sliding
window of 104 bits. For each 104-bit window, the 4 offset words are sought at the last 10 bits of
each 26-bit block. An offset word is identified if no bit errors are detected by the
RBDSErrorDetection helper. Once the offset words are identified, group-level synchronization is
7-36
RDS/RBDS and RadioText Plus (RT+) FM Receiver
attained and the exhaustive sliding-window processing stops. Subsequently, the next 104 bits will
be treated as the next group.
If future groups contain bit errors and the offset words cannot be identified at their expected
position, synchronization may be lost. In this case, Layer 2 first examines the possibility of 1-bit
synchronization slips, exploiting the fact that the first information word (16 bits) is always the same
for all bit groups. If the first information word is found dislocated by 1 bit (either leftward or
rightward), synchronization is retained and the group boundaries are adjusted accordingly. If bit
errors persist for 25 group receptions and at the same time synchronization cannot be reestablished
using such leftward/rightward 1-bit shifts, then synchronization is lost and Layer 2 re-enters the
exhaustive, sliding-window-based search for synchronization.
• Error correction: The RDS/RBDS error correction code is a (26, 16) cyclic code shortened from
(341, 331). The RBDSErrorCorrection helper uses the shift-register scheme described in Annex
B of [ 1 ] on page 7-40.
Layer 2 removes the parity/offset bits, therefore Layer 3 receives groups of 64-bits, comprising four
16-bit blocks. There exist up to 32 different group types, each labeled with a number from 0 to 15 and
the letter 'A' or 'B', for example, 0B, 2A, 3A. The format of each group can be fixed or it can be
abstract if this group is allocated for an Open Data Application (ODA, see list in [ 3 ] on page 7-40).
Layer 3 is implemented using the RBDSSessionDecoder helper. This object supports decoding of the
0A, 0B, 2A, 2B, 3A, 4A, 10A fixed-format group types.
For ODAs, the RDS/RBDS receiver supports decoding of RadioText Plus (RT+). This ODA can break
down the long 32- or 64-character string from group types 2A or 2B into two specific content types
(for example, artist and song).
The RDS/RBDS receiver is extensible. ODA implementations can be specified using the
registerODA' function of the RBDSSessionDecoder helper. This function accepts the hexadecimal
ID of the ODA (ODA IDs can be found in [ 3 ] on page 7-40), and handles to the functions that
process the main ODA group type, as well as the ODA-specific part of the 3A group type. For example,
the session decoder RBDSSessionDecoder object can be extended for RadioText Plus (RT+) using
this code:
rtID = '4BD7'; % hexadecimal ID of RadioText Plus (RT+)
registerODA(sessionDecoder, rtID, @RadioTextPlusMainGroup,
@RadioTextPlus3A);
Use the helperRBDSInit helper function to set RDS/RBDS system parameters. The commented
code lines shows alternate settings to run the example from captured data or various SDRs. Use the
helperRBDSConfig helper function to configure the RDS/RBDS system.
7-37
7 Examples
userInput = helperRBDSInit();
userInput.Duration = 10.8;
% userInput.SignalSource = 'File';
% userInput.SignalFilename = 'rbds_capture.bb';
% userInput.SignalSource = 'RTL-SDR';
% userInput.CenterFrequency = 98.5e6;
% userInput.SignalSource = 'ADALM-PLUTO';
% userInput.CenterFrequency = 98.5e6;
% userInput.SignalSource = 'USRP';
% userInput.CenterFrequency = 98.5e6;
Create and configure an FM broadcast receiver System object™ with the RDS/RBDS parameters.
fmBroadcastDemod = comm.FMBroadcastDemodulator(...
'SampleRate',228e3, ...
'FrequencyDeviation',rbdsParam.FrequencyDeviation, ...
'FilterTimeConstant',rbdsParam.FilterTimeConstant, ...
'AudioSampleRate',rbdsParam.AudioSampleRate, ...
'Stereo',true);
% Layer 2 object
datalinkDecoder = RBDSDataLinkDecoder();
% Layer 3 object
sessionDecoder = RBDSSessionDecoder();
% register processing implementation for RadioText Plus (RT+) ODA:
rtID = '4BD7';
registerODA( ...
sessionDecoder,rtID,@RadioTextPlusMainGroup,@RadioTextPlus3A);
7-38
RDS/RBDS and RadioText Plus (RT+) FM Receiver
% Stop the viewer and release the signal source and audio writer
stop(viewer);
release(sigSrc);
release(player);
Viewing Results
7-39
7 Examples
• Open data applications (ODA): If any 3A group types are received, this ODA list displays the
name and the dedicated group type for each ODA received.
Further Exploration
You can further explore RDS/RBDS signals using the RBDSExampleApp app. The RBDSExampleApp
app allows you to:
• Select the source of the signal (capture file or RTL-SDR, ADALM-PLUTO or USRP).
• Specify the station frequency (for RTL-SDR, ADALM-PLUTO or USRP).
• Run Layers 1 and 2 of the RDS/RBDS receiver though generated C code. These are the most time-
consuming parts of the RDS/RBDS chain and generating code can help you achieve real-time
processing.
• Disable audio playback.
• Open scopes, such as a Spectrum Analyzer and Time Scopes, that analyze the received signal and
illustrate the decoding process. Enabling scopes requires extra computational effort and may
preclude real-time decoding. In this case, RDS/RBDS decoding may only be successful for
captured signals loaded from a file.
• Log RBDS fields from other group types by selecting Log data to file.
You can explore the RBDS implementation, initialization, and configuration in these functions and
System objects:
• RBDSPhyDecoder
• RBDSCostasLoop
• RBDSDataLinkDecoder
• RBDSSessionDecoder
• helperRBDSInit
• helperRBDSConfig
References
1. National Radio Systems Committee, United States RBDS standard, April 1998
5. Joseph P. Hoffbeck, "Teaching Communication Systems with Simulink® and the USRP", ASEE
Annual Conference, San Antonio, TX, June 2012
7-40
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals
This example shows how to train a semantic segmentation network using deep learning for spectrum
monitoring. One of the uses of spectrum monitoring is to characterize spectrum occupancy. The
neural network in this example is trained to identify 5G NR, LTE, and WLAN signals in a wideband
spectrogram.
Introduction
Computer vision uses the semantic segmentation technique to identify objects and their locations in
an image or a video. In wireless signal processing, the objects of interest are wireless signals, and the
locations of the objects are the frequency and time occupied by the signals. In this example we apply
the semantic segmentation technique to wireless signals to identify spectral content in a wideband
spectrogram.
1 The “Capture and Label NR and LTE Signals for AI Training” (Wireless Testbench) example
shows how to scan, capture, and label bandwidths with 5G NR and LTE signals using an SDR.
2 The “WLAN Activity Scanner” (Wireless Testbench) example shows how to scan and capture
WLAN signals using an SDR.
3 This example shows how to train a semantic segmentation network to identify 5G NR and LTE
signals in a wideband spectrogram.
4 The “Identify LTE and NR Signals from Captured Data Using SDR and Deep Learning” (Wireless
Testbench) example shows how to use a deep learning trained semantic segmentation network to
identify NR and LTE signals from wireless data captured with a SDR.
7-41
7 Examples
One advantage of wireless signals in the deep learning domain is the fact that the signals are
synthesized. Also, we have highly reliable channel and RF impairment models. As a result, instead of
collecting and manually labeling signals, you can generate 5G NR signals using 5G Toolbox™, LTE
signals using LTE Toolbox™, and WLAN signals using WLAN Toolbox™ functions. You can pass these
signals through standards-specified channel models to create the training data.
Train the network with frames that contain only 5G NR, LTE, or WLAN signals and then shift these
signals in frequency randomly within the band of interest. Each frame is 40 ms long, which is the
duration of 40 subframes. The network assumes that the 5G NR, LTE, or WLAN signal occupies the
same band for the whole frame duration. To test the network performance, create frames that contain
both 5G NR and LTE signals, 5G NR and WLAN signals, or LTE and WLAN signals on distinct random
bands within the band of interest.
Use a sampling rate of 61.44 MHz. This rate is high enough to process most of the latest standard
signals and several low-cost software defined radio (SDR) systems can sample at this rate providing
about 50 MHz of useful bandwidth. To monitor a wider band, you can increase the sample rate,
regenerate training frames and retrain the network.
7-42
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals
Use the nrCDLChannel (5G Toolbox),the lteFadingChannel (LTE Toolbox), and the
wlanTGaxChannel (WLAN Toolbox) functions to add channel impairments. For details of the channel
configurations, see the helperSpecSenseTrainingData function. This table lists channel
parameters.
7-43
7 Examples
the configuration of your computer. Using a PC with Intel® Xeon® W-2133 CPU @ 3.60GHz and
creating a parallel pool with six workers with the Parallel Computing Toolbox™, training data
generation takes about an hour. Choose "Train network now" to train the network. This process takes
about 8 minutes with the same PC and NVIDIA® Titan V GPU. Choose "Use trained network" to skip
network training. Instead, the example downloads the trained network.
Use 900 frames from each set of signals: 5G NR only, LTE only, WLAN only, and combination of two of
the three possible types of signals. If you increase the number of possible values for the system
parameters, increase the number of training frames.
The downloaded training data also includes captured, preprocessed, and labeled data for LTE, 5G,
WLAN, and unknown signals over a wideband. For more information, see the “Capture and Label NR
and LTE Signals for AI Training” (Wireless Testbench) and “WLAN Activity Scanner” (Wireless
Testbench) examples.
trainingDataSource = ;
trainNow = ;
useCapturedData = ;
if trainingDataSource == "Generated data"
numFramesPerStandard = 900;
saveChannelInfo = false;
helperSpecSenseTrainingData(numFramesPerStandard,classNames,imageSize, ...
trainDirRoot,numSubFrames,sampleRate,saveChannelInfo);
end
You have the choice of training a semantic segmentation network from scratch, or applying transfer
learning to a pretrained semantic segmentation network.
• To apply transfer learning, set baseNetwork to the desired pretrained network architecture.
• To train a custom network from scratch, set baseNetwork to "custom".
The baseNetwork is set to resnet18 (Deep Learning Toolbox). If the Deep Learning Toolbox™
Model for ResNet-18 Network support package is not installed, then the function provides a link to
the required support package in the Add-On Explorer. To install the support package, click the link,
and then click Install. Check that the installation is successful by typing resnet18 at the command
line. If the required support package is installed, then the function returns a dlnetwork object. For
more information, see“Make Predictions Using dlnetwork Object” (Deep Learning Toolbox).
7-44
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals
baseNetwork = ;
trainDir = fullfile(trainDirRoot,'256x256');
imageSize = [256 256];
helperSpecSenseDownloadData(trainingDataSource,trainNow,useCapturedData, ...
baseNetwork,imageSize)
Use the imageDatastore function to load training images with the spectrogram of 5G NR, LTE, and
WLAN signals. The imageDatastore function enables you to efficiently load a large collection of
images from disk. Spectrogram images are stored in .png files.
folders = trainDir;
if useCapturedData
folders = [folders,fullfile(trainDir,"captured")];
end
imds = imageDatastore(folders,FileExtensions=".png");
Use the pixelLabelDatastore (Computer Vision Toolbox) function to load spectrogram pixel label
image data. Each pixel is labeled as one of "NR", "LTE", "Noise", "WLAN" or "Unknown". A pixel label
datastore encapsulates the pixel label data and the label ID to a class name mapping. Pixel labels are
stored in .hdf files.
numClasses = length(classNames);
pixelLabelID = floor((0:numClasses-1)/(numClasses-1)*255);
pxdsTruthLTENRWLAN = pixelLabelDatastore(folders,classNames,pixelLabelID,...
FileExtensions=".hdf");
To see the distribution of class labels in the training dataset, use the countEachLabel (Computer
Vision Toolbox) function to count the number of pixels by class label, and plot the pixel counts by
class.
tbl = countEachLabel(pxdsTruthLTENRWLAN);
frequency = tbl.PixelCount/sum(tbl.PixelCount);
figure
bar(1:numel(classNames),frequency)
grid on
xticks(1:numel(classNames))
xticklabels(tbl.Name)
7-45
7 Examples
xtickangle(45)
ylabel("Frequency")
Ideally, all classes would have an equal number of observations. However, with wireless signals it is
common for the classes in the training set to be imbalanced. 5G NR and WLAN signals may have
larger bandwidth than LTE signals, and noise fills the background. Because the learning is biased in
favor of the dominant classes, imbalance in the number of observations per class can be detrimental
to the learning process. In the Balance Classes Using Class Weighting on page 7-47 section, class
weighting is used to mitigate bias caused by imbalance in the number of observations per class.
The deep neural network uses 80% of the signal images from the dataset for training, 10% of the
images for validation, and 10% of the images for testing. The helperSpecSensePartitionData
function randomly splits the image and pixel label data into training,validation, and test sets.
[imdsTrain,pxdsTrain,imdsVal,pxdsVal,imdsTest,pxdsTest] = ...
helperSpecSensePartitionData(imds,pxdsTruthLTENRWLAN,[80 10 10]);
cdsTrain = combine(imdsTrain,pxdsTrain);
cdsVal = combine(imdsVal,pxdsVal);
cdsTest = combine(imdsTest,pxdsTest);
You have the choice of training a network from scratch or applying transfer learning.
7-46
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals
To apply transfer learning, use the deeplabv3plus (Computer Vision Toolbox) function to create a
semantic segmentation neural network. Choose resnet18 as the base network (by setting the value
of baseNetwork) and specify the input image size (number of pixels used to represent time and
frequency axes) and the number of classes.
if ~strcmp(baseNetwork,"custom")
layers = deeplabv3plus([256 256],numel(classNames),baseNetwork);
end
Instead of transfer learning, you can design a simple semantic segmentation network.
if strcmp(baseNetwork,"custom")
layers = helperSpecSenseCustomNetwork(imageSize,numClasses);
end
To improve training when classes in the training set are not balanced, you can use class weighting to
balance the classes. Use the pixel label counts computed earlier with the countEachLabel function
and calculate the median frequency class weights.
Configure training using the trainingOptions (Deep Learning Toolbox) function to specify the
stochastic gradient descent with momentum (SGDM) optimization algorithm and the hyper-
parameters used for SGDM. To get the best performance from the network, you can use the
Experiment Manager (Deep Learning Toolbox) to optimize training options.
mbs = 40;
opts = trainingOptions("sgdm",...
MiniBatchSize = mbs,...
MaxEpochs = 20, ...
LearnRateSchedule = "piecewise",...
InitialLearnRate = 0.02,...
LearnRateDropPeriod = 10,...
LearnRateDropFactor = 0.1,...
ValidationData = cdsVal,...
ValidationPatience = 5,...
7-47
7 Examples
Shuffle="every-epoch",...
OutputNetwork = "best-validation-loss",...
Plots = 'training-progress');
Train the network using the combined training data store, cdsTrain. The combined training data
store contains single signal frames and true pixel labels. Use weighted cross-entropy loss together
with a custom normalization to update the network during training. Define a custom loss function,
lossFunction on page 7-63, using the crossentropy (Deep Learning Toolbox) loss function and
apply custom normalization.
if trainNow
[net,trainInfo] = trainnet(cdsTrain,layers, ...
@(ypred,ytrue) lossFunction(ypred,ytrue,classWeights),opts); %#ok
save(sprintf('myNet_%s_%s',baseNetwork, ...
datetime('now',format='yyyy_MM_dd_HH_mm')), 'net')
else
net = loadNetworkFromMATFile(baseNetwork);
end
Test the network signal identification performance using signals that contain both 5G NR, LTE, and
WLAN signals. Use the semanticseg (Computer Vision Toolbox) function to get the pixel estimates
of the spectrogram images in the test data set. Use the evaluateSemanticSegmentation
(Computer Vision Toolbox) function to compute various metrics to evaluate the quality of the
semantic segmentation results.
dataDir = fullfile(trainDir,"LTE_NR_WLAN");
imdsLTENRWLAN = imageDatastore(dataDir,FileExtensions=".png");
pxdsResultsLTENRWLAN = semanticseg(imdsLTENRWLAN,net,MinibatchSize=mbs,WriteLocation=tempdir, ...
Classes=classNames);
pxdsTruthLTENRWLAN = pixelLabelDatastore(dataDir,classNames,pixelLabelID,...
FileExtensions=".hdf");
metrics = evaluateSemanticSegmentation(pxdsResultsLTENRWLAN,pxdsTruthLTENRWLAN);
cm = confusionchart(metrics.ConfusionMatrix.Variables, ...
classNames, Normalization='row-normalized');
cm.Title = 'Confusion Matrix - Synthetic';
7-48
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals
If you chose to use captured data in the Generate Training Data on page 7-44 section, test with just
captured data.
if useCapturedData
capturedIdx = contains(imdsTest.Files,'captured');
imdsTestCaptured = subset(imdsTest,capturedIdx);
pxdsTestCaptured = subset(pxdsTest,capturedIdx);
Repeat the same process, considering only the frames with captured data in the test set.
pxdsResultsCaptured = semanticseg(imdsTestCaptured,net,MinibatchSize=mbs,WriteLocation=tempdir,
Classes=classNames);
metrics = evaluateSemanticSegmentation(pxdsResultsCaptured,pxdsTestCaptured);
cm = confusionchart(metrics.ConfusionMatrix.Variables, ...
classNames, Normalization="row-normalized");
cm.Title = "Normalized Confusion Matrix";
The confusion matrix shows that the network confuses NR signals with Noise or Unknown signals.
Examining the captured signals reveals that the captured signals with file prefix CF3550 has very low
SNR and the network is having a hard time to identify signals correctly.
CF3550Indices = contains(imdsTestCaptured.Files,'CF3550');
idx = find(CF3550Indices,1);
rcvdSpectrogram = readimage(imdsTestCaptured,idx);
trueLabels = readimage(pxdsTestCaptured,idx);
7-49
7 Examples
predictedLabels = readimage(pxdsResultsCaptured,idx);
figure
helperSpecSenseDisplayResults(rcvdSpectrogram,trueLabels,predictedLabels, ...
classNames,250e6,0,frameDuration)
imdsTestCaptured2 = subset(imdsTestCaptured,~CF3550Indices);
pxdsTestCaptured2 = subset(pxdsTestCaptured,~CF3550Indices);
pxdsResultsCaptured2 = semanticseg(imdsTestCaptured2,net,MinibatchSize=mbs,WriteLocation=tempdi
Classes=classNames);
metrics = evaluateSemanticSegmentation(pxdsResultsCaptured2,pxdsTestCaptured2);
figure
cm = confusionchart(metrics.ConfusionMatrix.Variables, ...
classNames, Normalization="row-normalized");
cm.Title = "Normalized Confusion Matrix";
end
7-50
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals
7-51
7 Examples
7-52
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals
Visualize the received spectrum, true labels, and predicted labels for a captured signal.
if useCapturedData
signals = find(~CF3550Indices);
numSignals = length(signals);
idx = ;
rcvdSpectrogram1 = readimage(imdsTestCaptured,signals(idx));
trueLabels1 = readimage(pxdsTestCaptured,signals(idx));
predictedLabels1 = readimage(pxdsResultsCaptured,signals(idx));
idx = ;
rcvdSpectrogram2 = readimage(imdsTestCaptured,signals(idx));
trueLabels2 = readimage(pxdsTestCaptured,signals(idx));
predictedLabels2 = readimage(pxdsResultsCaptured,signals(idx));
else
numSignals = length(imdsLTENRWLAN.Files);
idx = ;
rcvdSpectrogram1 = readimage(imdsLTENRWLAN,idx);
trueLabels1 = readimage(pxdsTruthLTENRWLAN,idx);
predictedLabels1 = readimage(pxdsResultsLTENRWLAN,idx);
idx = length(imdsLTENRWLAN.Files);
rcvdSpectrogram2 = readimage(imdsLTENRWLAN,idx);
7-53
7 Examples
trueLabels2 = readimage(pxdsTruthLTENRWLAN,idx);
predictedLabels2 = readimage(pxdsResultsLTENRWLAN,idx);
end
figure
helperSpecSenseDisplayResults(rcvdSpectrogram1,trueLabels1,predictedLabels1, ...
classNames,250e6,0,frameDuration)
figure
helperSpecSenseDisplayIdentifiedSignals(rcvdSpectrogram1,predictedLabels1, ...
classNames,250e6,0,frameDuration)
7-54
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals
figure
helperSpecSenseDisplayResults(rcvdSpectrogram2,trueLabels2,predictedLabels2, ...
classNames,250e6,0,frameDuration)
7-55
7 Examples
figure
helperSpecSenseDisplayIdentifiedSignals(rcvdSpectrogram2,predictedLabels2, ...
classNames,250e6,0,frameDuration)
7-56
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals
Test the performance of the trained network using over-the-air signal captures using SDR. Find a
nearby base station and tune the center frequency of your radio to cover the band of the signals you
want to identify. This example sets the center frequency to 2.35 GHz. If you have at least one ADALM-
PLUTO radio and have installed Communication Toolbox Support Package for ADALM-PLUTO Radio,
you can run this section of the code. In case you do not have access to an ADALM-PLUTO radio, this
example shows results of a test conducted using captured signals and a trained network.
Use Wireless Testbench example “Identify LTE and NR Signals from Captured Data Using SDR and
Deep Learning” (Wireless Testbench) to test with wideband signals.
runSDRSection = false;
if helperIsPlutoSDRInstalled()
radios = findPlutoRadio();
if length(radios) >= 1
runSDRSection = true;
else
disp("At least one ADALM-PLUTO radios is needed. Skipping SDR test.")
end
else
disp("Communications Toolbox Support Package for Analog Devices ADALM-PLUTO Radio not found."
disp("Click Add-Ons in the Home tab of the MATLAB toolstrip to install the support package.")
disp("Skipping SDR test.")
end
Communications Toolbox Support Package for Analog Devices ADALM-PLUTO Radio not found.
7-57
7 Examples
Click Add-Ons in the Home tab of the MATLAB toolstrip to install the support package.
if runSDRSection
% Set up PlutoSDR receiver
rx = sdrrx('Pluto');
rx.CenterFrequency = 2.43e9;
rx.BasebandSampleRate = sampleRate;
rx.SamplesPerFrame = frameDuration*rx.BasebandSampleRate;
rx.OutputDataType = 'single';
rx.EnableBurstMode = true;
rx.NumFramesInBurst = 1;
Nfft = 4096;
overlap = 10;
[segResults(:,:,frameCnt),scores,allScores] = semanticseg(rxSpectrogram,net);
meanAllScores = (meanAllScores*(frameCnt-1) + allScores) / frameCnt;
end
release(rx)
[~,predictedLabels] = max(meanAllScores,[],3);
figure
helperSpecSenseDisplayResults(rxSpectrogram,[],predictedLabels,classNames,...
sampleRate,rx.CenterFrequency,frameDuration)
figure
freqBand = helperSpecSenseDisplayIdentifiedSignals(rxSpectrogram,predictedLabels,...
classNames,sampleRate,rx.CenterFrequency,frameDuration)
else
figure
imshow('lte_capture_result1.png',InitialMagnification='fit')
figure
imshow('lte_capture_result2.png',InitialMagnification='fit')
figure
imshow('nr_capture_result1.png',InitialMagnification='fit')
figure
imshow('nr_capture_result2.png',InitialMagnification='fit')
end
7-58
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals
7-59
7 Examples
7-60
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals
7-61
7 Examples
The trained network can distinguish 5G NR, LTE, and WLAN signals including two example captures
from real base stations. The network may not be able to identify every captured signal correctly. In
such cases, enhance the training data either by generating more representative synthetic signals or
capturing over-the-air signals and including these in the training set. The results obtained after
training can differ from the results mentioned here for different networks due to random initial
conditions.
Different network structures result in different accuracy for detection. The table shows detection
accuracy results for custom, ResNet-18, MobileNetv2, and ResNet-50, which have 1.4M, 20.6M,
43.9M and 46.9M learnables, respectively. Detection accuracy results are for overall test set, only
synthetic signals, and only for captured signals. The overall and captured only tests include signals
from the test set. The synthetic tests include generated signals in the LTE_NR_WLAN directory, which
are not used in training. Increasing the network complexity results in increased accuracy.
7-62
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals
You can use the “Identify LTE and NR Signals from Captured Data Using SDR and Deep Learning”
(Wireless Testbench) example to identify LTE and 5G NR signals using the trained networks.
If you need to monitor wider bands of spectrum, increase the sampleRate, regenerate the training
data, capture signals using the “Capture and Label NR and LTE Signals for AI Training” (Wireless
Testbench) example, and retrain the network.
Supporting Functions
7-63
7 Examples
This example shows you how to undertake spectral analysis of signals. You can either use recorded
data from a file, or receive signals in real time using the RTL-SDR radio, ADALM-PLUTO radio, or
USRP™ radio. You can change the radio's center frequency to tune the radio to a band where a signal
is present. You can then use the spectrum analyzer to view and make measurements on the received
spectrum.
For Simulink® implementation of this example, see “Spectrum Analysis of Signals in Simulink”.
By default, this example runs using recorded data from a file. Optionally, you can receive signals over-
the-air. For this, you also need one of the following:
• RTL-SDR radio and Communications Toolbox Support Package for RTL-SDR Radio
• ADALM-PLUTO radio and Communications Toolbox Support Package for ADALM-PLUTO Radio
• USRP N2xx or B2xx series radio and Communications Toolbox Support Package for USRP Radio.
For information on supported radios, see “Supported Hardware and Required Software”.
• USRP E3xx, N3xx, X3xx, or X4xx series radio and Wireless Testbench Support Package for NI
USRP Radios. For information on supported radios, see “Supported Radio Devices” (Wireless
Testbench).
Example Code
The receiver asks for user input and initializes variables. Then, it calls the signal source and FM
broadcast receiver in a loop. The loop also keeps track of the radio time using the frame duration and
lost samples reported by the signal source.
cmdlineInput = ;
if cmdlineInput
% Request user input from the command-line for application parameters
userInput = helperSpectralAnalysisUserInput;
% Set initial parameters
[SAParams, sigSrc] = helperSpectralAnalysisConfig(userInput);
else
% Set initial parameters
load defaultInputSpecAnalysis.mat
[SAParams, sigSrc] = helperSpectralAnalysisConfig;
end
Setup
hSpectrum = spectrumAnalyzer(...
'Name', 'Passband Spectrum',...
'Title', 'Passband Spectrum', ...
'Method', 'Welch', ...
'SpectrumType', 'Power density', ...
'FrequencySpan', 'Full', ...
7-64
Spectrum Analysis of Signals
Stream processing
View the spectrum. While the spectrum analyzer is running, you can measure peaks, occupied
bandwidth, and other properties of the signal.
% Main loop
while radioTime < userInput.Duration
% Receive baseband samples (Signal Source)
if SAParams.isSourceRadio
if SAParams.isSourcePlutoSDR
rcv = sigSrc();
lost = 0;
late = 1;
elseif SAParams.isSourceUsrpRadio
rcv= sigSrc();
lost = 0;
else
[rcv,~,lost,late] = sigSrc();
end
else
rcv = sigSrc();
lost = 0;
late = 1;
end
% Update radio time. If there were lost samples, add those too.
radioTime = radioTime + SAParams.FrontEndFrameTime + ...
double(lost)/SAParams.FrontEndSampleRate;
end
7-65
7 Examples
Conclusion
In this example, you used System objects to analyze the spectrum of a received signal.
7-66
Ship Tracking Using AIS Signals
This example shows how to track ships by processing automatic identification system (AIS) signals.
You can use previously captured signals or receive signals in real time using an RTL-SDR radio, an
ADALM-PLUTO radio or a USRP™ Radio. You can also show the tracked ships on a map using the
Mapping Toolbox™.
By default, this example runs using previously captured signals. Optionally, you can receive signals
over-the-air. For this, you also need one of the following:
• RTL-SDR radio and Communications Toolbox Support Package for RTL-SDR Radio.
• ADALM-PLUTO radio and Communications Toolbox Support Package for ADALM-PLUTO Radio.
• USRP N2xx or B2xx series radio and Communications Toolbox Support Package for USRP Radio.
For information on supported radios, see “Supported Hardware and Required Software”.
• USRP E3xx, N3xx, or X3xx series radio and Wireless Testbench Support Package for NI USRP
Radios. For information on supported radios, see “Supported Radio Devices” (Wireless Testbench).
Overview
In marine transportation, vessel traffic services use AIS as a component of the marine traffic
monitoring system. AIS performs these functions:
7-67
7 Examples
Receiver Structure
This block diagram shows the receiver code structure. The processing has three main parts: signal
source, physical layer and data viewer.
Signal Source
• ''File'' — Uses the comm.BasebandFileReader object to read a file that contains a captured
signal.
• ''RTL-SDR'' — Uses an RTL-SDR radio to receive a live signal.
• ''ADALM-PLUTO'' — Uses a Pluto radio to receive a live signal.
• ''USRP'' — Uses a USRP radio to receive a live signal.
The example uses a signal symbol rate of 9600 Hz and 24 samples per symbol.
If you specify ''RTL-SDR'' as the signal source, the example searches your computer for an RTL-SDR
radio at the radio address '0' and uses that radio as the signal source.
If you specify ''ADALM-PLUTO'' as the signal source, the example searches your computer for a Pluto
radio at the radio address 'usb:0' and uses that radio as the signal source.
7-68
Ship Tracking Using AIS Signals
If you specify ''USRP'' as the signal source, the example searches your computer for a USRP radio at
the radio address you specify and uses that radio as the signal source.
Physical Layer
The physical layer (PHY) processes the baseband samples from the signal source to produce packets
that contain the ship position information and raw message bytes. This figure shows the PHY
processing components.
• Packet Search — Search for the strongest burst in the received signal by dividing into multiple
windows.
• DC Offset Removal — Remove DC offset from the detected signal.
• Frequency Compensation — Estimate and compensate for the carrier frequency offset.
• Matched Filtering — Perform filtering with a Gaussian pulse generated according to AIS
specifications.
• Synchronization and Demodulation — Perform timing synchronization by correlating the received
signal with the known preamble and demodulate to produce bits.
• AIS Bit Parser — Detect the Start Flag and End Flags, then perform CRC detection. If the CRC is
successful, then decodes the ship information.
AIS signal contains 64 specific message types. Ship position information is included in 11 of the
message types. In this example, you decode all of the 11 message types that contain ship position
information.
This example lists the ship position information including the ship ID, latitude, and longitude, as well
as the associated date and time in a table. For decoding additional information from the messages,
see [1 on page 7-72].
Data Viewer
The data viewer shows the received messages on a graphical user interface (GUI). As data is
captured, the application lists information that it decodes from these messages in a table.
7-69
7 Examples
The default configuration runs for a duration of 10 seconds and uses signal data from a captured data
file, and outputs to a text file. To provide input values from the command line, you must change
cmdlineInput to 1, then you will be prompted to enter the following information when you run the
example:
1 Reception duration in seconds,
2 Signal source (Captured data file or RTL-SDR radio or ADALM-PLUTO radio or USRP radio),
3 Optional output methods (map, text file, or both).
cmdlineInput = 0;
if cmdlineInput
% Request user input from the command-line for application parameters
userInput = helperAISUserInput;
else
load('defaultInputs.mat');
end
% Calculate AIS parameters based on the user input
[aisParam,sigSrc] = helperAISConfig(userInput);
% Create the data viewer object and configure based on user input
viewer = helperAISViewer('LogFileName',userInput.LogFilename, ...
'SignalSourceType',userInput.SignalSourceType);
7-70
Ship Tracking Using AIS Signals
release(sigSrc)
If you have the Mapping Toolbox, you can also observe AIS tracking of ships on a map.
7-71
7 Examples
Further Exploration
You can investigate AIS signals using the AISExampleApp. To launch the app, enter AISExampleApp
in the MATLAB® Command Window. Use the app interface to select the signal source and change the
duration.
You can explore the supporting functions and System objects for details of the physical layer
implementation.
• helperAISRxPhy.m
• helperAISRxPhyPacketSearch.m
• helperAISRxPhyFreqComp.m
• helperAISRxPhySyncDemod.m
• helperAISRxPhyBitParser.m
References
7-72
Ship Tracking Using AIS Signals
7-73
7 Examples
This example shows how to design an orthogonal frequency division multiplexing (OFDM) transmitter
for a single-input single-output (SISO) channel using a software-defined radio (SDR).
This example details the physical-layer transmission protocol of the OFDM system that mimics typical
synchronization signals, reference symbols, control channels, and data channels. The OFDM
transmission system processing includes cyclic redundancy check(CRC), encoding, scrambling,
convolutional encoding, modulation, filtering, channel distortion.
The “OFDM Receiver Using Software Defined Radio” example receives and demodulates the OFDM
signal transmitted by this example.
To run this example you will need one of the following hardware and the corresponding support
package
• USRP™ N2xx or B2xx series radio and Communications Toolbox Support Package for USRP Radio.
For information on supported radios, see “Supported Hardware and Required Software”.
• USRP E3xx, N3xx, X3xx, or X4xx series radio and Wireless Testbench Support Package for NI
USRP Radios. For information on supported radios, see “Supported Radio Devices” (Wireless
Testbench).
• ADALM-PLUTO radio and the Communications Toolbox Support Package for Analog Devices®
ADALM-PLUTO Radio software
Set the OFDM parameters, including the FFT length, cyclic prefix length, and number of subcarriers.
The pilot subcarrier spacing and channel bandwidth parameters are fixed at 30 KHz and 3 MHz,
respectively.
After configuring the OFDM parameters, you must set the data parameters. Set the modulation order,
code rate, number of symbols per frame, and the number of frames per transmission. The possible
modulation schemes are BPSK, QPSK and 16-QAM and the possible code rates are 1/2 and 2/3. The
OFDM parameters and the data parameters must be common to both transmitter and receiver.
You can enable or disable the scopes for visualization, however for long simulations, it is
recommended to disable the scope. To control the diagnostic output, enable or disable the verbosity
as needed.
% The chosen set of OFDM parameters:
OFDMParams.FFTLength = 128; % FFT length
OFDMParams.CPLength = 32; % Cyclic prefix length
OFDMParams.NumSubcarriers = 90; % Number of sub-carriers in the band
OFDMParams.Subcarrierspacing = 30e3; % Sub-carrier spacing of 30 KHz
OFDMParams.PilotSubcarrierSpacing = 9; % Pilot sub-carrier spacing
OFDMParams.channelBW = 3e6; % Bandwidth of the channel 3 MHz
% Data Parameters
7-74
OFDM Transmitter Using Software-Defined Radio
Assign the name of the radio you are using for transmitting the OFDM signal to the variable
radioDevice. Set the receiver gain and operating center frequency.
[sysParam,txParam,trBlk] = helperOFDMSetParamsSDR(OFDMParams,dataParams);
sampleRate = sysParam.scs*sysParam.FFTLen; % Sample rate of signal
ofdmTx = helperGetRadioParams(sysParam,radioDevice,sampleRate,centerFrequency,g
% Get the radio transmitter and spectrum analyzer system object system object for the user to vis
[radio,spectrumAnalyze] = helperGetRadioTxObj(ofdmTx);
A transport block contains user data and control information. The OFDM transmitter transmits one
transport block per frame. The transport block size varies based on several factors: the number of
active subcarriers, the number of pilot subcarriers, modulation order, coding rate, CRC length,
encoder constraint length, and the number of data symbols per frame.
The transmission grid populates signals and channels on a per-frame basis. The figure below shows
one transmission frame of 28 OFDM symbols with FFT length of 128.
A synchronization (sync) signal is transmitted as the first symbol in the frame. The sync signal
consists of a 62-subcarriers signal centered at DC generated using a ZadOff-Chu. This signal is
designed to be bandwidth agnostic, meaning that all transmitters can transmit this signal regardless
of the allocated bandwidth for that cell. The signal is meant to be detected by receivers to positively
detect the cell signal and identify the frame boundary (the start of the frame).
7-75
7 Examples
The next symbol in the transmit frame is the reference symbol. Known at both the transmitter and
receiver, the reference symbol allows the receiver to compare the received reference symbol with the
known reference symbol to estimate the channel. The receiver then compensates for the channel
distortion between the transmitter and receiver.
Header Symbol
The header symbol conveys the bandwidth, subcarrier modulation scheme, and code rate of the
OFDM data symbols to help the receiver decode the transmitted frame. The information is important
enough that it is transmitted with large signaling and coding margins to maximize correct decoding.
Therefore, the symbol is coded at 1/2 rate with wide interleaving and modulated using BPSK. Since
the channel distortion may change over time, the header symbol is transmitted immediately after the
reference symbol to maximize the probability of correct reception. Because the bandwidth is not yet
known, the header is always transmitted with a 72-subcarrier signal centered at DC.
Pilot Signals
Finally, to combat phase jitter seen at higher transmission frequencies, a pilot is transmitted at fixed
subcarrier intervals within the data symbols to provide a phase reference to the receiver.
Null subcarriers at the edge of the transmission spectrum are used to constrain spectral energy to a
specified bandwidth. The subcarrier at DC is also nulled to keep the signal energy to within the linear
range of the power amplifier.
7-76
OFDM Transmitter Using Software-Defined Radio
Transmitter processing
The data symbols comprise a single user populating a single transport block of data transmitted once
per frame. A comm.CRCGenerator object computes the CRC for the transport block payload and
appends it to the payload. The data is additively scrambled using a comm.PNSequence object to
distribute the data power evenly across the transmission spectrum. Interleaving is done with the
reshape function to resist burst errors caused by deep fades. Convolutional encoding adds
redundant bits for forward error correction and is done with the convenc function. Puncturing of the
data increases data throughput by reducing the number of redundant bits. The transport block is
modulated using the qammod function and is ready for transmission in an OFDM frame. All signals are
OFDM-modulated using the ofdmmod function. The signal is filtered to reduce out-of-band emissions
using dsp.FIRFilter, with coefficients generated using the firpmord and firpm filter design
functions.
% Initialize transmitter
txObj = helperOFDMTxInit(sysParam);
7-77
7 Examples
% Repeat the data in a buffer for PLUTO radio to make sure there are less
% underruns. The receiver decodes only one frame from where the first
% synchroization signal is received
txOutSize = length(txOut);
if contains(radioDevice,'PLUTO') && txOutSize < 48000
frameCnt = ceil(48000/txOutSize);
txWaveform = zeros(txOutSize*frameCnt,1);
for i = 1:frameCnt
txWaveform(txOutSize*(i-1)+1:i*txOutSize) = txOut;
end
else
txWaveform = txOut;
end
if dataParams.enableScopes
7-78
OFDM Transmitter Using Software-Defined Radio
spectrumAnalyze(txOut);
end
Further Exploration
7-79
7 Examples
This example shows how to design an orthogonal frequency division multiplexing (OFDM) receiver for
a single-input single-output (SISO) channel using a software-defined radio (SDR). The OFDM receiver
captures and demodulates the OFDM signal that the “OFDM Transmitter Using Software-Defined
Radio” example sends. The OFDM receiver design includes sample buffering for timing adjustment,
filtering, carrier frequency adjustment, and OFDM demodulation.
To run this example, you need one of these SDRs and the corresponding software support package.
• USRP™ N2xx or B2xx series radio and Communications Toolbox Support Package for USRP Radio.
For information on supported radios, see “Supported Hardware and Required Software”.
• USRP E3xx, N3xx, X3xx, or X4xx series radio and Wireless Testbench Support Package for NI
USRP Radios. For information on supported radios, see “Supported Radio Devices” (Wireless
Testbench).
• ADALM-PLUTO radio and the Communications Toolbox Support Package for Analog Devices®
ADALM-PLUTO Radio.
The example requires two MATLAB™ sessions, one for the transmitter and one for the receiver. You
run the OFDM Transmitter Using Software-Defined Radio example in one MATLAB session to
transmit the OFDM signal.
Set the OFDM parameters, including the FFT length, cyclic prefix length, and number of subcarriers.
The pilot subcarrier spacing and channel bandwidth are fixed at 30 KHz and 3 MHz, respectively.
After configuring the OFDM parameters, set the data parameters. Set the modulation order, code
rate, number of symbols per frame, and the number of frames per transmission.
You can enable or disable the scopes for visualization, however for long simulations, it is
recommended to disable the scope. To control the display of the diagnostic output text, enable or
disable the verbosity as needed. To view the decoded data in each frame, enable the print data flag
% Data Parameters
7-80
OFDM Receiver Using Software Defined Radio
The helperGetRadioParams function initializes the receiver System object™ ofdmRx. Assign the
name of the radio you are using for receiving the OFDM signal to the variable radioDevice. Set the
receiver gain and operating center frequency.
[sysParam,txParam,transportBlk] = helperOFDMSetParamsSDR(OFDMParams,dataParams);
sampleRate = sysParam.scs*sysParam.FFTLen; % Sample rate of
ofdmRx = helperGetRadioParams(sysParam,radioDevice,sampleRate,centerFrequency,gain);
[radio,spectrumAnalyze,constDiag] = helperGetRadioRxObj(ofdmRx);
Synchronization
The OFDM receiver checks the sample buffer for the synchronization symbol to find the starting point
of the data frames within the received OFDM signal. The receiver correlated the received OFDM
signal with the known synchronization symbol. Once the OFDM receiver detects a high correlation
peak, it identifies the position where it finds the synchronization symbol as the start of the frame.
The OFDM receiver estimates and corrects the frequency and timing offset introduced to the
transmitted OFDM signal due to channel impairments. The OFDM receiver checks the receiver buffer
for the required number of frames and performs automatic frequency correction over each symbol.
The receiver averages the frequency correction across the subcarriers and then across every six
symbols, considering a group of six symbols as a slot. The receiver considers the overall average
value of these corrections as the frequency offset and compensates this frequency offset across the
entire frame.
7-81
7 Examples
The receiver is considered camped to a based station upon achieving successful synchronization and
channel impairment correction.
Receiver Processing
This process is the reverse of the process that happens at the transmitter.
Initially, the OFDM receiver performs channel estimation on the OFDM demodulated reference
symbols. To remove the effects of time-varying fading, the receiver selects two reference symbols
from adjacent frames to estimate the channel at two different points in time. The receiver then
linearly interpolates the channel estimates between the two reference symbols to get the channel
estimates for the header and data symbols. The ofdmEqualize function then equalizes the reference
symbols and data symbols using the channel estimates.
Header Decoding
The receiver extracts and decodes the header symbols to get the data symbol parameters such as FFT
length, subcarrier modulation scheme, and code rate. The receiver uses these parameters to
demodulate and decode the data symbols.
Data Decoding
The common phase error (CPE) affects all subcarriers equally and the OFDM receiver uses the pilot
symbols within the data symbols to estimate CPE. The helperOFDMRx function corrects the phase
errors in the data symbols and the qamdemod function soft decodes the data subcarriers into log
likelihood ratios (LLRs).
The receiver then deinterleaves the demodulated bitstream and the vitdec function performs
maximum likelihood decoding using the Viterbi algorithm. The descrambler descrambles the decoded
bits, and the comm.CRCDetector computes the cyclic redundancy check (CRC) and compares it with
the appended CRC.
7-82
OFDM Receiver Using Software Defined Radio
% Clear all the function data as they contain some persistent variables
clear helperOFDMRx helperOFDMRxFrontEnd helperOFDMRxSearch helperOFDMFrequencyOffset;
close all;
errorRate = comm.ErrorRate();
toverflow = 0; % Receiver overflow count
rxObj = helperOFDMRxInit(sysParam);
BER = zeros(1,dataParams.numFrames);
for frameNum = 1:dataParams.numFrames
sysParam.frameNum = frameNum;
[rxWaveform, ~, overflow] = radio();
7-83
7 Examples
rxDataBits);
BER(frameNum) = berVals(1);
if dataParams.printData
% As each character in the data is encoded by 7 bits, decode the received data up
numBitsToDecode = length(rxDataBits) - mod(length(rxDataBits),7);
recData = char(bit2int(reshape(rxDataBits(1:numBitsToDecode),7,[]),7));
fprintf('Received data in frame %d: %s',frameNum,recData);
end
end
if dataParams.enableScopes
spectrumAnalyze(rxWaveform);
end
end
end
7-84
OFDM Receiver Using Software Defined Radio
7-85
7 Examples
Simulation complete!
Average BER = 0
release(radio);
Troubleshooting
Problem
Possible causes
Possible solutions
7-86
OFDM Receiver Using Software Defined Radio
Problem
• Even when synchronization and receiver camping are successful, the header CRC check fails.
Possible causes
Possible solutions
• The frequency compensation algorithm measures and corrects the frequency and phase offset for
each frame, and it can estimate the correct offset up to half of the subcarrier spacing. You can
calibrate the frequency offset to resolve this error.
For USRP radios, you can determine the frequency offset by sending a tone at a known frequency
from the transmitter and measure the offset between the transmitted and received frequency. Apply
the measured offset to the center frequency of comm.SDRuReceiver receiver System object.
For ADALM-Pluto radios, run the “Frequency Offset Calibration with ADALM-PLUTO Radio in
Simulink” on page 7-126 example to get the frequency offset. Apply the measured offset to the center
frequency of the comm.SDRRxPluto receiver System object.
Problem
• The data decoding fails even when the header CRC decoding is successful.
Possible causes
Possible solutions
Further Exploration
You can use an external clock source or GPSDO with the radios to try smaller subcarrier spacing of
15 KHz with smaller bandwidths such as 1.4 MHz (LTE bandwidths) or higher FFTLengths such as
256.
This example uses burst mode in the radios to receive the data, with the burst size set to the number
of frames. You can further explore receiving the data using the radios in non-burst mode.
7-87
7 Examples
This example shows how to track planes by processing automatic dependent surveillance-broadcast
(ADS-B) signals. You can use previously captured signals, or receive signals in real time using an RTL-
SDR radio, an ADALM-PLUTO radio or a USRP™ radio. You can also visualize the tracked planes on a
map with Mapping Toolbox™.
By default, this example runs using previously captured data. Optionally, you can receive signals over-
the-air. For this, you also need one of the following:
• RTL-SDR radio and Communications Toolbox Support Package for RTL-SDR Radio.
• Pluto radio and Communications Toolbox Support Package for Analog Devices® ADALM-PLUTO
Radio.
• USRP N2xx or B2xx series radio and Communications Toolbox Support Package for USRP Radio.
For information on supported radios, see “Supported Hardware and Required Software”.
• USRP E3xx, N3xx, or X3xx series radio and Wireless Testbench Support Package for NI USRP
Radios. For information on supported radios, see “Supported Radio Devices” (Wireless Testbench).
Introduction
For an introduction on the Mode-S signaling scheme and ADS-B technology for tracking aircraft, refer
to the “Airplane Tracking Using ADS-B Signals” MATLAB® example.
Receiver Structure
This diagram summarizes the receiver code structure. The processing has four main parts: signal
source, physical layer, message parser, and data viewer.
7-88
Airplane Tracking Using ADS-B Signals in Simulink
Signal Source
• ''Captured Signal'' - Over-the-air signals written to a file and sourced using a baseband file
reader block at 2.4 Msps
• ''RTL-SDR Radio'' - RTL-SDR radio at 2.4 Msps
• ''ADALM-PLUTO'' - ADALM-PLUTO radio at a sample rate of 12 Msps
• ''USRP Radio'' - USRP radio at a sample rate of 20 Msps for all radios except N310/N300
radio, that uses 2.4 Msps sample rate
The extended squitter message is 120 micro seconds long, so the signal source is configured to
process enough samples to contain 180 extended squitter messages simultaneously, and set
SamplesPerFrame of the signal property accordingly. The rest of the algorithm searches for Mode-S
packets in this frame of data and outputs all correctly identified packets. This type of processing is
referred to as batch processing. An alternative approach is to process one extended squitter message
at a time. This single packet processing approach incurs 180 times more overhead than the batch
processing, while it has 180 times less delay. Since the ADS-B receiver is delay tolerant, you use
batch processing in this example.
Physical Layer
7-89
7 Examples
The physical layer (PHY) processes baseband samples from the signal source to produce packets that
contain the PHY layer header information and the raw message bits. This diagram shows the physical
layer structure.
The RTL-SDR radio can use a sampling rate in the range [200e3, 2.8e6] Hz. When the source is an
RTL-SDR radio, the example uses a sampling rate of 2.4 MHz and interpolates by a factor of 5 to a
practical sampling rate of 12 MHz.
The ADALM-PLUTO radio can use a sampling rate in the range [520e3, 61.44e6] Hz. When the source
is an ADALM-PLUTO radio, the example samples the input directly at 12 MHz.
The USRP radios are capable of using different sampling rates. When the source is a USRP radio, the
example samples the input directly at 20 MHz. For the N310/N300 radio the data is received at 2.4
MHz sample rate and interpolates by a factor of 5 to a practical sampling rate of 12e6.
For example, if the data rate is 1 Mbit/s and the effective sampling rate is 12 MHz, the signal contains
12 samples per symbol. The receive processing chain uses the magnitude of the complex symbols.
The packet synchronizer works on subframes of data that is equivalent to two extended squitter
packets, i.e. 1440 samples at 12 MHz or 120 micro seconds. This subframe length ensures that the
subframe contains the whole extended squitter. Packet synchronizer first correlates the received
signal with the 8 microsecond preamble and finds the peak value. The synchronizer then validates the
found synchronization point by checking if it confirms to the preamble sequence, [1 0 0 0 0 0 1 0 1 0
0 0 0 0 0], where a value of 1 represents a high value and a value of 0 represents a low value.
The Mode-S PPM scheme defines two symbols. Each symbol has two chips, where one has a high
value and the other has a low value. If the first chip is high and the subsequent chip is low, then the
symbol is 1. Alternatively, if the first chip is low and subsequent chip is high, then the symbol is 0.
The bit parser demodulates the received chips and creates a binary message. The CRC checker
validates the binary message. The output of bit parser is a vector of Mode-S physical layer header
packets that contains these fields:
Message Parser
7-90
Airplane Tracking Using ADS-B Signals in Simulink
The message parser extracts the raw bits based on the packet type as described in [ 2 ]. This example
can parse short squitter packets and extended squitter packets that contain airborne velocity,
identification, and airborne position data.
Data Viewer
The data viewer shows the received messages on a graphical user interface (GUI). For each packet
type, the data viewer shows the number of detected packets, the number of correctly decoded
packets and the packet error rate (PER). As the radio captures data, the application lists information
decoded from these messages in a table.
You can also launch the map and start text file logging using the two slider switches(Launch Map and
Log Data).
• Log Data* - When Log Data is On, it Saves the captured data in a TXT file. You can use the saved
data for later for post processing.
• Launch Map - When Launch Map is On, map will be launched where the tracked flights can be
viewed. NOTE: You must have a valid license for the Mapping Toolbox if you want to use this
feature.
These figures illustrate how the application tracks and lists flight details and displays them on a map.
7-91
7 Examples
7-92
Airplane Tracking Using ADS-B Signals in Simulink
References
1 International Civil Aviation Organization, Annex 10, Volume 4. Surveillance and Collision
Avoidance Systems.
2 Technical Provisions For Mode S Services and Extended Squitter (Doc 9871)
7-93
7 Examples
This example shows you how to use Simulink® and Communications Toolbox™ to read utility meters
by processing Standard Consumption Message (SCM) or Interval Data Message (IDM) signals
emitted by meters. You can either use recorded data from a file, or receive over-the-air signals in real
time using the RTL-SDR Radio or ADALM-PLUTO Radio.
To run this example using recorded data from a file, you need Simulink® and Communications
Toolbox™ software.
To receive signals in real time, you also need one of the following SDR devices and the corresponding
software add-on:
• RTL-SDR radio and Communications Toolbox Support Package for RTL-SDR Radio add-on
• ADALM-PLUTO radio and Communications Toolbox Support Package for Analog Devices®
ADALM-PLUTO Radio add-on
For a full list of Communications Toolbox supported SDR platforms, refer to Supported Hardware
section of the Software Defined Radio (SDR) discovery page.
Introduction
For an introduction to the SCM/IDM signaling scheme and AMR technology for reading utility meters,
refer to the “Automatic Meter Reading” example in MATLAB®.
The following block diagram summarizes the receiver structure. The processing has four main parts:
Signal Source, Physical Layer, Message Parser, and Data Viewer.
Signal Source
7-94
Automatic Meter Reading in Simulink
1 ''File'': Over-the-air signals written to a file and read using a Baseband File Reader block at 1.0
Msps
2 ''RTL-SDR Radio'': RTL-SDR radio at a sample rate of 1.0 Msps
3 ''ADALM-PLUTO Radio'': ADALM-PLUTO radio at a sample rate of 1.0 Msps
If you assign ''RTL-SDR'' or ''ADALM-PLUTO'' as the signal source, the example searches your
computer for the radio you specified, either an RTL-SDR radio at radio address '0' or an ADALM-
PLUTO radio at radio address 'usb:0' and uses the radio as the signal source.
Physical Layer
The baseband samples received from the signal source are processed by the physical layer (PHY) to
produce packets that contain the SCM or IDM information. This diagram shows the physical layer
receive processing.
The RTL-SDR radio is capable of using a sampling rate in the range of 225-300 kHz or 900-2560 kHz
and ADALM-PLUTO radio is capable of using a sampling rate in the range of 520 kHz-61.44 MHz. A
sampling rate of 1.0 Msps is used to produce a sufficient number of samples per Manchester encoded
data bit. For each frequency in the hopping pattern, every AMR data packet is transmitted. The
frequency hopping allows for increased reliability over time. Since every packet is transmitted on
each frequency hop, it is sufficient to monitor only one frequency for this example. The radio is tuned
to a center frequency of 915 MHz for the entire simulation runtime.
The received complex samples are amplitude demodulated by extracting their magnitude. The on-off
keyed Manchester coding implies that the bit selection block includes clock recovery. The output of
this block is bit sequences (ignoring the idle times in the transmission) which are subsequently
checked for the known preamble. If the preamble matches, the bit sequence is further decoded,
otherwise, it is discarded and the next sequence is processed.
When the known SCM preamble is found for a bit sequence, the received message bits are decoded
using a shortened (255,239) BCH code which can correct up to two bit errors. In the case where the
known IDM preamble is found, the receiver performs a cyclic redundancy check (CRC) of the meter
serial number and of the whole packet starting at the Packet type (the 5th byte) to determine if the
packet is valid. Valid, corrected messages are passed onto the AMR Message parser.
Message Parser
For a valid message, the bits are then parsed into the specific fields of either the IDM or SCM format.
This example can parse both the SCM format and the IDM format.
Data Viewer
7-95
7 Examples
The data viewer shows the decoded SCM or IDM messages on a user interface. For each successfully
decoded SCM/IDM, the commodity type, meter ID, consumption information and the capture time is
shown. As data is captured and decoded, the application lists the information decoded from these
messages in a tabular form. The table lists only the unique meter IDs with their latest consumption
information.
You can also change the meter ID and start text file logging using the user interface.
• Meter ID - The default value, 0, is reserved for displaying all detected meters. You can enter the
ID of a specific meter to display readings from only that meter ID.
• Log data to file - Save the decoded messages in a TXT file. You can use the saved data for post
processing.
This figures shows the meter readings displayed in the user interface.
Further Exploration
The data file accompanying the example has only one meter reading and has been captured at center
frequency of 915 MHz. Using RTL-SDR or ADALM-PLUTO radio, the example will display readings
from multiple meters when it is run for a longer period in a residential neighborhood.
You can further explore AMR signals using the AMRSimulinkExampleApp app. The app allows you to
set the run duration, select the signal source, change the center frequency of the radio, and run to
log meter readings.
7-96
Automatic Meter Reading in Simulink
Selected Bibliography
7-97
7 Examples
This example shows how to build an FM mono or stereo receiver. You can either use previously
captured signals, or receive signals in real time using the RTL-SDR, ADALM-PLUTO or USRP™ radio.
By default, this example runs using previously captured data. Optionally, you can receive signals over-
the-air. For this, you also need one of the following:
Introduction
For an introduction to the FM broadcasting technology and demodulation of these signals, refer to
the “FM Broadcast Receiver” example.
To run the example using captured signals, select the FM Broadcast Captured Signal block as
the source using the Signal Source Selector block. Then click the run button.
To run the example using the RTL-SDR radio, ADALM-PLUTO radio or USRP radio as the source,
select the corresponding RTL-SDR Receiver, ADALM-PLUTO Radio Receiver or USRP Radio
Receiver block as the source using the Signal Source Selector block. Double-click the Center
Frequency (MHz) block and select the value to the center frequency to a broadcast FM radio
station near you.
If you hear some dropouts or delay in the sound, run the model in Accelerator mode. From the model
menu, select Simulation->Accelerator, then click the run button. If you still experience dropouts or
delay in Accelerator mode, try running the model in Rapid Accelerator mode.
Receiver Structure
The receiver structure in this block diagram represents the FMReceiverSimulinkExample.slx model
used in this example. The processing has three main parts: signal source, FM broadcast
demodulation, and audio output.
Warning: Sample rate setting is ignored. This block uses master clock rate and
decimation/interpolation factor to calculate sample rate.
Warning: Sample time setting is ignored. This block uses master clock rate and
decimation/interpolation factor to calculate sample time.
7-98
FM Broadcast Receiver in Simulink
Signal Source
1 ''Captured Signal'': Over-the-air signals written to a file and sourced using a Baseband File
Reader block at 228e3 samples per second.
2 ''RTL-SDR Radio'': RTL-SDR radio running at 200e3 samples per second. Set the center
frequency to a broadcast FM radio station near you.
3 ''ADALM-PLUTO Radio Receiver'': ADALM-PLUTO radio running at 200e3 samples per second.
Set the center frequency to a broadcast FM radio station near you.
4 ''USRP Radio Receiver'': USRP radio running at 200e3 samples per second. Set the center
frequency to a broadcast FM radio station near you.
FM Broadcast Demodulation
The baseband samples received from the signal source are processed by the FM Broadcast
Demodulation Baseband block. This block converts the input sampling rate of 228 kHz to 45.6
kHz, the sampling rate for your host computer's audio device. According to the FM broadcast
7-99
7 Examples
standard in the United States, the de-emphasis lowpass filter time constant is set to 75 microseconds.
This example processes received mono signals. The demodulator can also process stereo signals.
To perform stereo decoding, the FM Broadcast Demodulator Baseband object uses a peaking filter
which picks out the 19 kHz pilot tone from which the 38 kHz carrier is created. Using the resulting
carrier signal, the FM Broadcast Demodulator Baseband block downconverts the L-R signal, centered
at 38 kHz, to baseband. Afterwards, the L-R and L+R signals pass through a 75 microsecond de-
emphasis filter. The FM Broadcast Demodulator Baseband block separates the L and R signals and
converts them to the 45.6 kHz audio signal.
Play the demodulated audio signals through your computer's speakers using the Audio Device
Writer block.
Further Exploration
To further explore the example, you can vary the center frequency of the RTL-SDR radio, ADALM-
PLUTO radio or USRP radio and listen to other radio stations using the Center Frequency (MHz)
block.
You can set the Stereo property of the FM Broadcast Demodulator Baseband block to true to
process the signals in stereo fashion and compare the sound quality.
Selected Bibliography
https://en.wikipedia.org/wiki/FM_broadcasting
7-100
Frequency Correction for ADALM-PLUTO Radio in Simulink
This example shows how to synchronize both the baseband sample rate and the center frequency of
two PlutoSDRs by using the Frequency correction parameter of the ADALM-PLUTO Radio Receiver
block.
The baseband sample rate and the center frequency of a PlutoSDR are physically derived from the
same oscillator. Although each PlutoSDR is factory-calibrated to use appropriate PLL settings to
digitally compensate for component variations of the oscillator, the compensation is imperfect
because of quantization effects and changes in operating conditions (temperature in particular).
Consequently, two PlutoSDRs will operate at slightly different baseband sample rates and center
frequencies even if the corresponding System objects or Simulink blocks for the two PlutoSDRs use
the same baseband sample rate and the same center frequency. To solve this problem, the Frequency
correction parameter of the ADALM-PLUTO Radio Receiver block can be used.
The Frequency correction parameter specifies the parts-per-million change to the baseband sample
rate and the center frequency. The default value is 0, which means that the radio will use its factory-
calibrated PLL settings. In this example, we treat one PlutoSDR, the transmitter, as a source with
accurate baseband sample rate and center frequency. We use the signal received by another
PlutoSDR, the receiver, to estimate the right value of Frequency correction for the receiver block, and
show that when Frequency correction is set appropriately, the frequency of the received tone will be
very close to 80 kHz, the frequency of the transmitted tone.
Refer to the Getting Started documentation for details on configuring your host computer to work
with the PlutoSDR.
Consider a signal transmitted from one PlutoSDR to another PlutoSDR. Let and be the center
frequency and the baseband sample rate of the transmitter. Let and be the center frequency and
the baseband sample rate of the receiver. Assume that the oscillator of the transmitter has not drifted
and the oscillator of the receiver has drifted by a factor , i.e. and where
is a number very close to 1.
A tone at baseband frequency in the transmitted signal will appear as a tone at baseband
To remove the frequency offset between the transmitter and the receiver, we need to scale the
baseband sample rate and the center frequency of the receiver by a factor of . Let be the parts-
per-million change to the baseband sample rate and the center frequency of the receiver. Then
. Therefore .
7-101
7 Examples
We use one PlutoSDR to transmit three tones at 20, 40, and 80 kHz. The tone at 80 kHz is used to
estimate the value for Frequency correction for the receiver. The tones at 20 and 40 kHz are only
used to help visualize the spectrum.
% Run the receiver. The detected frequency may be far from 80 kHz
disp('Running the receiver...');
sim('plutoradioFrequencyCorrectionRx')
disp(['The detected frequency is ' num2str(peakFreq/1000) ' kHz.']);
txRadioInfo =
7-102
Frequency Correction for ADALM-PLUTO Radio in Simulink
7-103
7 Examples
currentFrequencyCorrection =
7-104
Frequency Correction for ADALM-PLUTO Radio in Simulink
newFrequencyCorrection =
-4.9426
Run the receiver again. The detected frequency should be closer to 80 kHz.
7-105
7 Examples
This model shows how to use the ADALM-PLUTO Radio with Simulink® to implement a QPSK
receiver. The receiver addresses practical issues in wireless communications, e.g. carrier frequency
and phase offset, timing offset and frame synchronization. This model receives the signal sent by the
“QPSK Transmitter with ADALM-PLUTO Radio in Simulink” on page 7-111 example. The receiver
demodulates the received symbols and outputs a simple message to the MATLAB® command line.
Overview
This model performs all processing at complex baseband to handle a time-varying frequency offset, a
time-varying symbol delay, and Gaussian noise. To cope with the above-mentioned impairments, this
example provides a reference design of a practical digital receiver, which includes correlation-based
coarse frequency compensation, symbol timing recovery with fixed-rate resampling and bit stuffing/
skipping, fine frequency compensation, frame synchronization and phase ambiguity resolution. The
example uses some key algorithms in MATLAB, emphasizing textual algorithm expression over
graphical algorithm expression.
The top-level structure of the model is shown in the following figure, which includes a ADALM-PLUTO
receiver block, a QPSK Receiver subsystem and a BER Display blocks.
The detailed structures of the QPSK Receiver subsystem are illustrated in the following figure.
7-106
QPSK Receiver with ADALM-PLUTO Radio in Simulink
Receiver
AGC
The received signal amplitude affects the accuracy of the carrier and symbol synchronizer. Therefore
the signal amplitude should be stabilized to ensure an optimum loop design. The AGC output power is
set to a value ensuring that the equivalent gains of the phase and timing error detectors keep
constant over time. The AGC is placed before the Raised Cosine Receive Filter so that the signal
7-107
7 Examples
amplitude can be measured with an oversampling factor of two, thus improving the accuracy of the
estimate. You can refer to Chapter 7.2.2 and Chapter 8.4.1 of [ 1 ] for details on how to design the
phase detector gain.
The Raised Cosine Receive Filter provides matched filtering for the transmitted waveform with a
rolloff factor of 0.5.
The Coarse Frequency Compensation subsystem corrects the input signal with a rough estimate of
the frequency offset. The following diagram shows the subsystem, in which the frequency offset is
estimated by averaging the output of the correlation-based algorithm of the Coarse Frequency
Compensator block. The compensation is performed by the Phase/Frequency Offset block. There is
usually a residual frequency offset even after the coarse frequency compensation, which would cause
a slow rotation of the constellation. The Carrier Synchronizer block compensates for this residual
frequency.
The accuracy of the Coarse Frequency Compensator decreases with its maximum frequency offset
value. Ideally, this value should be set just above the expected frequency offset range.
Symbol Synchronization
The timing recovery is performed by a Symbol Synchronizer library block, which implements a PLL,
described in Chapter 8 of [ 1 ], to correct the timing error in the received signal. The timing error
detector is estimated using the Gardner algorithm, which is rotationally invariant. In other words,
this algorithm can be used before or after frequency offset compensation. The input to the block is
oversampled by two. On average, the block generates one output symbol for every two input samples.
However, when the channel timing error (delay) reaches symbol boundaries, there will be one extra
or missing symbol in the output frame. In that case, the block implements bit stuffing/skipping and
generates one more or less samples comparing to the desired frame size. So the output of this block
is a variable-size signal.
The Damping factor, Normalized loop bandwidth, and Detector gain parameters of the block are
tunable. Their default values are set to 1 (critical damping), 0.01 and 5.4 respectively, so that the PLL
quickly locks to the correct timing while introducing little timing jitter.
7-108
QPSK Receiver with ADALM-PLUTO Radio in Simulink
Carrier Synchronization
The fine frequency compensation is performed by a Carrier Synchronizer library block, which
implements a phase-locked loop (PLL), described in Chapter 7 of [ 1 ], to track the residual frequency
offset and the phase offset in the input signal. The PLL uses a Direct Digital Synthesizer (DDS) to
generate the compensating phase that offsets the residual frequency and phase offsets. The phase
offset estimate from DDS is the integral of the phase error output of a Loop Filter.
The Damping factor and Normalized loop bandwidth parameters of the block are tunable. Their
default values are set to 1 (critical damping) and 0.01 respectively, so that the PLL quickly locks to
the intended phase while introducing little phase noise.
Frame Synchronization
The Frame Synchronizer MATLAB System block uses the known frame header (QPSK-modulated
Barker code) to correlate against the received QPSK symbols to locate the frame header and align the
frame boundaries. It also transforms the variable-size output of the Symbol Synchronizer block into a
fixed-size frame, which is necessary for the downstream processing. The second output of the block is
a boolean scalar indicating if the first output is a valid frame with the desired header and if so,
enables the Data Decoding subsystem to run.
Decode Data
The Data Decoding enabled subsystem performs phase ambiguity resolution, demodulation and text
message decoding. The Carrier Synchronizer block may lock to the unmodulated carrier with a phase
shift of 0, 90, 180, or 270 degrees, which can cause a phase ambiguity. For details of phase ambiguity
and its resolution, please refer to Chapter 7.2.2 and 7.7 in [ 1 ]. The Phase Offset Estimator
subsystem determines this phase shift. The Phase Ambiguity Correction & Demodulation subsystem
rotates the input signal by the estimated phase offset and demodulates the corrected data. The
payload bits are descrambled, and then decoded. All of the stored bits are converted to characters
are printed in the Simulink Diagnostic Viewer.
Before running this model, first connect two ADALM-PLUTO Radios to the computer and start the
plutoradioQPSKTransmitterSimulinkExample model from the “Frequency Offset Calibration
with ADALM-PLUTO Radio in Simulink” on page 7-126 example. This receiver model is capable of
handling a frequency offset of 12.5kHz between the transmitter and receiver boards. However, when
the frequency offset exceeds this range, the Coarse Frequency Compensation subsystem cannot
7-109
7 Examples
accurately determine the offset of the received signal, which is critical for correct timing recovery
and data decoding. Due to hardware variations among the ADALM-PLUTO Radios, a frequency offset
will likely exist between the transmitter hardware and the receiver hardware. In that case, examine
the resulting frequency offset by performing a manual frequency calibration using the companion
frequency offset calibration plutoradiofreqcalib transmitter and plutoradiofreqcalib_rx
receiver models included with the “Frequency Offset Calibration with ADALM-PLUTO Radio in
Simulink” on page 7-126 example. With that frequency offset value, you can manually adjust the
Center frequency of the ADALM-PLUTO Receiver subsystem in the receiver model to ensure a
residual frequency offset that the model can track.
If the received signal is too weak or too strong, you might notice some garbled message output. In
that case, you can change the gain of either the ADALM-PLUTO Transmitter subsystem in the
plutoradioQPSKTransmitterSimulinkExample model or the ADALM-PLUTO Receiver
subsystem in the current model for better reception.
Set the Center frequency parameter of the ADALM-PLUTO Radio Receiver block according to the
center frequency setting of the plutoradioQPSKTransmitterSimulinkExample model and the
frequency calibration result. Then run the model. To ensure real-time processing, the model is by
default set to run in Accelerator mode, and to remove all signal visualization. The received messages
are decoded and printed out in the View diagnostics window while the simulation is running. To
ensure real-time operation, run the models on two separate MATLAB sessions; one for transmitter
and the other for receiver.
The example allows you to experiment with multiple system capabilities to examine their effect on bit
error rate performance.
You can tune the Normalized loop bandwidth and Damping factor parameters of the Symbol
Synchronizer and Carrier Synchronizer blocks, to assess their convergence time and estimation
accuracy. In addition, you can assess the pull-in range of the Carrier Synchronizer block. With a large
Normalized loop bandwidth and Damping factor, the PLL can acquire over a greater frequency offset
range. However a large Normalized loop bandwidth allows more noise, which leads to a large mean
squared error in the phase estimation. "Underdamped systems (with Damping Factor less than one)
have a fast settling time, but exhibit overshoot and oscillation; overdamped systems (with Damping
Factor greater than one) have a slow settling time but no oscillations." [ 1 ]. For more detail on the
design of these PLL parameters, you can refer to Appendix C in [ 1 ].
You can also tune the Preamble detector threshold and see its effects on the output message.
References
1. Michael Rice, "Digital Communications - A Discrete-Time Approach", Prentice Hall, April 2008.
7-110
QPSK Transmitter with ADALM-PLUTO Radio in Simulink
This model shows how to use the ADALM-PLUTO Radio with Simulink® to implement a QPSK
transmitter. The ADALM-PLUTO Radio in this model will keep transmitting indexed 'Hello world'
messages at its specified center frequency. You can demodulate the transmitted message using the
“QPSK Receiver with ADALM-PLUTO Radio in Simulink” on page 7-106 example. This example
assumes that two ADALM-PLUTO Radios are attached to your computer.
The transmitter includes the Bit Generation subsystem, the QPSK Modulator block, and the
Raised Cosine Transmit Filter block. The Bit Generation subsystem uses a MATLAB workspace
variable as the payload of a frame, as shown in the figure below. Each frame contains 100 'Hello
world ###' messages and a header. The first 26 bits are header bits, a 13-bit Barker code that has
been oversampled by two. The Barker code is oversampled by two in order to generate precisely 13
QPSK symbols for later use in the Data Decoding subsystem of the receiver model. The remaining
bits are the payload. The payload correspond to the ASCII representation of 'Hello world ###',
where '###' is a repeating sequence of '000', '001', '002', ..., '099'. The payload is scrambled to
guarantee a balanced distribution of zeros and ones for the timing recovery operation in the receiver
model. The scrambled bits are modulated by the QPSK Modulator (with Gray mapping). The
modulated symbols are upsampled by two by the Raised Cosine Transmit Filter with a roll-off
factor 0.5. The output rate of the Raised Cosine Filter is set to be 400k samples/second with a
symbol rate of 200k symbols per second. Please match the symbol rate of the transmitter model and
the receiver model correspondingly.
7-111
7 Examples
Before running the model, connect two ADALM-PLUTO Radios to the computer. Set the Center
frequency parameter of the ADALM-PLUTO Radio Transmitter block and run the model. You can
run the QPSK Receiver with ADALM-PLUTO Radio model to receive the transmitted signal. We
suggest initialize two MATLAB® sessions to ensure real-time process.
Due to hardware variations among the ADALM-PLUTO Radios, a frequency offset will likely exist
between the transmitter hardware and the receiver hardware. In that case, perform a manual
frequency calibration using the companion frequency offset calibration plutoradiofreqcalib
transmitter and plutoradiofreqcalib_rx receiver models and examine the resulting behavior.
If the message is not properly decoded by the receiver model, you can vary the gain of the source
signals in the ADALM-PLUTO Radio Transmitter block of this model, and that of the ADALM-
PLUTO Radio Receiver block in the receiver model.
7-112
RDS/RBDS and RadioText Plus (RT+) FM Receiver in Simulink
This example shows how to extract program or song information from FM radio stations using the
RDS or RBDS standard and, optionally, the RadioText Plus (RT+) standard. You can use a previously
captured signal, or receive signals over-the-air in real time using an RTL-SDR radio, an ADALM-
PLUTO radio, or a USRP™ radio.
By default, this example runs using recorded data from a file. Optionally, you can receive signals over-
the-air using a device that supports the required sample rate of 228 ksps. For this, you also need one
of the following:
• RTL-SDR radio and Communications Toolbox Support Package for RTL-SDR Radio.
• Pluto radio and Communications Toolbox Support Package for Analog Devices® ADALM-PLUTO
Radio.
• USRP B2xx series radio and Communications Toolbox Support Package for USRP Radio. For
information on supported radios, see “Supported Hardware and Required Software”.
• USRP E3xx series radio and Wireless Testbench Support Package for NI USRP Radios. For
information on supported radios, see “Supported Radio Devices” (Wireless Testbench).
Background
RBDS and RDS are very similar standards specifying how to supplement FM radio signals with
additional information. RBDS is used in North America, while RDS was originally used in Europe and
evolved to an international standard. RBDS and RDS comprise 3 layers:
The RBDSSimulinkExample model in this diagram receives FM signals either from a captured file or
over the air. The model plays the audio signal and displays the RBDS information.
7-113
7 Examples
The physical layer subsystem receives the captured signal from a file or the live signal from the radio
and performs these steps:
• FM demodulation: Once the FM signal is demodulated, the RDS/RBDS signal resides at the 57
kHz +/- 2.4 kHz band. Be aware that the RDS/RBDS signal is transmitted with relatively low
power, so it is not always visible in the FM spectrum as shown in this figure.
7-114
RDS/RBDS and RadioText Plus (RT+) FM Receiver in Simulink
FM signals contain a pilot tone at 19 kHz, which can be used as a phase and frequency reference for
coherent demodulation of the RDS/RBDS signal at 57 kHz and the stereo audio at 38 kHz. Pilot tones
at 38 kHz and 57 kHz can be generated by doubling and tripling the frequency of the 19 kHz pilot
tone [ 2 ].
• Bandpass filtering: The PHY receiver conducts bandpass filtering at 19 kHz and 57 kHz, to
isolate the pilot tone and the RDS/RBDS signal, respectively.
• Frequency tripling: Raise the complex representation of the 19 kHz pilot tone to the 3rd power
to triple its frequency and obtain a 57 kHz pilot tone.
• AM Demodulation: RDS and RBDS symbols are generated at an 1187.5 Hz rate and are AM-
modulated to a 57 kHz carrier. The 57 kHz RDS/RBDS signal can be coherently demodulated with
a 57 kHz carrier that is locked in frequency and phase. Typically, the frequency-tripled 19 kHz
pilot tone suffices for coherent demodulation. The next figures show the 19 kHz and 57 kHz pilot
tones, the 57 kHz RDS/RBDS signal, and the AM-demodulated baseband RDS/RBDS signal.
7-115
7 Examples
At the same time, there exist several FM stations whose 57 kHz RDS/RBDS signal exhibits a time-
varying phase offset from the 19 kHz pilot tone and its frequency-tripled version. The PHY receiver
contains a Costas loop to compensate for such time-varying phase offsets.
• Costas loop: The Costas loop performs 2 orthogonal AM demodulations, one demodulation with a
57 kHz sine and another with a 57 kHz cosine. The sampling rate of the received signal is
carefully chosen as 228 kHz, which provides 4 samples per 57 kHz cycle. Therefore, a one sample
delay of the 57 kHz pilot tone results to a one quarter wavelength phase offset, and allows us to
generate a cosine wave from a sine wave. The sine-demodulated signal corresponds to the
coherent demodulation output. The cosine-demodulated signal is used for detection of phase error.
The products of the 57 kHz RDS/RBDS signal with the sine/cosine waves are low-pass filtered with
the filter specified in Sec. 1.7 of [ 1 ]. The product of the two filter outputs is an error signal. The
larger it is, the more the 19 kHz pilot tone is delayed to behave more like the cosine-based
demodulator.
7-116
RDS/RBDS and RadioText Plus (RT+) FM Receiver in Simulink
• Clock extraction: To perform biphase symbol decoding, a clock matching the RDS/RBDS symbol
rate of 1187.5 Hz is extracted from the 19 kHz pilot tone. Note, 1187.5 Hz x 16 = 19 kHz. To
account for frequency offsets, frequency division is used to extract the clock from the 19 kHz pilot
tone. Since the frequency division operation provides multiple correct answers, the baseband
RDS/RBDS signal serves as training data that aid in the determination of the desired output.
• Biphase symbol decoder: RDS and RBDS use bi-phase-level (bi- -L) coding, which is commonly
known as Manchester coding. In each clock cycle, the RDS/RBDS symbol takes two opposite
amplitude values, either a positive followed by a negative, or a negative followed by a positive.
The biphase symbol decoder negates the second amplitude level, so that each symbol holds the
same amplitude level throughout the entire clock cycle. The new clock-wide amplitude level
corresponds to the symbol's bit representation. These screenshots correspond to the waveforms
#1-6 in Figure 2 of [ 1 ].
7-117
7 Examples
To obtain each symbol's bit value, the waveform is integrated over each clock cycle, and the outcome
is compared to zero (slicer).
7-118
RDS/RBDS and RadioText Plus (RT+) FM Receiver in Simulink
• Differential decoding: Finally, the bits are differentially decoded to revert the differential
encoding at the transmitter.
Layer 2 is implemented using the RBDSDataLinkDecoder System block. This layer is responsible for
synchronization and error correction.
The bit output of the PHY layer is logically organized in 104-bit groups comprising four 26-bit blocks.
Each block contains a 16-bit information word and 10 parity bits (see Figure 8 in [ 1 ]). A distinct 10-
bit offset word is modulo-2 added to the parity bits of each block.
• Synchronization: Initially, block and group boundaries are sought exhaustively using a sliding
window of 104 bits. For each 104-bit window, the 4 offset words are sought at the last 10 bits of
each 26-bit block. An offset word is identified if no bit errors are detected in the
RBDSErrorDetection System block. Once the offset words are identified, group-level
7-119
7 Examples
synchronization is attained and the exhaustive sliding-window processing stops. Subsequently, the
next 104 bits will be treated as the next group.
If future groups contain bit errors and the offset words cannot be identified at their expected
position, synchronization may be lost. In this case, Layer 2 first examines the possibility of 1-bit
synchronization slips, exploiting the fact that the first information word (16 bits) is always the same
for all bit groups. If the first information word is found dislocated by 1 bit (either leftward or
rightward), synchronization is retained and the group boundaries are adjusted accordingly. If bit
errors persist for 25 group receptions and at the same time synchronization cannot be reestablished
using such leftward/rightward 1-bit shifts, then synchronization is lost and Layer 2 re-enters the
exhaustive, sliding-window-based search for synchronization.
• Error correction: The RDS and RBDS error correction code is a (26, 16) cyclic code shortened
from (341, 331). The RBDSErrorCorrection System block uses the shift-register scheme
described in Annex B of [ 1 ].
Layer 2 removes the parity/offset bits, therefore Layer 3 receives groups of 64-bits, comprising four
16-bit blocks. There exist up to 32 different group types, each labeled with a number from 0 to 15 and
the letter 'A' or 'B', for example, 0B, 2A, 3A. The format of each group can be fixed or it can be
abstract if this group is allocated for an Open Data Application (ODA, see list in [ 3 ]).
Layer 3 is implemented using the RBDSSessionDecoder System block. This block supports decoding
of the 0A, 0B, 2A, 2B, 3A, 4A, 10A fixed-format group types.
For ODAs, the RDS/RBDS receiver supports decoding of RadioText Plus (RT+) [ 4 ]. This ODA can
break down the long 32 or 64-character string from group types 2A and 2B into two specific content
types (for example, artist and song).
Viewing Results
This screenshot illustrates the graphical display of the processed RDS/RBDS data:
7-120
RDS/RBDS and RadioText Plus (RT+) FM Receiver in Simulink
1 The first field corresponds to the program type, which is conveyed by the second information
word of all group types. If 10A group types are received, the first field provides further
characterization, such as Sports \ Football.
2 The second field illustrates the 8-character text conveyed by 0A/0B groups.
3 The third field illustrates the longer 32/64-character text conveyed by 2A/2B group types.
• RadioText Plus (RT+): This section is used if any 3A groups indicate that the RadioText Plus (RT
+) ODA [ 4 ] uses a certain abstract-format group type, such as 11A. Then, upon receptions of this
abstract group type, the 32/64-character text conveyed by groups 2A/2B will be split to two
substrings. Moreover, the two labels will be updated to characterize the substrings, such as Artist
and Song.
• Group type receptions: The tables act as a histogram illustrating which group types have been
received from a station and with what frequency. As a result, users may want to look at the logged
data for further information not depicted in the graphical viewer. For example, system time in 4A,
alternate frequencies in 0A, or others.
• Open data applications (ODA): If any 3A group types are received, then the list of encountered
ODAs is updated with the ODA name and their dedicated group type.
Moreover, you can enable the 'Log data to file' checkbox in order to log further fields from all group
types.
Selected Bibliography
1 National Radio Systems Committee, United States RBDS standard, April 1998
2 Der, Lawrence. "Frequency Modulation (FM) Tutorial". Silicon Laboratories Inc.
3 National Radio Systems Committee, List of ODA Applications in RDS
4 RadioText Plus (RT+) Specification
7-121
7 Examples
5 Joseph P. Hoffbeck, "Teaching Communication Systems with Simulink® and the USRP", ASEE
Annual Conference, San Antonio, TX, June 2012
7-122
Spectrum Analysis of Signals in Simulink
This example shows you how to use Simulink® to undertake spectral analysis of signals. You can tune
the radio to a band where a signal is present by changing the center frequency. You can then use the
spectrum analyzer to view and make measurements on the received spectrum. You can either use
recorded data from a file, or receive over-the-air signals in real time using an RTL-SDR radio,
ADALM-PLUTO radio, or USRP™ radio.
The “Spectrum Analysis of Signals” example provides a MATLAB® implementation of this example.
By default, this example runs using recorded data from a file. Optionally, you can receive signals over-
the-air. For this, you also need one of the following:
• RTL-SDR radio and Communications Toolbox Support Package for RTL-SDR Radio.
• Pluto radio and Communications Toolbox Support Package for Analog Devices® ADALM-PLUTO
Radio.
• USRP N2xx or B2xx series radio and Communications Toolbox Support Package for USRP Radio.
For information on supported radios, see “Supported Hardware and Required Software”.
• USRP E3xx, N3xx, X3xx, or X4xx series radio and Wireless Testbench Support Package for NI
USRP Radios. For information on supported radios, see “Supported Radio Devices” (Wireless
Testbench).
Overview
The spectralAnalysis model performs an FFT-based spectrum analysis at complex baseband, and
provides:
7-123
7 Examples
Spectrum Analyzer
This figure shows the output of the Spectrum Analyzer for a data signal recorded in the
spectrum_capture.bb file. The spectrum shows data captured over the FM radio band, specifically
over the frequency range of 88 MHz to 108 MHz.
7-124
Spectrum Analysis of Signals in Simulink
When you run the example, you can measure signal characteristics such as peaks, occupied
bandwidth, adjacent channel power ratio, harmonic and intermodulation levels, and spur-free
dynamic range.
7-125
7 Examples
These two models show how to determine the relative frequency offset between two ADALM-PLUTO
radios.
The transmitter sends a 12000 Hz sine wave with the plutoradiofreqcalib Frequency Offset
Calibration (Tx) with ADALM-PLUTO Radio> model. The receiver receives the signal, calculates the
frequency offset and displays the offset in the plutoradiofreqcalib_rx Frequency Offset
Calibration (Rx) with ADALM-PLUTO Radio> model.
This example deals with offset in the center frequency only. To compensate for offsets in both the
center frequency and the baseband sample rate, see the
FrequencyCorrectionForADALMPLUTORadioExample Frequency Correction for ADALM-PLUTO
Radio example.
Overview
These two models perform an FFT-based frequency offset calculation at complex baseband. The
receiver model provides the following information:
7-126
Frequency Offset Calibration with ADALM-PLUTO Radio in Simulink
The following figure shows the detailed structure of the Receiver subsystem:
• The Find Peak Frequency block - uses an FFT to find the frequency with the maximum power in
the received signal.
• The Spectrum Analyzer block - computes and displays the power spectral density of the received
signal.
Receiver
The Find Peak Frequency subsystem finds the frequency with the maximum power in the received
signal, which equals the frequency offset plus 12000 Hz. The following diagram shows the subsystem.
In this subsystem, the Periodogram block returns the PSD estimate of the received signal. The Probe
block finds the frame size and the frame sample time. With this information, this subsystem finds the
index of the maximum amplitude across the frequency band and converts the index to the frequency
value according to
7-127
7 Examples
Spectrum Analyzer
The following figure shows the output of the Spectrum Analyzer on a frequency range of -50 kHz to
50 kHz. In the case shown below, the frequency with the maximum power of the received signal is
about 7 kHz, and the spur-free dynamic range of the receiver is about 34 dB.
7-128
Frequency Offset Calibration with ADALM-PLUTO Radio in Simulink
Connect two ADALM-PLUTO Radios to the computer. Run the plutoradiofreqcalib Frequency
Offset Calibration (Tx) with ADALM-PLUTO Radio model, and then open the
plutoradiofreqcalib_rx Frequency Offset Calibration (Rx) with ADALM-PLUTO Radio model.
To run the receiver model, set the Center frequency parameter of the ADALM-PLUTO Radio
Receiver block to the same value as the center frequency setting of the plutoradiofreqcalib
Frequency Offset Calibration (Tx) with ADALM-PLUTO Radio model. Then run the model. The
frequency offset is calculated and displayed while the simulation is running.
To compensate for a transmitter/receiver frequency offset, add the displayed frequency offset value to
the center frequency of the ADALM-PLUTO Radio Receiver block. If the displayed frequency offset is
negative, then subtract it from the center frequency. The spectrum displayed by the Spectrum
Analyzer block should then have its maximum at 12000 Hz.
7-129
7 Examples
This example shows how to tune software-defined radios (SDRs) to receive signals using the SDR
Receiver app. In this example, you:
To run this example, you need one of these radios and the corresponding software support package.
• USRP™ N2xx series or B2xx series radio and Communications Toolbox Support Package for USRP
Radio. For more information, see “USRP Radio” and “Supported Hardware and Required
Software”.
• USRP™ N3xx series, X series, or E320 radio and Wireless Testbench Support Package for NI
USRP Radios. For more information, see “Supported Radio Devices” (Wireless Testbench)
(Wireless Testbench).
• ADALM-PLUTO radio and Communications Toolbox Support Package for Analog Devices®
ADALM-PLUTO Radio. For more information, see “ADALM-Pluto Radio”.
• RTL-SDR radio and the Communications Toolbox™ Support Package for RTL-SDR Radio. For more
information, see “RTL-SDR Radio”.
Introduction
An SDR is a wireless device that consists of a configurable RF front end with an FPGA or
programmable system-on-chip (SoC) to perform digital functions. Commercially available SDRs
transmit and receive signals at different frequencies to implement wireless standards such as FM,
LTE, WLAN, and 5G.
7-130
Signal Reception Using Software-Defined Radios
The SDR Receiver app allows you to interactively tune the gain of the selected SDR and obtain phase,
and both coarse and fine frequency offsets. The image shows a schematic of the workflow used in the
SDR Receiver app.
app = SDRReceiver();
7-131
7 Examples
Configure SDR
Select SDR
SDR Type: Select the type of SDR. You can select USRP, RTL-SDR, or PLUTO. Each time you change
the SDR Type, the app refreshes the list of available SDRs.
SDR Name: Select the SDR platform from the drop-down list.
SDR Address: Select the SDR address of the required radio form the drop-down list.
Refresh SDR List: If you are unable to see your radio in the list, click Refresh SDR List.
Center Frequency (Hz): Specify Center Frequency as a nonnegative scalar. The valid range of
Center Frequency values varies from SDR to SDR with the following considerations:
• For USRP radios, the valid range of Center Frequency depends on the RF daughter card.
7-132
Signal Reception Using Software-Defined Radios
• For PLUTO radio, the valid tuning range of Center Frequency is from 325 MHz to 3.8 GHz.
Communications Toolbox Support Package for Analog Devices ADALM-Pluto Radio enables you to
use the PLUTO radio outside the qualified tuning range by configuring the radio to operate using
the AD9364 firmware. To extend the Center Frequency range, at the MATLAB command prompt,
enter configurePlutoRadio('AD9364').
• For RTL-SDR, list of tuner chips and their Center Frequency ranges, see [1 on page 7-135].
Rx Gain (dB): Specify the SDR receiver gain in dB. The valid range of Rx Gain values varies from
SDR to SDR with the following considerations:
• For USRP radios, the valid range of Rx Gain depends on the RF daughter card. To get valid gain
values, use the info() method of comm.SDRuReceiver.
• For PLUTO radio, Rx Gain ranges from -4 to 71 dB.
• For RTL-SDR, the valid range of Rx Gain values depends on the tuner chip. To get valid gain
values, use the info() method of comm.SDRRTLReceiver.
Sample Rate (Hz): Specify the baseband sample rate of the radio front end in Hz as a positive
numeric scalar with the following considerations:
• For USRP radios, Sample Rate depends on the master clock rate (MCR) and decimation factor.
For more information, see comm.SDRuReceiver.
• For PLUTO radio, Sample Rate is the same value as the BasebandSampleRate property of
comm.SDRRxPluto. It ranges from 65105 to 61.44e6 samples per second.
• For RTL-SDR, the valid range of Sample Rate is [225, 300] kHz and [900, 3200] in kHz. If you set
the Sample Rate greater than 2560 kHz, you might observe dropped samples. For more
information about the maximum reliable sample rate, see [1].
Frame Size: Specify number of samples per frame of the output signal, specified as a positive integer
with following considerations:
• For USRP radios, Frame Size is the same value as the SamplesPerFrame property of
comm.SDRuReceiver. For more information, see comm.SDRuReceiver.
• For PLUTO radio, Frame Size is the same value as the SamplesPerFrame property of
comm.SDRRxPluto. Specify Frame Size as an even positive integer from 2 to 16,777,216.
• For RTL-SDR, Frame Size is the same value as the SamplesPerFrame property of
comm.SDRRTLReceiver. For more information, see comm.SDRRTLReceiver.
For more information on the range of parameters, use info() method of the respective receiver
System objects.
Receive Signal
Start/Pause: Click START to receive the signal. To pause the signal reception, click PAUSE. Once
reception starts:
Apply RF Corrections
In radio frequency (RF) communication systems, RF corrections such as phase offset and frequency
offset are essential for ensuring accurate signal transmission and reception. Phase offset refers to the
7-133
7 Examples
discrepancy in phase between a received signal and a reference signal, which can affect the integrity
of the transmitted data. Frequency offset denotes the difference between the expected carrier
frequency and the actual received frequency, potentially leading to misalignment and degraded signal
quality. Correcting these offsets is crucial for maintaining optimal performance and reliability in
wireless communication systems.
The SDR Receiver app helps you to interactively estimate phase and frequency offsets using Phase
Offset (deg), Coarse Frequency (Hz), and Fine Frequency (Hz) during simulation. Change these
parameters to see how they impact the Constellation plot.
You can visualize the receiving signal using these three plots:
IQ Plot: Plots the real and imaginary parts of the receiving signal, where, X-axis is Samples and Y-
axis is Amplitude.
Power Spectrum Plot: Plots the power spectrum of the received signal. The app generates these
plots using SpectrumAnalyzer app. In the plot, the X-axis is Frequency in Hz and Y-axis is dBFS
(decibels relative to full scale). For more information, see spectrumAnalyzer.
Constellation Plot: Plot the constellation of the received signal and to estimate phase and frequency
offsets.
Stop Reception
Stop: Click STOP to stop the simulation. Once reception stops, the app enables the Select SDR
controls, allowing you to change the radio.
Export To MATLAB Script: Click on Export To MATLAB Script button to generate MATLAB script
for the current SDR Receiver app configuration.
Close the opened SDR Receiver app by closing the window or by using this
app.delete();
7-134
Signal Reception Using Software-Defined Radios
In this example, you tune your SDR and estimate phase and and frequency offsets based on your
requirements. For more information about SDRs see these examples:
References
Helper Functions
• SDRReceiver.m
• helperUISDRRxWidgets.m
• helperUISDRRxController.m
7-135
7 Examples
This example shows how to use the Universal Software Radio Peripheral® (USRP™) and ADALM-
PLUTO device using SDRu and PLUTO Radio System objects to implement a QPSK receiver. The
receiver addresses practical issues in wireless communications, such as carrier frequency and phase
offset, timing offset and frame synchronization. This system receives the signal sent by the QPSK
transmitter at bit rate of up to 1 Mbps. The receiver demodulates the received symbols and prints a
simple message to the MATLAB® command line. For more information on designing a QPSK
transmitter, see the QPSK Transmitter with Software-Defined Radio (SDR) example.
To run this example, you need one of these USRP or ADALM-PLUTO radios and the corresponding
hardware support package.
• USRP™ N2xx series or B2xx series radio and Communications Toolbox Support Package for USRP
Radio. For more information, see “USRP Radio” and “Supported Hardware and Required
Software”.
• USRP™ N3xx series or X series radio and Wireless Testbench Support Package for NI USRP
Radios. For more information, see “Supported Radio Devices” (Wireless Testbench) (Wireless
Testbench).
• ADALM-PLUTO radio and Communications Toolbox Support Package for Analog Devices®
ADALM-PLUTO Radio. For more information, see “ADALM-Pluto Radio”.
Initialization
Select Radio
Select the required radio SDRName from the availableRadios. For more information regarding
discovery of radios see findsdru and findPlutoRadio for USRP and PLUTO radios respectively.
sdrType = ;
availableRadios = helperFindRadios(sdrType);
7-136
QPSK Receiver Using Software-Defined Radio
SDRName = ;
SDRAddress = ;
The sdrQPSKReceiverInit.m script initializes the simulation parameters and generates the
structure prmQPSKReceiver.
sampleRate = ;
SDR Parameters
SDRGain = ;
SDRCenterFrequency = ;
SDRStopTime = ;
Note:
• To receive successfully, ensure that the specified center frequency of the receiver system objects
is within the acceptable range of the selected RF card.
• Enable either previewReceivedData or printReceivedData, enabling both will show only
preview of received data.
7-137
7 Examples
Code Architecture
Initialization
The function runSDRQPSKReceiver implements the QPSK receiver using two System objects,
1 Either comm.SDRuReceiverfor USRP or comm.SDRRxPluto for ADALM-PLUTO.
2 QPSKReceiver for decoding received data.
USRP/PLUTO Receiver
The host computer communicates with the USRP radio using comm.SDRuReceiver and with the
ADALM-PLUTO radio using the comm.SDRRxPluto System object.
QPSK Receiver
This component regenerates the original transmitted message. It is divided into six subcomponents,
modeled using System objects. Each subcomponent is modeled by other subcomponents using System
objects.
1 Automatic Gain Control: Sets its output power to a level ensuring that the equivalent gains of the
phase and timing error detectors keep constant over time. The AGC is placed before the Raised
Cosine Receive Filter so that the signal amplitude can be measured with an oversampling
factor of two. This process improves the accuracy of the estimate.
2 Coarse frequency compensation: Uses a correlation-based algorithm to roughly estimate the
frequency offset and then compensate for it. The estimated coarse frequency offset is averaged
so that fine frequency compensation is allowed to lock/converge. Hence, the coarse frequency
offset is estimated using a comm.CoarseFrequencyCompensator System object and an
averaging formula; the compensation is performed using a comm.PhaseFrequencyOffset
System object.
3 Timing recovery: Performs timing recovery with closed-loop scalar processing to overcome the
effects of delay introduced by the channel, using a comm.SymbolSynchronizer System object.
7-138
QPSK Receiver Using Software-Defined Radio
The object implements a PLL to correct the symbol timing error in the received signal. The
rotationally-invariant Gardner timing error detector is chosen for the object in this example;
thus, timing recovery can precede fine frequency compensation. The input to the object is a fixed-
length frame of samples. The output of the object is a frame of symbols whose length can vary
due to bit stuffing and stripping, depending on actual channel delays.
4 Fine frequency compensation: Performs closed-loop scalar processing and compensates for the
frequency offset accurately, using a comm.CarrierSynchronizer System object. The object
implements a phase-locked loop (PLL) to track the residual frequency offset and the phase offset
in the input signal.
5 Frame Synchronization: Performs frame synchronization and, also, converts the variable-length
symbol inputs into fixed-length outputs, using a FrameSynchronizer System object. The object
has a secondary output that is a boolean scalar indicating if the first frame output is valid.
6 Data decoder: Performs phase ambiguity resolution and demodulation. Also, the data decoder
compares the regenerated message with the transmitted one and calculates the BER.
To ensure data reception, first start the QPSK Transmitter with Software-Defined Radio example.
Note: Before running the example, first connect the selected SDRName to the computer and turn it
on.
When you run the experiments, the received messages are decoded and preview of the received data
is shown. BER information is also shown at the end of the script execution. The receiver calculates
the BER value even when some of the adaptive components are not converged. This results in a high
BER value. Once the transient period is over, the receiver is able to estimate the transmitted frame
and the BER dramatically decreases. In this example, to guarantee a reasonable execution time of the
system in simulation mode, the simulation duration is fairly short. As such, the overall BER results
7-139
7 Examples
are significantly affected by the high BER values at the beginning of the simulation. To increase the
simulation duration and obtain lower BER values, you can change the SDRStopTime.
Troubleshooting
• The gain behavior of ADALM-PLUTO and different USRP RF cards varies considerably. Thus, the
gain setting in the transmitter and receiver defined in this example may not be well-suited for your
RF cards. If the message is not properly decoded by the receiver system, you can vary the gain of
the source signals in the SDR Transmitter and SDR Receiver System objects by changing the
SDRGain value.
• Preamble detector's threshold also affects the decoded message. If you see recurrent garbled
messages, please try to increase the preamble detector's threshold as the following steps are
trying to decode the header. If you cannot see any output message, try to decrease the threshold
in the receiver initialization file.
• A large relative frequency offset between the transmit and receive USRP radios can prevent the
receiver functions from properly decoding the message. If that happens, you can determine the
offset by sending a tone at a known frequency from the transmitter to the receiver, then
measuring the offset between the transmitted and received frequency, then applying that offset to
the SDRCenterFrequency of the receiver System object. You increase the frequency offset value
in the receiver initialization file to estimate the maximum possible frequency offset at the receiver.
Helper Functions
• helperFindRadios.m
• sdrQPSKReceiverInit.m
• runSDRQPSKReceiver.m
• QPSKReceiver.m
• QPSKDataDecoder.m
• FrameSynchronizer.m
References
[1] Rice, Michael. Digital Communications - A Discrete-Time Approach. 1st ed. New York, NY: Prentice
Hall, 2008.
7-140
QPSK Transmitter Using Software-Defined Radio
This example shows the implementation of a QPSK transmitter using a software-defined radio (SDR),
which modulates and transmits indexed "Hello world" messages at specified center frequency and a
bit rate of 1 Mbps. In this example, the transmitter generates a message using ASCII characters,
converts these characters to bits, and appends a Barker code at the beginning for receiver frame
synchronization. This data is then QPSK modulated and filtered with a square root raised cosine filter.
You can transmit the filtered QPSK symbols over the air using SDR. You can demodulate the
transmitted message using the QPSK Receiver Using Software-Defined Radio example.
To run this example, you need one of these USRP or ADALM-PLUTO radios and the corresponding
hardware support package.
• USRP™ N2xx series or B2xx series radio and Communications Toolbox Support Package for USRP
Radio. For more information, see “USRP Radio” and “Supported Hardware and Required
Software”.
• USRP™ N3xx series or X series radio and Wireless Testbench Support Package for NI USRP
Radios. For more information, see “Supported Radio Devices” (Wireless Testbench) (Wireless
Testbench).
• ADALM-PLUTO radio and Communications Toolbox Support Package for Analog Devices®
ADALM-PLUTO Radio. For more information, see “ADALM-Pluto Radio”.
Initialization
Select Radio
Select the required radio SDRName from the availableRadios. For more information regarding
discovery of radios see findsdru and findPlutoRadio for USRP and PLUTO radios respectively.
sdrType = ;
availableRadios = helperFindRadios(sdrType);
7-141
7 Examples
SDRName = ;
SDRAddress = ;
7-142
QPSK Transmitter Using Software-Defined Radio
StopTime: 10
Note: To achieve a successful transmission, ensure that the specified center frequency of the
transmitter system objects is within the acceptable range of your respective RF cards.
Code Architecture
Initialization
The function runSDRQPSKTransmitter implements the QPSK transmitter using two System objects,
1 QPSKTransmitter for generation of transmission signal.
2 Either comm.SDRuTransmitter for USRP or comm.SDRTxPluto for ADALM-PLUTO.
QPSK Transmitter
The transmitter includes the Bit Generation, QPSK Modulator, and Raised Cosine Transmit
Filter objects. The Bit Generation object generates the data frames. The Barker code is sent on
both in-phase and quadrature components of the QPSK modulated symbols. This is achieved by
repeating the Barker code bits twice before modulating them with the QPSK modulator.
The remaining bits are the payload. The payload contains 100 'Hello world ###' messages, where
'###' is an increasing sequence of '000', '001', ... '099' in binary forms. The number of messages is
tunable via the initialization file, namely transmitter initialization file. Please make corresponding
changes in the receiver initialization file, receiver initialization file. The payload is then scrambled to
guarantee a balanced distribution of zeros and ones for the timing recovery operation in the receiver
object. The scrambled bits are modulated by the QPSK modulator (with Gray mapping). The Raised
Cosine Transmit Filter upsamples the modulated symbols by two, and has roll-off factor of 0.5. The
output rate of the Raised Cosine Filter is set to be 1 M samples per second with a symbol rate of
0.5 M symbols per second.
USRP/PLUTO Transmitter
The host computer communicates with the USRP radio using comm.SDRuTransmitter and with the
ADALM-PLUTO radio using comm.SDRTxPluto System object.
Execution
As already mentioned, you can check the correct data transmission by running the QPSK Receiver
with Software-Defined Radio example while running the transmitter script.
7-143
7 Examples
underruns = runSDRQPSKTransmitter(prmQPSKTransmitter);
fprintf('Total number of underruns = %d.\n', underruns);
Note: Before running the example, first connect the selected platform, SDRName, to the computer
and turn it on.
Troubleshooting
• The gain behavior of ADALM-PLUTO and different USRP RF cards varies considerably. Thus, the
gain setting in the transmitter and receiver defined in this example may not be well suited for your
RF cards. If the message is not properly decoded by the receiver object, you can vary the gain of
the source signals in the SDR Transmitter and SDR Receiver System objects by changing the
SDRGain value.
• A large relative frequency offset between the transmit and receive radios can prevent the receiver
functions from properly decoding the message. If that happens, you can determine the offset by
sending a tone at a known frequency from the transmitter to the receiver, then measuring the
offset between the transmitted and received frequency, then applying that offset to the center
frequency of the respective receiver System object.
Helper Functions
• helperFindRadios.m
• sdrQPSKTransmitterInit.m
• runSDRQPSKTransmitter.m
• QPSKTransmitter.m
• QPSKBitsGenerator.m
7-144