0% found this document useful (0 votes)
11 views200 pages

Plutoradio Ug

The document is a user's guide for the Communications Toolbox Support Package for Analog Devices ADALM-Pluto Radio, detailing installation, setup, and configuration procedures. It includes sections on supported hardware, installation instructions, radio configuration, and troubleshooting common issues. The guide also provides contact information for MathWorks and outlines the licensing terms for the software.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views200 pages

Plutoradio Ug

The document is a user's guide for the Communications Toolbox Support Package for Analog Devices ADALM-Pluto Radio, detailing installation, setup, and configuration procedures. It includes sections on supported hardware, installation instructions, radio configuration, and troubleshooting common issues. The guide also provides contact information for MathWorks and outlines the licensing terms for the software.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 200

Communications Toolbox™

Support Package for Analog Devices® ADALM-Pluto


Radio User's Guide

R2025a
How to Contact MathWorks

Latest news: www.mathworks.com

Sales and services: www.mathworks.com/sales_and_services

User community: www.mathworks.com/matlabcentral

Technical support: www.mathworks.com/support/contact_us

Phone: 508-647-7000

The MathWorks, Inc.


1 Apple Hill Drive
Natick, MA 01760-2098
Communications Toolbox™ Support Package for Analog Devices® ADALM-Pluto Radio User's Guide
© COPYRIGHT 2017–2025 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied
only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form
without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through
the federal government of the United States. By accepting delivery of the Program or Documentation, the government
hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer
software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014.
Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain
to and govern the use, modification, reproduction, release, performance, display, and disclosure of the Program and
Documentation by the federal government (or other entity acquiring for or through the federal government) and shall
supersede any conflicting contractual terms or conditions. If this License fails to meet the government's needs or is
inconsistent in any respect with federal procurement law, the government agrees to return the Program and
Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be
trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see www.mathworks.com/patents for
more information.
Revision History
March 2017 Online only New for Version 17.1.0 (R2017a)
May 2017 Online only Revised for Version 17.1.2 (R2017a)
September 2017 Online only Revised for Version 17.2.0 (R2017b)
November 2017 Online only Revised for Version 17.2.2 (R2017b)
March 2018 Online only Revised for Version 18.1.0 (R2018a)
September 2018 Online only Revised for Version 18.2.0 (R2018b)
October 2018 Online only Revised for Version 18.2.1 (R2018b)
March 2019 Online only Revised for Version 19.1.0 (R2019a)
July 2019 Online only Revised for Version 19.1.1 (R2019a)
September 2019 Online only Revised for Version 19.2.0 (R2019b)
March 2020 Online only Revised for Version 20.1.0 (R2020a)
September 2020 Online only Revised for Version 20.2.0 (R2020b)
March 2021 Online only Revised for Version 21.1.0 (R2021a)
August 2021 Online only Rereleased for Version 21.1.1 (R2021a)
September 2021 Online only Rereleased for Version 21.1.2 (R2021a)
September 2021 Online only Revised for Version 21.2.0 (R2021b)
March 2022 Online only Revised for Version 22.1.0 (R2022a)
September 2022 Online only Revised for Version 22.2.0 (R2022b)
March 2023 Online only Revised for Version 23.1.0 (R2023a)
September 2023 Online only Revised for Version 23.2.0 (R2023b)
March 2024 Online only Revised for Version 24.1.0 (R2024a)
September 2024 Online only Revised for Version 24.2.0 (R2024b)
March 2025 Online only Revised for Version 25.1.0 (R2025a)
Contents

Getting Started with the Communications Toolbox Support


Package for Analog Devices ADALM-Pluto Radio
1
What to Do After Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

Supported Hardware and Required Software . . . . . . . . . . . . . . . . . . . . . . . 1-3


Supported Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Operating System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Required Third-Party Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Required MathWorks Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Recommended Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3

Setup and Installation


2
Install Support Package for Analog Devices ADALM-PLUTO Radio . . . . . 2-2
Add-On Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
File Exchange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Hardware Manager App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2

Guided Host-Radio Hardware Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3


Before You Begin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Select Hardware Support Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3

Manual Host-Radio Hardware Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6


Required Hardware Checklist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Set Up Support Package in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Configure Host Computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Verify Radio Hardware Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Radio Identity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8

Setup for Two Radios Connecting to One Host . . . . . . . . . . . . . . . . . . . . . 2-10


Guided Setup for Two Radios on One Host . . . . . . . . . . . . . . . . . . . . . . . 2-10
Interacting with Two Radios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11

Uninstall Support Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13

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

DC Offset Tracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5


DC Offset Tracking on Receiver Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5
DC Offset Tracking in Receiver System Object . . . . . . . . . . . . . . . . . . . . . 3-5

Quadrature Tracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6


Tx Quadrature Tracking Calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6
Rx Quadrature Tracking Calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6

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

Repeated Waveform Transmitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5


Continuously Transmit 100 kHz Complex Tone . . . . . . . . . . . . . . . . . . . . . 4-5
Transmit and Receive on Single Device . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6

Detect Underruns and Overruns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7


Detect Lost Samples Using Transmit Block for ADALM-PLUTO radio . . . . 4-7
Detect Lost Samples Using Receive Block for ADALM-PLUTO radio . . . . . 4-7
Detect Lost Samples Using Transmitter System Object for ADALM-PLUTO
radio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8
Detect Lost Samples Using Receiver System Object for ADALM-PLUTO
radio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8

Burst Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10


Determine If You Need Burst Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10
Enable Burst Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10

Performance
5
Simulink Performance Improvements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Model Tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2

iv Contents
MATLAB Performance Improvements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Vector-Based Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3

Optimizations for Computing Environment . . . . . . . . . . . . . . . . . . . . . . . . 5-4

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

Airplane Tracking Using ADS-B Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4

Automatic Meter Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12

FM Broadcast Receiver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-18

Frequency Correction for ADALM-PLUTO Radio . . . . . . . . . . . . . . . . . . . 7-22

RDS/RBDS and RadioText Plus (RT+) FM Receiver . . . . . . . . . . . . . . . . . 7-32

Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN
Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-41

Spectrum Analysis of Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-64

Ship Tracking Using AIS Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-67

OFDM Transmitter Using Software-Defined Radio . . . . . . . . . . . . . . . . . . 7-74

OFDM Receiver Using Software Defined Radio . . . . . . . . . . . . . . . . . . . . . 7-80

Airplane Tracking Using ADS-B Signals in Simulink . . . . . . . . . . . . . . . . 7-88

v
Automatic Meter Reading in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-94

FM Broadcast Receiver in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-98

Frequency Correction for ADALM-PLUTO Radio in Simulink . . . . . . . . 7-101

QPSK Receiver with ADALM-PLUTO Radio in Simulink . . . . . . . . . . . . . 7-106

QPSK Transmitter with ADALM-PLUTO Radio in Simulink . . . . . . . . . . 7-111

RDS/RBDS and RadioText Plus (RT+) FM Receiver in Simulink . . . . . . 7-113

Spectrum Analysis of Signals in Simulink . . . . . . . . . . . . . . . . . . . . . . . . 7-123

Frequency Offset Calibration with ADALM-PLUTO Radio in Simulink 7-126

Signal Reception Using Software-Defined Radios . . . . . . . . . . . . . . . . . 7-130

QPSK Receiver Using Software-Defined Radio . . . . . . . . . . . . . . . . . . . . 7-136

QPSK Transmitter Using Software-Defined Radio . . . . . . . . . . . . . . . . . 7-141

vi Contents
1

Getting Started with the


Communications Toolbox Support
Package for Analog Devices ADALM-
Pluto Radio

• “What to Do After Installation” on page 1-2


• “Supported Hardware and Required Software” on page 1-3
1 Getting Started with the Communications Toolbox Support Package for Analog Devices ADALM-Pluto Radio

What to Do After Installation


After you have successfully installed the support package, you can do any of the following:

• 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 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.

Operating System Requirements


For MATLAB® and Simulink® operating system requirements, see https://www.mathworks.com/
support/requirements/matlab-system-requirements.html.

For operating system recommendations from Analog Devices, see https://github.com/


analogdevicesinc/libiio/wiki/releases.

Required Third-Party Software


Third-party tools required by the I/O mode features are automatically downloaded and installed
during the support package installation.

Required MathWorks Products


To use the I/O mode features of the Communications Toolbox Support Package for Analog Devices
ADALM-Pluto Radio, the following MathWorks® products are required:

• MATLAB
• Communications Toolbox

The following MathWorks products are also recommended:

• 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

Setup and Installation

• “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

Install Support Package for Analog Devices ADALM-PLUTO


Radio
You can use one of the following options to install the Communications Toolbox Support Package for
Analog Devices ADALM-Pluto Radio.

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.

Hardware Manager App


On the Apps tab in the MATLAB toolstrip, under Test and Measurement, click to open the
Hardware Manager app. Alternatively, enter hardwareManager in the MATLAB command window.
Then, follow these steps to install the support package.

1 Click Add Hardware.


2 For Hardware Type/Interface, choose Software-Defined Radios (SDR).
3 Choose ADLAM-Pluto from the Select your SDR drop down menu.
4 Click Install.

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

Guided Host-Radio Hardware Setup

Before You Begin


To implement the features in the Communications Toolbox Support Package for Analog Devices
ADALM-Pluto Radio, you must establish communication between the host and the radio hardware.

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.

Host Setup Checklist

• 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.

Radio Hardware Checklist

• ADALM-PLUTO radio
• USB communication cable
• USB power cable (optional)
• Antennas or a loopback cable

Select Hardware Support Package


On the MATLAB Home tab, in the Environment section, click Add-Ons > Manage Add-Ons.

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.

Click Next to continue.


2 Test ADALM-PLUTO Radio Connection

Click Test Connection.


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

Manual Host-Radio Hardware Setup


To implement the features in this support package, you must establish communication between the
host and the radio hardware. After the support package is installed, follow these steps to manually
configure the radio hardware and host computer.

Required Hardware Checklist


Use this list to confirm that you have the required hardware to complete the setup and configuration
process.

• ADALM-PLUTO radio
• USB communication cable
• USB power cable (optional)
• Antennas or a loopback cable

Set Up Support Package in MATLAB


To work with the support package in MATLAB, you must create a radio object for your radio
hardware. In the following example, dev is a radio object for the ADALM-PLUTO radio.

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.

See sdrdev for valid device names.

Configure Host Computer


Connect the radio hardware to the host computer using a USB cable.

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.

The PlutoSDR drive contains these files.

• 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.

For more information, see “Radio Identity” on page 2-8.

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.

Verify Radio Hardware Setup


Before you can verify the setup, you must start the radio properly. You will see failures if you do not
wait until the radio is ready (see previous step).

Check the radio connection, using the radio object you created with the sdrdev function.

dev = sdrdev('Pluto')

dev =

SDRDevPluto with properties:

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 operating on Windows keep these considerations in mind.

• 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

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');

• 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.

To change the network settings for a PlutoSDR.

• 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

Setup for Two Radios Connecting to One Host


After the support package is installed, set up the two radio hardware by using the guided setup
method.

Note The two ADALM-PLUTO radios must be set up with different radio IDs.

Guided Setup for Two Radios on One Host


The guided setup is recommended for Windows, Linux, and OS X operating systems.

• 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 operating on Windows keep these considerations in mind.

• 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

1 Clear all SDR objects.


2 Connect all radios.
3 Check to confirm that the connected radios are recognized by running this command:

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');

Interacting with Two Radios


The internal radio ID of each radio object, System object™, or block interacting with the radio
hardware must match the radio ID assigned to the radio hardware during setup.

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 operating on Windows keep these considerations in mind.

• 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

Radio System Objects

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

Uninstall Support Packages


1 On the MATLAB Home tab, in the Environment section, click Add-Ons > Manage Add-Ons.
2 In the Add-Ons panel window, locate the support package, and click Uninstall.

See Also

More About
• “Get and Manage Add-Ons”

2-13
3

Radio Configuration

• “Baseband Sampling Rate and Filter Chains” on page 3-2


• “DC Offset Tracking” on page 3-5
• “Quadrature Tracking” on page 3-6
3 Radio Configuration

Baseband Sampling Rate and Filter Chains


The AD9361/AD9364 RF chip on the ADALM-PLUTO radio hardware allows you to configure the
baseband sampling rate and the filter chains.

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

Filter Design with Blocks


Design Custom Filter

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.

In the filter wizard:

1 Update the settings to meet the requirements of your application.


2 Click Design Filter.
3 Click Apply filter design.
4 Click OK on the dialog box informing you that the design was saved to a block mask.
5 Close the filter wizard.

Default or Custom Filter Design

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.

Filter Design with System Objects


Design Custom Filter

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 Update the settings to meet the requirements of your application.


2 Click Design Filter.
3 Click Apply filter design.
4 Click OK on the dialog box informing you that the design was saved to a System object.
5 Close the filter wizard.

Save and Restore Custom Filter Design

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

% Use restored custom filter


rx = sdrrx('Pluto','UseCustomFilter',true,filtnv{:});

Default or Custom Filter Design

When applying a custom filter to a comm.SDRTxPluto or comm.SDRRxPluto System object using


the AD9361 Filter Design Wizard, the UseCustomFilter property of the object is automatically set
to true. To switch between the default and your custom filter design, set the UseCustomFilter
property to false or true, respectively.

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.

DC Offset Tracking on Receiver Block


DC offset tracking at RF and baseband is on by default. To disable these parameters, on the
Advanced tab of the Pluto Receiver block mask, clear Enable RF DC correction or Enable
baseband DC correction.

DC Offset Tracking in Receiver System Object


DC offset tracking at RF and baseband is on by default. To see these properties, set the
ShowAdvancedProperties property to true. To disable either of these properties, set the
corresponding properties to false. For example:

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.

Tx Quadrature Tracking Calibration


Quadrature tracking for the AD936x RF chipset takes place on the RF transmitter and is on always on
for the transmitter. For more information, see Tx Quadrature Calibration in [2].

Rx Quadrature Tracking Calibration


Real-only signals may cause the received signal to oscillate, so Communications Toolbox Support
Package for Analog Devices ADALM-Pluto Radio features require complex input signals regardless of
the setting for quadrature tracking.

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].

Quadrature Tracking in Receiver Block

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.

Quadrature Tracking in Receiver System Object

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

[2] Analog Devices AD9364 Reference Manual - UG-673.

3-7
4

Radio I/O

• “Channel I/O” on page 4-2


• “Repeated Waveform Transmitter” on page 4-5
• “Detect Underruns and Overruns” on page 4-7
• “Burst Mode” on page 4-10
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.

Transmit Data Using ADALM-PLUTO Radio Block


The ADALM-PLUTO radio transmitter block prepares input data for transmission using the ADALM-
PLUTO radio hardware.

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.

Receive Data Using ADALM-PLUTO Radio Block


Example

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.

Transmit Data Using ADALM-PLUTO Radio System Object


Create a transmitter System object for ADALM-PLUTO radio hardware.

tx = sdrtx('Pluto', ...
'RadioID','usb:0', ...
'CenterFrequency',2.4e9, ...
'BasebandSampleRate',1e6);

Create a comm.DPSKModulator System object to modulate the transmitted signals.

dpskMod = comm.DPSKModulator('BitInput',true);

Transmit data.

for counter = 1:20


data = randi([0 1],30,1);
modSignal=dpskMod(data);
tx(modSignal);
end

Release the System object.

release(tx);

Receive Data Using ADALM-PLUTO Radio System Object


Create a receiver System object for ADALM-PLUTO radio hardware.

rx = sdrrx('Pluto');

4-3
4 Radio I/O

Receive data.

data = rx();

Release the System object.

release(rx);

See Also

Related Examples
• “Radio Configuration”

4-4
Repeated Waveform Transmitter

Repeated Waveform Transmitter


In this section...
“Continuously Transmit 100 kHz Complex Tone” on page 4-5
“Transmit and Receive on Single Device” on page 4-6

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.

Use this feature to:

• Transmit signals such as reference signals and radio beacons.


• Provide waveforms that are continuously transmitted and do not rely on the host for further signal
generation.
• Transmit a fixed waveform at a specific rate until you explicitly stop it.
• Repeatedly transmit a signal from the hardware by using a targeted transmit bitstream.

To call the repeated waveform transmitter, use the transmitRepeat method, found on System
objects for ADALM-PLUTO radios.

Continuously Transmit 100 kHz Complex Tone


Send a complex tone of 100 kHz at a baseband sample rate of 1 MHz.

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

Stop transmitting the waveform and release the object.

release(radio);

Transmit and Receive on Single Device


You can use the transmitRepeat functionality with normal receive methods to transmit and receive
waveform data with single piece of hardware. You can develop receiver algorithms without requiring
two boards. Make sure your board is powered on, configured correctly for use with Communications
Toolbox Support Package for Analog Devices ADALM-Pluto Radio, and able to send and receive
signals.

The general workflow for this feature is:

1 Generate data for transmitting (see previous section).


2 Create your receiver design.
3 Create a transmitter System object.
4 Call the transmitRepeat method of the transmitter System object.
5 Set up antennas or loopback.
6 Run your receiver function.

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

Detect Underruns and Overruns


In this section...
“Detect Lost Samples Using Transmit Block for ADALM-PLUTO radio” on page 4-7
“Detect Lost Samples Using Receive Block for ADALM-PLUTO radio” on page 4-7
“Detect Lost Samples Using Transmitter System Object for ADALM-PLUTO radio” on page 4-8
“Detect Lost Samples Using Receiver System Object for ADALM-PLUTO radio” on page 4-8

Detect Lost Samples Using Transmit Block for ADALM-PLUTO radio


On all SDR blocks, the lost samples port is enabled by default. To disable it:

• 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:

• A 0 indicates no data samples were lost.


• A 1 indicates data samples were lost.

Detect Lost Samples Using Receive Block for ADALM-PLUTO radio


On all SDR blocks, the lost samples port is enabled by default. To disable it:

• 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:

• A 0 indicates no data samples were lost.


• A 1 indicates data samples were lost. See “Burst Mode” on page 4-10.

Detect Lost Samples Using Transmitter System Object for ADALM-


PLUTO radio
With ADALM-PLUTO radio transmitter System objects, the underflow output indicates data loss.
The following example demonstrates detecting lost samples by using an SDR transmitter System
object for ADALM-PLUTO radio.

Create a transmitter System object for the ADALM-PLUTO radio.

tx = sdrtx('Pluto')

Create transmitter data.

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

Check underflow to see if any data loss is occurring.

• A 0 indicates no data loss.


• A 1 indicates that an underflow is occurring at the transmitter.

Detect Lost Samples Using Receiver System Object for ADALM-PLUTO


radio
With ADALM-PLUTO radio receiver System objects, the overflow output indicates data loss. The
following example demonstrates detecting lost samples by using an SDR receiver System object for
ADALM-PLUTO radio.

Create a receiver System object for the ADALM-PLUTO radio.

rx = sdrrx('Pluto')

Create data to receive.

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

Check overflow to see if any data loss is occurring.

• A 0 indicates no data loss.


• A 1 indicates that an overflow is occurring at the receiver. See “Burst Mode” on page 4-10.

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.

Determine If You Need Burst Mode


It is recommended that you enable burst mode when your application requires fresh samples from the
hardware or guaranteed contiguous samples. To see if the received data is contiguous, enable the
overflow indicator on the receiver block or object.

To determine if you need burst mode, see “Detect Underruns and Overruns” on page 4-7.

Enable Burst Mode


Use burst mode when your model loses samples because it cannot keep up with the real-time data
received from the hardware. Burst mode enables you to buffer a minimum set of contiguous samples
without losing samples. However, lost samples can still happen between bursts, especially with large
burst sizes. If your model can keep up in real time, do not use burst mode. The default number of
frames in a burst is 20.

Enable Burst Mode in Receiver Block

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.

Enable Burst Mode in Receiver System Object

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

Simulink Performance Improvements


Performance improvements can help you achieve real-time execution. These adjustments suggest
ways you can improve the performance of your SDR radio model.

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

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

Optimizations for Computing Environment


To improve the performance of your ADALM-PLUTO radio, make these adjustments on your host
computer.

• Turn off antivirus and firewall software.


• Turn off all nonessential background processes on your computer.
• Use USB for radio connection.

See Also

More About
• “Simulink Performance Improvements” on page 5-2
• “MATLAB Performance Improvements” on page 5-3

5-4
6

Troubleshooting
6 Troubleshooting

Common Problems and Fixes

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.

Host Not Communicating with ADALM-PLUTO Radio


Problem

ADALM-PLUTO radio is not responding to commands or reboots randomly.

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.

If the ADALM-PLUTO radio is malfunctioning, go to https://ez.analog.com/adieducation/


university-program at Analog Devices for support.

6-2
Common Problems and Fixes

Host USB Port to ADALM-PLUTO Radio Communication Unreliable


Problem

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.

• If PlutoSDR is connected to an unpowered USB hub, switch to a powered USB hub.


• Try switching to another USB port on your computer.

Input Must Be Complex


Problem

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.

Specifically, the problem with receiving a real signal exists if:

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.

For more information, see “Quadrature Tracking” on page 3-6.

Possible Solutions

• Specify a complex signal for the transmission.

Overruns or Underruns
Problem

The model is not running in real-time.

6-3
6 Troubleshooting

Possible Solutions

• Follow the examples in “Detect Underruns and Overruns” on page 4-7.


• Try using vector-based processing, as described in “MATLAB Performance Improvements” on
page 5-3.

Firmware Version Warning


Problem

When using PlutoSDR with Communications Toolbox Support Package for Analog Devices ADALM-
Pluto Radio, you see this message:

Warning: ADALM-PLUTO radio with serial number '<serial num>' has


firmware version "0.23". The recommended firmware version is "0.26".
Click here to start the Hardware Setup App to update radio firmware
to the recommended version. To suppress this warning click here.

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

• Update to the recommended firmware version:

• 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

Hardware Setup on Windows 7 — Test ADALM-PLUTO Radio Connection


Failure
Problem

If all these conditions are true:


1 You have Windows 7 OS.
2 Both transmitter and receiver tests fail during the hardware setup process.
3 You see these errors when you call a Pluto radio object.
rx = sdrrx('Pluto');
rx()

Undefined function or variable 'internal_design_filter'.


Error in comm.libiio.AD9361.Filter.info.designDefaultFilter
Error in comm.libiio.AD9361.base/setupFIR
Error in comm.libiio.AD9361.base/initDevice
Error in comm.libiio.AD9361.Rx/setupImpl

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.

Hardware Setup on Linux — Configure ADALM-PLUTO Radio Failure

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

Use ssh to configure the frequency band, as follows:


1 Determine the IP address assign for the radio. The factory default IP address is 192.168.2.1.
Confirm the radio IP address by viewing the info.html file found in the PlutoSDR folder. The
radio appears as a USB drive named PlutoSDR when the radio is connected to the host computer.
2 At the Linux command prompt, enter the following commands (update the IP address to match
the one determined in the prior step):
ssh root@192.168.2.1
The authenticity of host '192.168.2.1 (192.168.2.1)' can't be established.
ECDSA key fingerprint is SHA256:MrvRV5EM7cdUe2bP0Vt2r4OQ5LKBc3PG08BGYMklblA.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.2.1' (ECDSA) to the list of known hosts.
root@192.168.2.1's password: [ Enter "analog" as password ]

analog

Welcome to:
______ _ _ _________________

6-5
6 Troubleshooting

| ___ \ | | | / ___| _ \ ___ \


| |_/ / |_ _| |_ ___ \ `--.| | | | |_/ /
| __/| | | | | __/ _ \ `--. \ | | | /
| | | | |_| | || (_) /\__/ / |/ /| |\ \
\_| |_|\__,_|\__\___/\____/|___/ \_| \_|

http://wiki.analog.com/university/tools/pluto

fw_setenv attr_name compatible


fw_setenv attr_val "ad9364"
pluto_reboot reset

The radio reboots and you can close ssh.

Unable to Assign IP Address Radio Identity


Problem

MATLAB returns an error when you attempt to assign an IP address RadioID:

tx = sdrdev('Pluto', 'RadioID', 'ip:192.168.2.4');

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:

ifconfig -a | grep eth[0-9]


• Map the IP address to the associated Ethernet port based on the HW address associated with host
computer. For example, if the Ethernet port is eth9 and the IP address is 192.168.2.10 use the
command:

sudo ifconfig eth9 192.168.2.10


• Attempt communicating with the ADALM-PLUTO radio, For example, if the ADALM-PLUTO radio
IP address is 192.168.2.1 use the command:

ping -c 3 192.168.2.1

ADALM-PLUTO Radio Is Busy


Problem

MATLAB returns this warning message from a call to the info method:

info(dev)

## Establishing connection to hardware. This process can take


## several seconds.

Warning: Cannot create a driver for the specified address. The address

6-6
Common Problems and Fixes

'ip: 192.168.2.1' is already owned by a block, block dialog, or System


object. Stop the simulation, close the open dialog, or call the release
method of the System object to allow a new owner to be assigned.

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:

• A Simulink simulation is in progress.


• A receiver or transmitter block is open.
• A locked receiver or transmitter System object is in memory.

Possible Solution

Release the radio hardware by stopping the simulation, closing the block, or calling the release
method of the System object.

No Data from Hardware


Problem

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:

• Check the cables and power.


• To make sure that you have a basic connection, refer to “Manual Host-Radio Hardware Setup” on
page 2-6.
• If you cannot establish communication with the host, check your radio hardware for faulty
connections or defects.

Synchronize Software and Radio Hardware

• For a radio object: Use the info method.


• For a receiver block: Open the block mask and click Info.
• For a receiver System object: Use the info method.

6-7
7

Examples
7 Examples

Capture RF Data to Baseband File Using ADALM-PLUTO Radio

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.

Configure SDR Hardware

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');

## Establishing connection to hardware. This process can take several seconds.

Configure Receiver System Object

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');

Initiate Data Capture to File

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');

## Establishing connection to hardware. This process can take several seconds.

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

fmbDemod = comm.FMBroadcastDemodulator('AudioSampleRate',48e3, ...


'SampleRate',bbr.Metadata.BasebandSampleRate,'PlaySound',true);
while ~isDone(bbr)
fmbDemod(bbr());
end

7-3
7 Examples

Airplane Tracking Using ADS-B Signals

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™.

Required Hardware and Software

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 is a type of aviation transponder interrogation mode. When an aircraft receives an


interrogation request, it sends back the squawk code of the transponder. This is referred to as Mode
3A. Mode-S (Select) is another type of interrogation mode that is designed to help avoid interrogating
the transponder too often. More details about Mode-S can be found in [ 1 ]. This mode is widely
adopted in Europe and is being phased in for North America.

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:

• A transmit frequency of 1090 MHz


• Pulse Position Modulation (PPM)
• A data rate of 1 Mbit/s
• A short squitter length of 56 microseconds
• An extended squitter length of 112 microseconds

Short squitter messages contain these fields:

• Downlink Format (DF)


• Capability (CA)
• Aircraft ID, which comprises of a unique 24-bit sequence
• CRC Checksum

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

You can specify one of these signal sources:

• ''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:

• RawBits - Raw message bits

7-6
Airplane Tracking Using ADS-B Signals

• CRCError - FALSE if CRC passes, TRUE if CRC fails


• Time - Time of reception in seconds, from the start of reception
• DF - Downlink format (packet type)
• CA - Capability

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.

Track Airplanes Using ADS-B Signals

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).

% For the option to change default settings, set |cmdlineInput| to 1.


cmdlineInput = 0;
if cmdlineInput
% Request user input from the command-line for application parameters
userInput = helperAdsbUserInput;
else
load('defaultinputsADSB.mat');
end

% Calculate ADS-B system parameters based on the user input


[adsbParam,sigSrc] = helperAdsbConfig(userInput);

% 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

% Create message parser object


msgParser = helperAdsbRxMsgParser(adsbParam);

7-7
7 Examples

% Start the viewer and initialize radio time


start(viewer)
radioTime = 0;

% 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

% Process physical layer information (Physical Layer)


[pkt,pktCnt] = helperAdsbRxPhy(rcv,radioTime,adsbParam);

% Parse message bits (Message Parser)


[msg,msgCnt] = msgParser(pkt,pktCnt);

% View results packet contents (Data Viewer)


update(viewer,msg,msgCnt,lostFlag);

% Update radio time


radioTime = radioTime + adsbParam.FrameDuration;
end

% Stop the viewer and release the signal source


stop(viewer)
release(sigSrc)

7-8
Airplane Tracking Using ADS-B Signals

This figure shows the information about the detected airplanes.

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

Automatic Meter Reading

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.

Required Hardware and Software

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:

• Transmission frequency within range: 910-920 MHz


• Data rate: 32768 bps
• On-off keyed Manchester coded signaling

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

When you run the 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);

% Calculate AMR system parameters based on the initialized parameters


[amrParam,sigSrc] = helperAMRConfig(initParam);

% Create the data viewer object


viewer = helperAMRViewer('MeterID',initParam.MeterID, ...
'LogData',initParam.LogData, ...
'LogFilename',initParam.LogFilename, ...
'Fc',amrParam.CenterFrequency, ...
'SignalSourceType',initParam.SignalSourceType);

7-13
7 Examples

start(viewer);
radioTime = 0; % Initialize the radio time

% Main Processing Loop


while radioTime < initParam.Duration
rcvdSignal = sigSrc();
amrBits = helperAMRRxPHY(rcvdSignal,amrParam);
amrMessages = helperAMRMessageParser(amrBits,amrParam);
update(viewer,amrMessages);
radioTime = radioTime + amrParam.FrameDuration;
end

stop(viewer); % Stop the viewer


release(sigSrc); % Release the signal source

Downloading captured AMR data set.


Done.

Receiver Code Structure

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

This example can use three signal sources:

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

1 Automatic meter reading, https://en.wikipedia.org/wiki/Encoder_receiver_transmitter, 2016.

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.

Required Hardware and Software

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 the “RTL-SDR Radio” support package.


• Pluto radio and the “ADALM-Pluto Radio” 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, or X3xx series radio and Wireless Testbench Support Package for NI USRP
Radios. For information on supported radios, see “Supported Radio Devices” (Wireless Testbench).

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 ].

Run the Example

To and run the example, you need to enter the following information:

1 Reception duration in seconds


2 Signal source (captured data, RTL-SDR radio, ADALM-PLUTO radio or USRP radio)
3 FM channel frequency

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.

%For the option to change default settings, set |cmdlineInput| to 1.


cmdlineInput = 0;
if cmdlineInput
% Request user input from the command-line for application parameters
userInput = helperFMUserInput;
else
load('defaultinputsFM.mat');
end

% Calculate FM system parameters based on the user input


[fmRxParams,sigSrc] = helperFMConfig(userInput);

% Create FM broadcast receiver object and configure based on user input


fmBroadcastDemod = comm.FMBroadcastDemodulator(...
'SampleRate', fmRxParams.FrontEndSampleRate, ...
'FrequencyDeviation', fmRxParams.FrequencyDeviation, ...
'FilterTimeConstant', fmRxParams.FilterTimeConstant, ...
'AudioSampleRate', fmRxParams.AudioSampleRate, ...
'Stereo', false);

% Create audio player


player = audioDeviceWriter('SampleRate',fmRxParams.AudioSampleRate);

% Initialize radio time


radioTime = 0;

% 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

% Demodulate FM broadcast signals and play the decoded audio


audioSig = fmBroadcastDemod(rcv);
player(audioSig);

% Update radio time. If there were lost samples, add those too.
radioTime = radioTime + fmRxParams.FrontEndFrameTime + ...
double(lost)/fmRxParams.FrontEndSampleRate;
end

% Release the audio and the signal source


release(sigSrc)
release(fmBroadcastDemod)
release(player)

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

Frequency Correction for ADALM-PLUTO Radio

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.

Algorithm for Estimating Frequency Correction

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

frequency in the receiver, where . The term in the


numerator is due to the mismatch in center frequencies. The scaling factor in the denominator is
due to the mismatch in baseband sample rates. Hence, we can solve for with , , and .

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

Set up the Transmitter and the Receiver

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.

% Set up parameters and signals


sampleRate = 200e3;
centerFreq = 2.42e9;
fRef = 80e3;
s1 = exp(1j*2*pi*20e3*[0:10000-1]'/sampleRate); % 20 kHz
s2 = exp(1j*2*pi*40e3*[0:10000-1]'/sampleRate); % 40 kHz
s3 = exp(1j*2*pi*fRef*[0:10000-1]'/sampleRate); % 80 kHz
s = s1 + s2 + s3;
s = 0.6*s/max(abs(s)); % Scale signal to avoid clipping in the time domain

% Set up the transmitter


% Use the default value of 0 for FrequencyCorrection, which corresponds to
% the factory-calibrated condition
tx = sdrtx('Pluto', 'RadioID', 'usb:1', 'CenterFrequency', centerFreq, ...
'BasebandSampleRate', sampleRate, 'Gain', 0, ...
'ShowAdvancedProperties', true);
% Use the info method to show the actual values of various hardware-related
% properties
txRadioInfo = info(tx)
% Send signals
disp('Send 3 tones at 20, 40, and 80 kHz');
transmitRepeat(tx, s);

% Set up the receiver


% Use the default value of 0 for FrequencyCorrection, which corresponds to
% the factory-calibrated condition
numSamples = 1024*1024;
rx = sdrrx('Pluto', 'RadioID', 'usb:0', 'CenterFrequency', centerFreq, ...
'BasebandSampleRate', sampleRate, 'SamplesPerFrame', numSamples, ...
'OutputDataType', 'double', 'ShowAdvancedProperties', true);
% Use the info method to show the actual values of various hardware-related
% properties
rxRadioInfo = info(rx)

## Establishing connection to hardware. This process can take several seconds.

txRadioInfo =

struct with fields:

Status: 'Full information'


CenterFrequency: 2.4200e+09
BasebandSampleRate: 200000
SerialNum: '10447354119600021d001f000af61ec621'
Gain: 0
RadioFirmwareVersion: "0.34"
ExpectedFirmwareVersion: "0.34"
HardwareVersion: "B1"
FrequencyCorrection: 0

Send 3 tones at 20, 40, and 80 kHz


## Establishing connection to hardware. This process can take several seconds.

7-23
7 Examples

## Waveform transmission has started successfully and will repeat indefinitely.


## Call the release method to stop the transmission.
## Establishing connection to hardware. This process can take several seconds.
Warning: ADALM-PLUTO radio with serial number
'1044734c9605001118000d00408f4fdca4' has firmware version "0.31". You can
continue using version "0.31", with the understanding that this release of the
support package was tested with version "0.34". If you experience unexpected
behavior while using version "0.31", we recommend installing version "0.34". To
switch the firmware version to "0.34", release the System object, then click <a
href="matlab:plutoradio.internal.openHSA;">here</a> to start the Hardware Setup
App.

rxRadioInfo =

struct with fields:

Status: 'Full information'


CenterFrequency: 2.4200e+09
BasebandSampleRate: 199999
SerialNum: '1044734c9605001118000d00408f4fdca4'
GainControlMode: 'AGC Slow Attack'
RadioFirmwareVersion: "0.31"
ExpectedFirmwareVersion: "0.34"
HardwareVersion: "B0"
EnableQuadratureTracking: 1
EnableRFDCTracking: 1
EnableBasebandDCTracking: 1
FrequencyCorrection: 0

Receive and Visualize Signal

disp(['Capture signal and observe the frequency offset' newline])


receivedSig = rx();

% Find the tone that corresponds to the 80 kHz transmitted tone


y = fftshift(abs(fft(receivedSig)));
[~, idx] = findpeaks(y,'MinPeakProminence',max(0.5*y));
fReceived = (max(idx)-numSamples/2-1)/numSamples*sampleRate;

% Plot the spectrum


sa = spectrumAnalyzer('SampleRate', sampleRate);
sa.Title = sprintf('Tone Expected at 80 kHz, Actually Received at %.3f kHz', ...
fReceived/1000);
receivedSig = reshape(receivedSig, [], 16); % Reshape into 16 columns
for i = 1:size(receivedSig, 2)
sa(receivedSig(:,i));
end

Capture signal and observe the frequency offset

## Establishing connection to hardware. This process can take several seconds.


Warning: ADALM-PLUTO radio with serial number
'1044734c9605001118000d00408f4fdca4' has firmware version "0.31". You can
continue using version "0.31", with the understanding that this release of the
support package was tested with version "0.34". If you experience unexpected
behavior while using version "0.31", we recommend installing version "0.34". To
switch the firmware version to "0.34", release the System object, then click <a

7-24
Frequency Correction for ADALM-PLUTO Radio

href="matlab:plutoradio.internal.openHSA;">here</a> to start the Hardware Setup


App.

Estimate and Apply the Value of FrequencyCorrection

rx.FrequencyCorrection = (fReceived - fRef) / (centerFreq + fRef) * 1e6;


msg = sprintf(['Based on the tone detected at %.3f kHz, ' ...
'FrequencyCorrection of the receiver should be set to %.4f'], ...
fReceived/1000, rx.FrequencyCorrection);
disp(msg);
rxRadioInfo = info(rx)

Based on the tone detected at 60.093 kHz, FrequencyCorrection of the receiver should be set to -8

rxRadioInfo =

struct with fields:

Status: 'Full information'


CenterFrequency: 2.4200e+09
BasebandSampleRate: 199999
SerialNum: '1044734c9605001118000d00408f4fdca4'
GainControlMode: 'AGC Slow Attack'
RadioFirmwareVersion: "0.31"
ExpectedFirmwareVersion: "0.34"
HardwareVersion: "B0"
EnableQuadratureTracking: 1

7-25
7 Examples

EnableRFDCTracking: 1
EnableBasebandDCTracking: 1
FrequencyCorrection: -8.2250

Receive and Visualize Signal

% 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

% Find the tone that corresponds to the 80 kHz transmitted tone


% fReceived2 should be very close to 80 kHz
y = fftshift(abs(fft(receivedSig)));
[~,idx] = findpeaks(y,'MinPeakProminence',max(0.5*y));
fReceived2 = (max(idx)-numSamples/2-1)/numSamples*sampleRate;

% Plot the spectrum


sa.Title = '3 Tones Received at 20, 40, and 80 kHz';
receivedSig = reshape(receivedSig, [], 16); % Reshape into 16 columns
for i = 1:size(receivedSig, 2)
sa(receivedSig(:,i));
end
msg = sprintf('Tone detected at %.3f kHz\n', fReceived2/1000);
disp(msg);

Capture signal and verify frequency correction

Tone detected at 79.916 kHz

7-26
Frequency Correction for ADALM-PLUTO Radio

Change FrequencyCorrection of the Transmitter

Now we change the FrequencyCorrection property of the transmitter to simulate the effect that the
transmitter's oscillator has drifted.

disp(['Change the FrequencyCorrection property of the transmitter to 1 to ' ...


'simulate the effect that the transmitter''s oscillator has drifted'])
tx.FrequencyCorrection = 1; % 1 ppm
txRadioInfo = info(tx)
tx.transmitRepeat(s);

Change the FrequencyCorrection property of the transmitter to 1 to simulate the effect that the t

txRadioInfo =

struct with fields:

Status: 'Full information'


CenterFrequency: 2.4200e+09
BasebandSampleRate: 200000
SerialNum: '10447354119600021d001f000af61ec621'
Gain: 0
RadioFirmwareVersion: "0.34"
ExpectedFirmwareVersion: "0.34"
HardwareVersion: "B1"
FrequencyCorrection: 1.0000

7-27
7 Examples

## Waveform transmission has started successfully and will repeat indefinitely.


## Call the release method to stop the transmission.

Receive and Visualize Signal

% 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

% Find the tone that corresponds to the 80 kHz transmitted tone


% fReceived3 will not be close to 80 kHz because tx.FrequencyCorrection
% has been changed
y = fftshift(abs(fft(receivedSig)));
[~,idx] = findpeaks(y,'MinPeakProminence',max(0.5*y));
fReceived3 = (max(idx)-numSamples/2-1)/numSamples*sampleRate;

% Plot the spectrum


sa.Title = sprintf('Tone Expected at 80 kHz, Actually Received at %.3f kHz', ...
fReceived3/1000);
receivedSig = reshape(receivedSig, [], 16); % Reshape into 16 columns
for i = 1:size(receivedSig, 2)
sa(receivedSig(:,i));
end

Capture signal and observe the frequency offset

7-28
Frequency Correction for ADALM-PLUTO Radio

Estimate and Apply the Value of FrequencyCorrection

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 =

struct with fields:

Status: 'Full information'

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

Receive and Visualize Signal

% 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

% Find the tone that corresponds to the 80 kHz transmitted tone


% fReceived4 should be very close to 80 kHz
y = fftshift(abs(fft(receivedSig)));
[~,idx] = findpeaks(y,'MinPeakProminence',max(0.5*y));
fReceived4 = (max(idx)-numSamples/2-1)/numSamples*sampleRate;

% Plot the spectrum


sa.Title = '3 Tones Received at 20, 40, and 80 kHz';
receivedSig = reshape(receivedSig, [], 16); % Reshape into 16 columns
for i = 1:size(receivedSig, 2)
sa(receivedSig(:,i));
end
msg = sprintf('Tone detected at %.3f kHz', fReceived4/1000);
disp(msg);

% Release the radios


release(tx);
release(rx);

Capture signal and verify frequency correction

Tone detected at 79.994 kHz

7-30
Frequency Correction for ADALM-PLUTO Radio

7-31
7 Examples

RDS/RBDS and RadioText Plus (RT+) FM Receiver

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.

Required Hardware and Software

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:

• Physical Layer (Layer 1)


• Data-link Layer (Layer 2)
• Session and presentation Layer (Layer 3)

Physical Layer (Layer 1)

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.

Processing steps for coherent demodulation of the RDS/RBDS signal are:

• 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.

Data-link Layer (Layer 2)

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.

Session and Presentation Layer (Layer 3)

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.

• 0A and 0B convey an 8-character string, which typically changes in a scrolling-text fashion.


• 2A and 2B convey longer 64- or 32-character strings.
• 3A registers ODAs and specifies their dedicated abstract-format group type.
• 4A conveys the system time.
• 10A further categorizes the program type, such as 'Football' for 'Sports' program type.

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).

Registering ODA Implementations: RadioText Plus (RT+)

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);

Run the Example Code

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;

[rbdsParam, sigSrc] = helperRBDSConfig(userInput);

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);

% Create audio player


player = audioDeviceWriter('SampleRate',rbdsParam.AudioSampleRate);

% 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);

% Create the data viewer object


viewer = helperRBDSViewer();

% Start the viewer and initialize radio time


start(viewer)
radioTime = 0;
% Main loop
while radioTime < rbdsParam.Duration
% Receive baseband samples (Signal Source)
rcv = sigSrc();

% Demodulate FM broadcast signals and play the decoded audio


audioSig = fmBroadcastDemod(rcv);
player(audioSig);

% Process physical layer (Layer 1)


bitsPHY = RBDSPhyDecoder(rcv, rbdsParam);

% Process data-link layer (Layer 2)


[enabled,iw1,iw2,iw3,iw4] = datalinkDecoder(bitsPHY);

% Process session and presentation layer (Layer 3)


outStruct = sessionDecoder(enabled,iw1,iw2,iw3,iw4);

7-38
RDS/RBDS and RadioText Plus (RT+) FM Receiver

% View results packet contents (Data Viewer)


update(viewer, outStruct);

% Update radio time


radioTime = radioTime + rbdsParam.FrameDuration;
end

% Stop the viewer and release the signal source and audio writer
stop(viewer);

release(sigSrc);
release(player);

Viewing Results

This window shows the processed RDS/RBDS data.

• Basic RDS/RBDS information:


• The first field contains the program type, which is conveyed by the second information word of all
group types. If 10A group types are received, the first field also provides further characterization,
such as, Sports \ Football.
• The second field contains the 8-character text conveyed by 0A/0B groups. The displayed text
wraps if the transmitted character string exceeds eight characters.
• The third field contains the longer 32/64-character text conveyed by 2A/2B group types.
• RadioText Plus (RT+): This section is populated if any 3A groups indicate that the RadioText
Plus (RT+) ODA uses an abstract-format group type, such as 11A. Upon reception of this abstract
group type, the 32/64-character text conveyed by groups 2A/2B will be split to two substrings. The
two labels will be updated to characterize the substrings (such as Artist and Song).
• Group type receptions: The tables provide a histogram displaying 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 that is not depicted in the graphical viewer (specifically, system time
in 4A, alternate frequencies in 0A etc.).

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

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

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

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.

In the following, you will:

1 Generate training signals.


2 Use a semantic segmentation network to identify 5G NR, LTE, and WLAN signals in time and
frequency. You have the choice of training a network from scratch or applying transfer learning
to a pretrained network.
3 Test the trained network with synthetic signals.
4 Use an SDR to test the network with over the air (OTA) signals.

Associated AI for Wireless Examples

Use this example as part of a complete deep learning workflow:

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.

The intended workflow of the examples above is shown in the diagram.

7-41
7 Examples

Generate Training Data

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 helperSpecSenseTrainingData function to generate training frames. This function


generates 5G NR signals using the helperSpecSenseNRSignal function, LTE signals using the
helperSpecSenseLTESignal function, and WLAN signals using helperSpecSenseWLANSignal
function.

This table lists 5G NR variable signal parameters.

This table lists LTE variable signal parameters.

This table lists WLAN variable signal parameters

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.

The helperSpecSenseTrainingData function uses the helperSpecSenseSpectrogramImage


function to create spectrogram images from complex baseband signals. Calculate the spectrograms
using an FFT length of 4096. Generate 256 by 256 RGB images. This image size allows a large
enough batch of images to fit in memory during training while providing enough resolution in time
and frequency. If your GPU does not have sufficient memory, you can resize the images to smaller
sizes or reduce the training batch size.

The trainingDataSource variable determines whether training data is to be downloaded or


generated. Choosing "Use downloaded data" downloads training data. Choosing "Generate training
data" generates the training data from scratch. Data generation may take several hours depending on

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.

You generate a set of training images for specified imageSize size.

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.

imageSize = [256 256]; % pixels


sampleRate = 61.44e6; % Hz
numSubFrames = 40; % corresponds to 40 ms
frameDuration = numSubFrames*1e-3; % seconds
trainDirRoot = fullfile(pwd,"TrainingData");
classNames = ["Noise" "NR" "LTE" "WLAN" "Unknown"];

trainingDataSource = ;

trainNow = ;

useCapturedData = ;
if trainingDataSource == "Generated data"
numFramesPerStandard = 900;
saveChannelInfo = false;
helperSpecSenseTrainingData(numFramesPerStandard,classNames,imageSize, ...
trainDirRoot,numSubFrames,sampleRate,saveChannelInfo);
end

Choose Deep Neural Network

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];

Based on selections, download training data and/or trained network.

helperSpecSenseDownloadData(trainingDataSource,trainNow,useCapturedData, ...
baseNetwork,imageSize)

Starting download of data files from:


https://www.mathworks.com/supportfiles/spc/SpectrumSensing/SpectrumSensingTrainingData256x256
Extracting files.
Extract complete.
Starting download of data files from:
https://www.mathworks.com/supportfiles/spc/SpectrumSensing/SpectrumSensingTrainedResnet18_202
Extracting files.
Extract complete.
Starting download of data files from:
https://www.mathworks.com/supportfiles/spc/SpectrumSensing/SpectrumSensingCapturedData256x256
Extracting files.
Extract complete.

Load Training Data

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");

Analyze Dataset Statistics

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.

Prepare Training, Validation, and Test Sets

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);

Train Deep Neural Network

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

Use a Pretrained Network for Transfer Learning

Apply transfer learning to a popular semantic segmentation network.

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

Design a Simple Semantic Segmentation Network

Instead of transfer learning, you can design a simple semantic segmentation network.

A common pattern in semantic segmentation networks requires the downsampling of an image


between convolutional and ReLU layers, and then upsampling the output to match the input size.
During this process, a network performs the operations using non-linear filters optimized for a
specific set of classes that you want to segment.

if strcmp(baseNetwork,"custom")
layers = helperSpecSenseCustomNetwork(imageSize,numClasses);
end

Balance Classes Using Class Weighting

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.

imageFreq = tbl.PixelCount ./ tbl.ImagePixelCount;


imageFreq(isnan(imageFreq)) = [];
classWeights = median(imageFreq) ./ imageFreq;
classWeights = classWeights/(sum(classWeights)+eps(class(classWeights)));
if length(classWeights) < numClasses
classWeights = [classWeights; zeros(numClasses - length(classWeights),1)];
end

Select Training Options

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 Deep Neural Network

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);

Running semantic segmentation network


-------------------------------------
* Processed 2294 images.

pxdsTruthLTENRWLAN = pixelLabelDatastore(dataDir,classNames,pixelLabelID,...
FileExtensions=".hdf");
metrics = evaluateSemanticSegmentation(pxdsResultsLTENRWLAN,pxdsTruthLTENRWLAN);

Evaluating semantic segmentation results


----------------------------------------
* Selected metrics: global accuracy, class accuracy, IoU, weighted IoU, BF score.
* Processed 2294 images.
* Finalizing... Done.
* Data set metrics:

GlobalAccuracy MeanAccuracy MeanIoU WeightedIoU MeanBFScore


______________ ____________ _______ ___________ ___________

0.90116 NaN 0.67109 0.82466 0.64699

Plot the normalized confusion matrix for all test frames.

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);

Replot the normalized confusion matrix.

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)

Test with captured data but exclude CF3550 frames.

imdsTestCaptured2 = subset(imdsTestCaptured,~CF3550Indices);
pxdsTestCaptured2 = subset(pxdsTestCaptured,~CF3550Indices);
pxdsResultsCaptured2 = semanticseg(imdsTestCaptured2,net,MinibatchSize=mbs,WriteLocation=tempdi
Classes=classNames);
metrics = evaluateSemanticSegmentation(pxdsResultsCaptured2,pxdsTestCaptured2);

Replot the normalized confusion matrix.

figure
cm = confusionchart(metrics.ConfusionMatrix.Variables, ...
classNames, Normalization="row-normalized");
cm.Title = "Normalized Confusion Matrix";
end

Running semantic segmentation network


-------------------------------------
* Processed 76 images.

Evaluating semantic segmentation results


----------------------------------------
* Selected metrics: global accuracy, class accuracy, IoU, weighted IoU, BF score.
* Processed 76 images.
* Finalizing... Done.
* Data set metrics:

GlobalAccuracy MeanAccuracy MeanIoU WeightedIoU MeanBFScore


______________ ____________ _______ ___________ ___________

0.98271 0.99308 0.93931 0.96778 0.89497

7-50
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals

7-51
7 Examples

Running semantic segmentation network


-------------------------------------
* Processed 66 images.

Evaluating semantic segmentation results


----------------------------------------
* Selected metrics: global accuracy, class accuracy, IoU, weighted IoU, BF score.
* Processed 66 images.
* Finalizing... Done.
* Data set metrics:

GlobalAccuracy MeanAccuracy MeanIoU WeightedIoU MeanBFScore


______________ ____________ _______ ___________ ___________

0.98404 0.99344 0.95623 0.97037 0.89122

7-52
Spectrum Sensing with Deep Learning to Identify 5G, LTE, and WLAN Signals

The NR detection rate increases to more than 99%.

Identify 5G NR and LTE Signals in Spectrogram

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 with Captured Data using SDR

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.

Skipping SDR test.

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;

meanAllScores = zeros([imageSize numel(classNames)]);


segResults = zeros([imageSize 10]);
for frameCnt=1:10
rxWave = rx();
rxSpectrogram = helperSpecSenseSpectrogramImage(rxWave,Nfft,sampleRate,imageSize);

[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

Conclusions and Further Exploration

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

function net = loadNetworkFromMATFile(baselineNetwork)


switch baselineNetwork
case "custom"
net = load("specSenseTrainedNetCustom.mat",'net');
case "resnet18"
net = load("specSenseTrainedNetResnet18.mat",'net');
case "resnet50"
net = load("specSenseTrainedNetResnet50.mat",'net');
case "mobilenetv2"
net = load("specSenseTrainedNetMobileNetv2.mat",'net');
otherwise
error("Unknown baseline network: " + baselineNetwork)
end
net = net.net;
end

function loss = lossFunction(ypred,yactual,weights)


% Compute weighted cross-entropy loss.
cdim = find(dims(ypred) == 'C');
loss = crossentropy(ypred,yactual,weights,WeightsFormat="C",NormalizationFactor="none");
wn = shiftdim(weights(:)',-(cdim-2));
wnT = extractdata(yactual).*wn;
normFac = sum(wnT(:))+eps('single');
loss = loss/normFac;
end

7-63
7 Examples

Spectrum Analysis of Signals

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”.

Required Hardware and Software

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.

For the option to change default settings, set |cmdlineInput| to 1.

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

Create spectrumAnalyzer object and configure based on user input

hSpectrum = spectrumAnalyzer(...
'Name', 'Passband Spectrum',...
'Title', 'Passband Spectrum', ...
'Method', 'Welch', ...
'SpectrumType', 'Power density', ...
'FrequencySpan', 'Full', ...

7-64
Spectrum Analysis of Signals

'SampleRate', SAParams.FrontEndSampleRate, ...


'FrequencyOffset', SAParams.CenterFrequency, ...
'YLimits', [-120 10], ...
'YLabel', 'Magnitude-squared, dB', ...
'Position', figposition([50 30 30 40]));

Stream processing

View the spectrum. While the spectrum analyzer is running, you can measure peaks, occupied
bandwidth, and other properties of the signal.

% Initialize radio time


radioTime = 0;

% 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

rcv = rcv - mean(rcv); % Remove DC component.


step(hSpectrum, rcv);

% Update radio time. If there were lost samples, add those too.
radioTime = radioTime + SAParams.FrontEndFrameTime + ...
double(lost)/SAParams.FrontEndSampleRate;
end

% Release all System objects


release(sigSrc);
release(hSpectrum);

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

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™.

Required Hardware and Software

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:

• Transmit vessel identifier, position, course, and speed.


• Receive and process specified interrogating calls.
• Operate continuously while sailing or at anchor.

AIS has these attributes:

• A transmit frequency in the range 156.025 MHz-162.025 MHz


• Gaussian minimum shift keying modulation
• A bit rate of 9600 bits/sec
• A transmit bandwidth-time product of 0.4
• A receive bandwidth-time product of 0.5
• A modulation index of 0.5

AIS transmission packets contain these fields:

• Training Sequence — 24-bit sequence of alternating zeros and ones (0101...)


• Start Flag — 8-bit sequence, 01111110
• Data — The data portion is 168 bits long in the default transmission packet
• Frame Check Sequence (FCS) — Uses the cyclic redundancy check (CRC) 16-bit polynomial to
calculate the checksum
• End Flag — Identical to the start flag
• Buffer — 24 bits long to account for bit stuffing (maximum 4 bits), distance delay (14 bits), and
synchronization jitter (6 bits)

This figure shows the AIS packet format

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

Specify the signal source as one of these values

• ''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

Track Ships Using AIS Signals

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);

% Launch map based on user input


if userInput.LaunchMap
startMapUpdate(viewer);
end

% Log data based on user input


if userInput.LogData
startDataLog(viewer);
end

% Start the viewer and initialize radio time


start(viewer)
radioTime = 0;

% Main loop for capturing and decoding the AIS samples


while radioTime < userInput.Duration
if aisParam.isSourceRadio
if aisParam.isSourceRTLSDRRadio % For RTL-SDR
[rcv,~,lost,~] = sigSrc();
lostFlag = logical(lost);
elseif aisParam.isSourcePlutoSDRRadio % For ADALM-PLUTO
[rcv,~,lostFlag] = sigSrc();
elseif aisParam.isSourceUSRPRadio % For USRP
[rcv,~,lostFlag] = sigSrc();
end
else % For baseband file
rcv = sigSrc();
lostFlag = uint32(0);
end

% Recover the information by decoding AIS samples


[info, pkt] = helperAISRxPhy(rcv,aisParam);

7-70
Ship Tracking Using AIS Signals

% View decoded information on viewer


update(viewer, info, pkt, lostFlag);

% Update radio time


radioTime = radioTime + aisParam.FrameDuration;
end

% Stop the viewer and release the signal source


stop(viewer)

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

[1] Recommendation ITU-R M.1371-5. "Technical characteristics for an automatic identification


system using time division multiple access in the VHF maritime mobile frequency band",
International Telecommunication Union. https://www.itu.int/rec/R-REC-M.1371-5-201402-I/en

7-73
7 Examples

OFDM Transmitter Using Software-Defined Radio

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.

Required Hardware and Software

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 OFDM Frame Parameters

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

dataParams.modOrder = ; % Data modulation order

dataParams.coderate = ; % Code rate

7-74
OFDM Transmitter Using Software-Defined Radio

dataParams.numSymPerFrame = ; % Number of data symbols per frame 20 for se

dataParams.numFrames = ; % Number of frames to transmit

dataParams.enableScopes = ; % Switch to enable or disable the visibility

dataParams.verbosity = ; % Switch to enable or disable the data diagno

Initialize Transmitter Parameters

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.

radioDevice = ; % Choose the radio device for transmission

centerFrequency = ; % Center Frequency

gain = ; % Set radio gain

The helperOFDMSetParamsSDR function initializes transmit-specific and common transmitter/


receiver parameters required for the OFDM simulation and the helperGetRadioParams function
initializes the parameters required for the transmitter System object™ radio.

[sysParam,txParam,trBlk] = helperOFDMSetParamsSDR(OFDMParams,dataParams);
sampleRate = sysParam.scs*sysParam.FFTLen; % Sample rate of signal
ofdmTx = helperGetRadioParams(sysParam,radioDevice,sampleRate,centerFrequency,g

Checking radio connections...


Win32; Microsoft Visual C++ version 1936; Boost_108100; UHD_4.6.0.0-vendor

---------- see libuhd version information above this line ----------

% Get the radio transmitter and spectrum analyzer system object system object for the user to vis
[radio,spectrumAnalyze] = helperGetRadioTxObj(ofdmTx);

Generate Transmitter Waveform

Transmit Frame Structure

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.

Synchronization Symbol (SS)

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

Reference Symbol (RS)

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.

DC and Guard Subcarriers

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

tunderrun = 0; % Initialize count for underruns

% A known payload is generated in the function helperOFDMSetParams with


% respect to the calculated trBlkSize
% Store data bits for BER calculations
txParam.txDataBits = trBlk;
[txOut,txGrid,txDiagnostics] = helperOFDMTx(txParam,sysParam,txObj);

% Display the grid if verbosity flag is enabled


if dataParams.verbosity
helperOFDMPlotResourceGrid(txGrid,sysParam);
end

% 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

Transmit Over Radio

for frameNum = 1:sysParam.numFrames+1


underrun = radio(txWaveform);
tunderrun = tunderrun + underrun; % Total underruns
end
% Clean up the radio System object
release(radio);

Further Exploration

You can modify the initialization parameters in the helperOFDMSetParamsSDR and


helperOFDMTxInit functions. Similarly, you can modify helperOFDMPilotSignal,
helperOFDMRefSignal, and helperOFDMSyncSignal helper functions to generate custom pilot,
reference and synchronization signals respectively.

7-79
7 Examples

OFDM Receiver Using Software Defined Radio

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.

Required Hardware and Software

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 OFDM Frame Parameters

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

% 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

dataParams.modOrder = ; % Data modulation order

dataParams.coderate = ; % Code rate

dataParams.numSymPerFrame = ; % Number of data symbols per frame

dataParams.numFrames = ; % Number of frames to transmit

7-80
OFDM Receiver Using Software Defined Radio

dataParams.enableScopes = ; % Switch to enable or disable the visibility

dataParams.verbosity = ; % Control to print the output diagnostics at

dataParams.printData = ; % Control to print the output decoded data

Initialize Receiver Parameters

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.

The helperGetRadioRxObj function initializes the radio receiver System object.

radioDevice = ; % Choose radio device for reception

centerFrequency = ; % Center Frequency

gain = ; % Set radio gain

The helperOFDMSetParamsSDR function initializes transmit-specific and common transmitter and


receiver parameters required for the OFDM simulation and the helperGetRadioParams function
initializes the parameters required for the receiver System object™ radio.

[sysParam,txParam,transportBlk] = helperOFDMSetParamsSDR(OFDMParams,dataParams);
sampleRate = sysParam.scs*sysParam.FFTLen; % Sample rate of

ofdmRx = helperGetRadioParams(sysParam,radioDevice,sampleRate,centerFrequency,gain);

Checking radio connections...

[radio,spectrumAnalyze,constDiag] = helperGetRadioRxObj(ofdmRx);

Execute Receiver Loop

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.

Frequency Offset Estimation and Correction

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.

Channel Estimation and Equalization

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();

toverflow = toverflow + overflow;

% Run the receiver front-end only when there is no overflow


if ~overflow
rxIn = helperOFDMRxFrontEnd(rxWaveform,sysParam,rxObj);

% Run the receiver processing


[rxDataBits,isConnected,toff,rxDiagnostics] = helperOFDMRx(rxIn,sysParam,rxObj);
sysParam.timingAdvance = toff;

% Collect bit and frame error statistics


if isConnected
% Continuously update the bit error rate using the |comm.ErrorRate|
% System object
berVals = errorRate(...
transportBlk((1:sysParam.trBlkSize)).', ...

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 isConnected && dataParams.enableScopes


constDiag(complex(rxDiagnostics.rxConstellationHeader(:)), ...
complex(rxDiagnostics.rxConstellationData(:)));
end

if dataParams.enableScopes
spectrumAnalyze(rxWaveform);
end
end
end

Sync symbol found.


Estimating carrier frequency offset ........
Receiver camped.
..................

7-84
OFDM Receiver Using Software Defined Radio

7-85
7 Examples

% Display the mean BER value across all frames


fprintf('Simulation complete!\nAverage BER = %d',mean(BER))

Simulation complete!
Average BER = 0

release(radio);

Troubleshooting

No data in any frame

Problem

• The receiver continuously receives no data in any frame.

Possible causes

• Transmitter is not running


• Too high or too low transmitter and receiver gains
• Too many under-runs at the transmitter

Possible solutions

• Ensure that the transmitter is running

7-86
OFDM Receiver Using Software Defined Radio

• Adjust the transmitter and receiver gains


• Adjust the frame length to make sure there are very few under-runs at the transmitter.

Header CRC fails

Problem

• Even when synchronization and receiver camping are successful, the header CRC check fails.

Possible causes

• Insufficient compensation of clock frequency offset.

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.

Data decoding fails

Problem

• The data decoding fails even when the header CRC decoding is successful.

Possible causes

• Data overflow at the receiver


• Inaccurate channel estimate due to exceeding frame length.

Possible solutions

• Adjust the frame size


• Change the number of symbols per frame to minimize the frame length.

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

Airplane Tracking Using ADS-B Signals in Simulink

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™.

Required Hardware and Software

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

You can specify one of these signal sources:

• ''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:

• RawBits - Raw message bits


• CRCError - FALSE if CRC passes, TRUE if CRC fails
• Time - Time of reception in seconds, from the start of reception
• DF - Downlink format (packet type)
• CA - Capability

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.

Launch Map and Log Data

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

Automatic Meter Reading in Simulink

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.

Required Hardware and Software

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®.

Receiver Model Structure

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

This example can use three signal sources:

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

1 Automatic meter reading, https://en.wikipedia.org/wiki/Encoder_receiver_transmitter, 2016.

7-97
7 Examples

FM Broadcast Receiver in Simulink

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.

Required Hardware and Software

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 the “RTL-SDR Radio” support package.


• Pluto radio and the “ADALM-Pluto Radio” 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, 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 to the FM broadcasting technology and demodulation of these signals, refer to
the “FM Broadcast Receiver” example.

Running the 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

This example can use three signal sources:

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.

Audio Device Writer

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

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.

Algorithm for Estimating Frequency Correction

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

frequency in the receiver, where . The term in the


numerator is due to the mismatch in center frequencies. The scaling factor in the denominator is
due to the mismatch in baseband sample rates. Hence, we can solve for with , , and .

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

Set up the Transmitter and the Receiver

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.

% Set up parameters and signals


sampleRate = 200e3;
centerFreq = 2.42e9;
fRef = 80e3;
s1 = exp(1j*2*pi*20e3*[0:10000-1]'/sampleRate); % 20 kHz
s2 = exp(1j*2*pi*40e3*[0:10000-1]'/sampleRate); % 40 kHz
s3 = exp(1j*2*pi*fRef*[0:10000-1]'/sampleRate); % 80 kHz
s = s1 + s2 + s3;
s = 0.6*s/max(abs(s)); % Scale signal to avoid clipping in the time domain

% Set up the transmitter


% Use the default value of 0 for FrequencyCorrection, which corresponds to
% the factory-calibrated condition
tx = sdrtx('Pluto', 'RadioID', 'usb:1', 'CenterFrequency', centerFreq, ...
'BasebandSampleRate', sampleRate, 'Gain', 0, ...
'ShowAdvancedProperties', true);
% Use the info method to show the actual values of various hardware-related
% properties
txRadioInfo = info(tx)
% Send signals
disp('Send 3 tones at 20, 40, and 80 kHz');
transmitRepeat(tx, s);

% Open the receiver model


open_system('plutoradioFrequencyCorrectionRx')

% 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.']);

## Establishing connection to hardware. This process can take several seconds.

txRadioInfo =

struct with fields:

Status: 'Full information'


CenterFrequency: 2.4200e+09
BasebandSampleRate: 200000
SerialNum: '1000002355237309002300260902167028'
Gain: 0
RadioFirmwareVersion: "0.30"
ExpectedFirmwareVersion: "0.30"
HardwareVersion: "A0"
FrequencyCorrection: 0

Send 3 tones at 20, 40, and 80 kHz


## Establishing connection to hardware. This process can take several seconds.
## Waveform transmission has started successfully and will repeat indefinitely.
## Call the release method to stop the transmission.
Running the receiver...

7-102
Frequency Correction for ADALM-PLUTO Radio in Simulink

## Establishing connection to hardware. This process can take several seconds.


The detected frequency is 68.0386 kHz.

7-103
7 Examples

Estimate the Frequency Correction Value


additionalCorrection = (peakFreq - fRef) / (centerFreq + fRef) * 1e6;

Apply the Frequency Correction Value

Since , applying two changes and


successively is equivalent to applying a single change of with respect to
the factory-calibrated condition.
currentFrequencyCorrection = str2double( ...
get_param('plutoradioFrequencyCorrectionRx/ADALM-Pluto Radio Receiver', ...
'FrequencyCorrection'))

newFrequencyCorrection = currentFrequencyCorrection + additionalCorrection + ...


currentFrequencyCorrection*additionalCorrection*1e-6

set_param('plutoradioFrequencyCorrectionRx/ADALM-Pluto Radio Receiver', ...


'FrequencyCorrection',num2str(newFrequencyCorrection,'%.12f'))

currentFrequencyCorrection =

7-104
Frequency Correction for ADALM-PLUTO Radio in Simulink

newFrequencyCorrection =

-4.9426

Verify the Results

Run the receiver again. The detected frequency should be closer to 80 kHz.

disp('Running the receiver again...');


sim('plutoradioFrequencyCorrectionRx')
disp(['The detected frequency is ' num2str(peakFreq/1000) ' kHz.']);

% Release the transmitter radio


release(tx);

Running the receiver again...


## Establishing connection to hardware. This process can take several seconds.
The detected frequency is 80.04 kHz.

7-105
7 Examples

QPSK Receiver with ADALM-PLUTO Radio in Simulink

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.

Structure of the Example

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

The components are further described in the following sections.

• AGC - Automatic gain control


• Raised Cosine Receive Filterring - Uses a rolloff factor of 0.5
• Coarse Frequency Compensation - Estimates an approximate frequency offset of the received
signal and corrects it
• Symbol Synchronization - Resamples the input signal according to a recovered timing strobe so
that symbol decisions are made at the optimum sampling instants
• Carrier Synchronization - Compensates for the residual frequency offset and the phase offset
• Frame Synchronization - Detects location of the frame header and aligns the frame boundaries
at the known frame header
• Decode Data - Resolves the phase ambiguity caused by the Carrier Synchronizer, demodulates
the signal, and decodes the text message

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.

Raised Cosine Receive Filtering

The Raised Cosine Receive Filter provides matched filtering for the transmitted waveform with a
rolloff factor of 0.5.

Coarse Frequency Compensation

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.

Running the Example

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.

Exploring the Example

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

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.

Structure of the Example

The top-level structure of the model is shown in the following figure:

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

Running the Example

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.

Exploring the Example

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

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.

Required Hardware and Software

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:

• Physical layer (Layer 1)


• Data-link layer (Layer 2)
• Session and presentation layer (Layer 3)

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

Physical Layer (Layer 1)

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 ].

Processing steps for coherent demodulation of the RDS/RBDS signal are:

• 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.

Data-link Layer (Layer 2)

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 ].

Session and Presentation Layer (Layer 3)

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.

• 0A and 0B convey an 8-character string, which typically changes in a scrolling-text fashion.


• 2A and 2B convey longer 64- or 32-character strings.
• 3A registers ODAs and specifies their dedicated abstract-format group type.
• 4A conveys the system time.
• 10A further categorizes the program type, such as 'Football' for 'Sports' program type).

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

• Basic RDS/RBDS information:

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

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.

Required Hardware and Software

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:

• A view of the spur-free dynamic range of the receiver


• A view of the qualitative SNR level of the received signal

Structure of the Example

This figure shows the spectralAnalysis model:

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

Running the Example

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

Frequency Offset Calibration with ADALM-PLUTO Radio in


Simulink

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:

• The quantitative value of the frequency offset


• A graphical view of the spur-free dynamic range of the receiver
• A graphical view of the qualitative SNR level of the received signal

Structure of the Example

The following figure shows the transmitter model:

The following figure shows the receiver model:

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

Find Peak Frequency

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

Foffset = IndexofMaxAmplitude * FrameSize / (FFTLength * FrameSampleTime)

The MATLAB function findpeakfreq.m performs this conversion.

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

Running the Example

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

Signal Reception Using Software-Defined Radios

This example shows how to tune software-defined radios (SDRs) to receive signals using the SDR
Receiver app. In this example, you:

1 Configure SDRs for continuous signal reception.


2 Visualize the IQ samples, power spectrum, and constellation.
3 Correct RF impairments.
4 Export app configuration to MATLAB™ script.

Required Hardware and Software

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.

While using SDRs, you encounter these problems:

• Obtaining correct gain values.


• Identifying correct phase and frequency offset values.

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.

Configure Signal Parameters


Configure SDR Reception Controls

Open SDR Receiver App

Run this command to open 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.

Configure Signal Parameters

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:

• The app disables the Select SDR.


• The app shows the status of reception as Receiving [Total Overruns = <Count of overruns>].
It resets overrun count to 0 before 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.

Visualize Received Signal

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

Export To MATLAB Script: Click on Export To MATLAB Script button to generate MATLAB script
for the current SDR Receiver app configuration.

Close the App

Close the opened SDR Receiver app by closing the window or by using this

app.delete();

7-134
Signal Reception Using Software-Defined Radios

Conclusion and Further Exploration

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:

• QPSK Transmitter with Software-Defined Radios.


• QPSK Receiver with Software-Defined Radios.
• Spectrum Analysis of Signals.
• FM Broadcast Receiver.

References

[1] SDR (Software Defined Radio)

Helper Functions

• SDRReceiver.m
• helperUISDRRxWidgets.m
• helperUISDRRxController.m

7-135
7 Examples

QPSK Receiver Using Software-Defined Radio

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.

This example has the following motivation:

• To implement a real QPSK-based transmission-reception environment in MATLAB using System


objects.
• To illustrate the use of key Communications Toolbox™ System objects for QPSK system design,
including coarse and fine carrier frequency compensation, timing recovery, frame synchronization,
carrier phase ambiguity resolution, and message decoding.

Required Hardware and Software

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

Checking radio connections ...

SDRName SDRType SDRAddress


_______ _______ __________

"B210" "USRP" "30F597A"

SDRName = ;

SDRAddress = ;

Run clear all whenever the SDR is modified.

Initialize Receiver Parameters

The sdrQPSKReceiverInit.m script initializes the simulation parameters and generates the
structure prmQPSKReceiver.

QPSK Receiver Parameters

sampleRate = ;

isHDLCompatible = ; % disable to run 'FFT-Based' coarse frequency compensation instead of

SDR Parameters

SDRGain = ;

SDRCenterFrequency = ;

SDRStopTime = ;

Display received data

previewReceivedData = ; % enable to preview the received data

printReceivedData = ; % enable to print the received data

Receiver parameter structure

prmQPSKReceiver = sdrQPSKReceiverInit(SDRName, SDRAddress, sampleRate, SDRCenterFrequency, ...


SDRGain, SDRStopTime, isHDLCompatible);

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.

Execution and Results

To ensure data reception, first start the QPSK Transmitter with Software-Defined Radio example.

[BER, overflow, output] = runSDRQPSKReceiver(prmQPSKReceiver, previewReceivedData, printReceivedD

Hello world 000


Hello world 001
Hello world 002
Hello world 003
Hello world 004
Hello world 005
...
...
Show all messages

fprintf('Error rate is = %f.\n', BER(1));

Error rate is = 0.000091.

fprintf('Number of detected errors = %d.\n', BER(2));

Number of detected errors = 622.

fprintf('Total number of compared samples = %d.\n', BER(3));

Total number of compared samples = 6845300.

fprintf('Total number of overflows = %d.\n', overflow);

Total number of overflows = 1.

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

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.

Required Hardware and Software

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);

Checking radio connections ...

SDRName SDRType SDRAddress


_______ _______ __________

"B210" "USRP" "30F597A"


"B200" "USRP" "F5BC9E"

7-141
7 Examples

SDRName = ;

SDRAddress = ;

Run clear all whenever the SDR is modified.

Initialize Transmitter Parameters

sdrQPSKTransmitterInit.m script initializes the simulation parameters and generates the


structure prmQPSKTransmitter.

sampleRate = ; % Sample rate of transmitted signal

SDRGain = ; % Set radio gain

SDRCenterFrequency = ; % Set radio center frequency

SDRStopTime = ; % Radio transmit time in seconds

% Transmitter parameter structure


prmQPSKTransmitter = sdrQPSKTransmitterInit(SDRName, SDRAddress, sampleRate, SDRCenterFrequency,
SDRGain, SDRStopTime)

prmQPSKTransmitter = struct with fields:


ModulationOrder: 4
Interpolation: 2
Decimation: 1
Fs: 1000000
Rsym: 500000
Tsym: 2.0000e-06
BarkerCode: [1 1 1 1 1 -1 -1 1 1 -1 1 -1 1]
BarkerLength: 13
HeaderLength: 26
Message: 'Hello world'
MessageLength: 16
NumberOfMessage: 100
PayloadLength: 11200
FrameSize: 5613
FrameTime: 0.0112
RolloffFactor: 0.5000
ScramblerBase: 2
ScramblerPolynomial: [1 1 1 0 1]
ScramblerInitialConditions: [0 0 0 0]
RaisedCosineFilterSpan: 10
MessageBits: [11200×1 double]
Platform: "B200"
Address: 'F5BC9E'
IsPluto: 0
MasterClockRate: 20000000
USRPCenterFrequency: 915000000
USRPGain: 35
USRPFrontEndSampleRate: 1000000
USRPInterpolationFactor: 20
USRPFrameLength: 11226
SDRFrameTime: 0.0112

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);

Total number of underruns = 0.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy