Main Content

Tone Transmitter on NI USRP Radio

R2026b
Since R2026b

This example shows how to convert a tone generation algorithm into a streaming transmit design that is deployable on the FPGA of an NI™ USRP™ radio. A Data Packager block handles packetization and buffering and you simulate the streaming behavior using a Radio Simulator block before generating the bitstream. To verify the transmission, you capture the signal on a receive antenna and analyze the output frequency.

Workflow

In this example, you follow a step-by-step guide to generate a custom FPGA image from a Simulink® model and deploy it on an NI USRP radio by using a generated MATLAB® host interface script.

For more information about how to prototype and deploy software-defined radio (SDR) algorithms on the FPGA of an NI USRP radio, see Target NI USRP Radios Workflow.

Design Overview

The example uses a tone generation algorithm that generates a configurable-frequency complex sinusoid on the FPGA and transmits it through a radio antenna. The design includes a numerically controlled oscillator (NCO) block for tone generation and a Data Packager block that formats the output data into packets for the radio streaming interface. To verify the transmitted tone, use a second antenna on the same radio to capture the over-the-air signal so you can analyze the output frequency on the host. For more information about how to configure antennas on your radio, see Supported Radio Devices.

This design demonstrates the recommended pattern for streaming transmit pipelines:

  • Provide samples from your algorithm.

  • Allow the Data Packager to handle packetization and backpressure buffering.

You can replace the NCO tone generator with any signal processing algorithm while keeping the Data Packager and streaming interface unchanged.

Requirements

To target NI USRP radio devices with Wireless Testbench™, you must install and configure third-party tools and additional support packages.

For details about which NI USRP radios you can target, see Supported Radio Devices.

Note

  • You cannot use this example with a USRP X310 radio with TwinRX daughterboards. The design in this example requires a transmit path.

  • This workflow supports generating bitstreams only on a Linux® operating system (OS). For details about host system requirements, see System Requirements.

For details about how to install and configure additional support packages and third-party tools, see Installation for Targeting NI USRP Radios.

Set Up Environment and Radio

Set up a working directory for running the example by using the openExample function in MATLAB. This function downloads the example files into a subfolder of the Examples folder in the currently running release and then opens the example. If a copy of the example exists, openExample opens the existing version of the example.

openExample("wt/ToneTransmitterOnNIUSRPRadioExample")

The working directory contains all the files you need to use this example, including helper functions and supporting files. The files you interact with are:

  • wtToneTransmitterUSRPTargetingSL.slx — The Simulink hardware generation model. The DUT subsystem implements a tone generation algorithm using an NCO. The Data Packager block handles AXI-Stream packetization and buffering.

  • ToneTransmitterOnNIUSRPRadioExample.m — The MATLAB script that simulates the behavior of the Simulink model before you generate HDL code.

  • VerifyToneTransmitterUsingMATLABExample.m — The live script that you use in MATLAB to verify the algorithm running on your radio.

To program the FPGA on your radio with the bitstream that you generate in this example, and to verify the algorithm running on your radio, use the Radio Setup wizard to connect and set up your radio.

Simulink Hardware Generation Model

The Simulink model in this example is a hardware generation model of a tone transmitter for NI USRP radio devices. Using the HDL Code tab in the Simulink Toolstrip or the HDL Workflow Advisor, you can generate a custom HDL IP core from the model, then generate a bitstream and load it onto the FPGA on your radio. You can then generate a host interface script that provides the MATLAB code you need to interact with the hardware.

The model implements a simple tone transmitter using helper library blocks. The Data Packager and Radio Simulator blocks handle packetization and flow control and validate your design against overflow and underflow conditions before deploying to hardware.

Library Blocks for Data Packetization and Verification

RF network on chip (RFNoC) is the FPGA data streaming architecture used on NI USRP radios. Understanding the RFNoC packet format helps you design DUT logic that produces correctly formatted data for the radio hardware.

When transmitting data to an NI USRP radio, the FPGA design must produce data packets that conform to the AXI-Stream protocol used by the RFNoC framework. The radio consumes these packets at a rate determined by its master clock rate (MCR). If the DUT produces data faster than the radio can consume it, an overflow occurs. If the DUT fails to supply data in time, an underflow occurs.

This example uses two library blocks from the targetingLib library to address these challenges:

  • Data Packager - Formats streams of data and valid signals into AXI-Stream packets that comply with the AXI4-Stream protocol.

  • Radio Simulator - Simulates the NI USRP radio TX interface behavior in Simulink so that you can detect overflows or underflows before deploying to hardware.

You can find the location of the targeting library by using this MATLAB command:

>> which targetingLib

Transmitter Model Structure

To view the model structure, open the Simulink model.

modelname = 'wtToneTransmitterUSRPTargetingSL';
open_system(modelname);

The top-level model includes these components:

  • The ToneTransmitter subsystem implements the tone generation and data packetization algorithm. This subsystem is the device under test (DUT).

  • The Radio Simulator block simulates the NI USRP TX interface. It consumes the AXI-Stream packets produced by the DUT at a representative rate and reports overflow and underflow conditions.

  • The Scope block displays the DUT output data during simulation.

  • Two Enabled Subsystem blocks capture the radio output stream and the DUT output stream to workspace variables for post-simulation analysis.

Open the ToneTransmitter subsystem.

open_system([modelname '/ToneTransmitter']);

The ToneTransmitter subsystem contains these components:

  • The NCO block generates a fixed-frequency complex tone. The block uses a 16-bit accumulator and 16-bit output word length. The frequency increment value is provided through the inc input port. In this model, the increment is set to 200.

  • The DataPackager subsystem converts NCO output into AXI-Stream packets using the Data Packager library block.

  • The valid_eob_sync MATLAB Function block synchronizes the end-of-burst (EoB) signal with the data valid signal, ensuring the EoB arrives on a clock cycle when valid data is present. For more information, see Streaming Interface Guidelines.

  • A Logical Operator AND gate combines the external validIn signal with the readyOutput backpressure signal from the Data Packager block. This gates the NCO so that it only advances when the downstream path is ready to accept data.

The data flow through the ToneTransmitter subsystem is:

  1. The validIn signal is ANDed with the Data Packager block readyOutput signal. The output signal is the enable for the NCO.

  2. The NCO generates one complex sample per enabled clock cycle.

  3. The NCO data and valid signals feed into the DataPackager subsystem.

  4. The DataPackager formats the data into AXI-Stream packets of length 256 samples, which is the recommended packet size.

  5. The packetized output (dataOut, validOut, lastOut, EoBOut) connects to the Radio Simulator block at the top level.

Format Data into AXI-Stream Packets

To correctly packetize your DUT output, use the Data Packager library block. This section explains the block interface and configuration so you can integrate it into your own design.

The Data Packager block converts generic data-and-valid signal pairs into packets that conform to the AXI-Stream protocol required by the NI USRP radio device. This block is provided in the targetingLib.slx library. Without the Data Packager block, you must manually generate the last signal at the end of every packet and handle end-of-burst alignment. Incorrect packetization can cause zero output or data corruption.

To examine the packetization logic, open the DataPackager subsystem.

open_system([modelname '/ToneTransmitter/DataPackager']);

The Data Packager block dialog exposes these configurable mask parameters:

  • BufferDepth - Depth of the internal FIFO buffer, specified as a power of 2. In this model, the buffer depth is 10, or 2^10 entries, which is 1024. A larger buffer absorbs more timing variation between data production and consumption. When the downstream consumer deasserts readyIn, the block buffers incoming valid data in this FIFO.

  • SPP (Samples Per Packet) - The number of samples in each output AXI-Stream packet. The valid range is 256 to 1024. The recommended value is 256. The block generates a TLAST signal every SPP valid output samples automatically.

  • Mode - Select the operating mode. In Continuous mode, the block transmits data continuously until EoBIn is asserted. Use this mode for streaming applications where data flows indefinitely. In Burst mode, the block transmits a fixed number of data samples, specified by the burstNum input port, and then asserts an EoB signal at the end of the packet. Use this mode for finite-length transmissions.

  • HasTime - Enable timestamp output. When enabled, the timestamp is sent with the first packet of each burst. In this example, set to off.

The input ports of the Data Packager block are:

  • enb - Enables the packetizer.

  • rst - Active-high synchronous reset. Resets the Data Packager block to its IDLE state.

  • dataIn - Input data samples. In this example, the input data is complex int16.

  • validIn - Indicates when dataIn is valid. The block only processes input data when the DUT asserts this signal.

  • readyIn - Backpressure signal from the radio, which is the downstream consumer. When deasserted, the Data Packager block stops sending output data and buffers incoming valid data in its internal FIFO.

  • EoBIn - End-of-burst input. In Continuous mode, when this signal is asserted, the Data Packager block stops and outputs an EoB signal. In Burst mode, the block generates the EoB automatically after burstNum samples.

  • burstNum - Number of samples to transmit in Burst mode. Sampled when the block starts a new burst. Ignored in Continuous mode.

  • startIn - Burst trigger. In Burst mode, a rising edge on this signals the block for a new burst. After startIn is received, the block latches burstNum and begins packetizing burstNum samples on the next asserted validIn. Ignored in Continuous mode.

  • validOut - The block forwards this signal to an internal valid counter. In this example, the counter uses this signal for TLAST generation.

  • timestampIn - Optional 64-bit timestamp input, which is not used in this example.

The output ports are:

  • dataOut - Packetized output data conforming to AXI-Stream format.

  • validOut - Valid signal for the output data packet.

  • lastOut - The TLAST signal, asserted on the last sample of each packet. The Data Packager block automatically generates this signal.

  • EoBOut - End-of-burst output.

  • CurrentBurstNum - Current burst count. You can use this count to check if data is dropped from the host side.

  • FIFONum - Current number of data samples stored in the internal FIFO. You can use this signal to design your own flow control logic to decide when to stop producing data.

  • readyOutput - Backpressure signal propagated to the upstream data producer. When deasserted, the upstream must stop producing data.

  • timestampOut - 64-bit output timestamp, aligned with the first packet of each burst. Present only when HasTime is enabled. Not used in this example.

Data Packager Flow Control and Timing

Understanding the flow control mechanism helps you design upstream logic that responds correctly to backpressure and avoids FIFO overflows.

The Data Packager block uses a hysteresis-based flow control mechanism for the readyOutput signal. The internal Justification subsystem implements a hysteresis function on the FIFO fill level. The high and low thresholds are fixed at 800 and 256 samples, independent of the BufferDepth mask value. When the FIFO level reaches 800, the block deasserts readyOutput to stop upstream data production. The block reasserts readyOutput only when the FIFO level drops to 256, preventing rapid toggling of the ready signal.

Because the thresholds are fixed, set BufferDepth to at least 10 (2^10 = 1024 entries) so that the high threshold of 800 sits below the FIFO capacity and leaves headroom for samples between when the block deasserts readyOutput and when the upstream stops producing. In this example, the FIFO depth is 1024, so the high threshold occupies about 78% of the buffer and the low threshold occupies 25%.

The following timing diagrams illustrate the Data Packager block behavior in different scenarios.

In normal operation, readyIn is always high. When the readyIn signal from downstream remains high, the Data Packager block passes data through and packages it into packets of SPP samples. The block asserts lastOut on the last sample of each packet.

When there is backpressure, readyIn is deasserted by the radio and the Data Packager block buffers incoming valid data in its internal FIFO. The FIFONum output indicates the current number of stored samples. When you design an algorithm, you can monitor this signal and design logic to decide when to produce data upstream.

When the Data Packager block is set to Burst mode, the DUT logic asserts startIn to arm the block, then asserts validIn to stream the data samples. The block outputs a fixed number of data samples, burstNum, and asserts an EoB signal at the end of the final packet in the burst.

When you enable HasTime, the block sends the timestamp with the first packet of each burst.

Validate Transmit Timing Before Deployment

The Radio Simulator block simulates the behavior of the NI USRP radio TX interface. It enables you to verify that your transmitter design does not overflow or underflow before deploying to hardware.

In this model, the Radio Simulator block is configured with these parameters:

  • Device - N320. The NI USRP radio device to simulate.

  • TX/RX - TX. Set to transmitter mode.

  • DUT clock source - Radio. The DUT runs at the MCR derived from the radio sample rate.

  • Sample rate - 62.50 MHz. The radio sample rate.

  • Stream Data Output - on. Enables output ports that show the data stream as it would appear after the radio consumes it.

In TX mode with Stream Data Output enabled, the block has these input and output ports.

Input ports:

  • dataIn - AXI-Stream data from the DUT.

  • validIn - Valid signal for the input data.

  • lastIn - Last flag for each packet.

  • EoBIn - End-of-burst flag.

  • start - Trigger to start the radio transmission.

Output ports:

  • dataOut - Data samples as consumed by the radio.

  • validOut - Valid signal for radio output data.

  • lastOut - Last flag for radio output packets.

  • EoBOut - End-of-burst flag from the radio.

  • readyIn - Backpressure signal from the Radio Simulator block to the DUT.

  • overflow - Flag indicating that the DUT is sending valid data when the radio FIFO is full. The radio discards this data.

  • underflow - Flag indicating that the radio is attempting to transmit but has no data available in its FIFO.

  • FIFOCount - Current number of samples stored in the internal FIFO, returned as a uint16 value.

The Radio Simulator block models the TX interface behavior using an internal state machine and FIFO buffer.

The Internal FIFO block contains a circular FIFO of depth 512 samples. When the DUT produces valid data and readyIn is asserted, the block writes the data into the FIFO. The radio reads data from the FIFO at a rate determined by the MCR and sample rate. If the MCR is higher than the sample rate, the Radio Simulator block inserts idle gaps between packet reads, simulating the real-time pacing of the hardware.

The TX state machine operates in these states:

  • IDLE - Waiting for the start signal.

  • WAIT - start received, waiting for data in the FIFO.

  • TX - Actively reading data from the FIFO and producing output. The block reads one sample per clock cycle, counting up to the SPP, 256, to determine packet boundaries.

  • GAP - Idle period between output packets. The gap duration is (MCR/SampleRate - 1) * SPP clock cycles. The gap models the rate difference between the FPGA clock and the radio sample rate.

An overflow occurs when the DUT asserts validIn but the internal FIFO is full. The block asserts the overflow output for the duration of that clock cycle.

An underflow occurs when the state machine is in the TX state but the FIFO is empty. The block asserts the underflow output, and the state machine transitions to wait until more data arrives.

In a backpressure scenario, the readyIn output reflects whether the FIFO can accept more data. When the FIFO is full, the block deasserts readyIn. The block reasserts readyIn as soon as a FIFO slot becomes available. In this model, the ToneTransmitter subsystem uses readyIn to gate the NCO and the Data Packager block. This is an example of proper flow control.

Prevent Overflows and Underflows

To avoid overflows and underflows, match the data production rate of the DUT to the data consumption rate of the radio.

The radio consumes data at the configured sample rate. In this example, the sample rate is 250 MS/s, which is a 1:1 ratio with the 250 MHz MCR. The DUT can produce data on every clock cycle without overflow. At lower sample rates, this ratio increases and the DUT must produce data at a lower rate.

To handle rate differences between the DUT and radio, use backpressure signals to gate data production:

  • The Data Packager block provides a readyOutput signal based on its internal FIFO level.

  • The readyIn signal from the Radio Simulator block provides backpressure from the radio FIFO.

  • The ToneTransmitter gates data production using the AND of validIn and readyOutput. The NCO only advances when both the Data Packager block and the radio are ready to accept data.

The Data Packager block internal FIFO has a depth of 2^10, or 1024 entries, as set by the BufferDepth mask value of 10. This buffer absorbs short-term timing mismatches. The hysteresis thresholds on the ready signal prevent rapid toggling.

Simulate Clock Drift Effects

To verify that your design tolerates real-world clock variation, simulate the model with a custom DUT clock and jitter enabled.

When the DUT uses a custom clock independent of the radio MCR, small frequency differences accumulate over time. The data production rate drifts relative to the consumption rate, gradually filling or draining the FIFO. Eventually this causes overflows or underflows.

To verify your design handles clock drift before deploying to hardware, use the Radio Simulator block clock drift mode. Change DUT clock source from Radio to Custom in the block dialog.

  • DUT clock source - Set to Custom to decouple the DUT clock from the radio MCR. When set to Radio, which is the default, the DUT runs at the MCR derived from the radio sample rate and device resampling factor.

  • Custom DUT clock rate - The clock frequency of the DUT in Hz. This parameter is visible only when the DUT clock source is Custom. Set this value to the actual clock frequency of your external clock source. The block recalculates the gap time between output packets as (DUTClockRate / SampleRate - 1) * SPP clock cycles. This value reflects the rate difference between the custom DUT clock and the radio sample rate.

To simulate timing uncertainty from a real oscillator, configure the Advanced Settings tab.

  • Clock uncertainty - Enable to add random variation to the gap time between radio output packets to model jitter from a real clock source.

  • Possibility of uncertainty (0 to 1) - The probability that jitter occurs on any given packet boundary. A value of 0 means no jitter. A value of 1 means jitter occurs on every packet boundary.

  • Cycle of clock uncertainty - The maximum jitter magnitude in clock cycles. Larger values simulate a less stable oscillator.

For example, to simulate a 122.88 MHz clock with moderate jitter:

  • Set the custom DUT clock rate to 122.88e6.

  • Enable clock uncertainty with a possibility of 0.3.

  • Set the cycle of clock uncertainty to 10.

These values produce a nominal gap time of (122.88e6 / 30.72e6 - 1) * 256 = 768 clock cycles. On 30% of packet boundaries, a random jitter of 0 to 10 cycles is added to the gap. This exercises the FIFO buffering and backpressure mechanisms under realistic timing conditions.

Verify Design in Simulation

Verify the design by simulating the model.

sl_out = sim(modelname);

Extract the logged variables from the simulation output. The To Workspace blocks inside the model log the overflow, underflow, DUT output, and radio output data into the Simulink.SimulationOutput object.

overflow = sl_out.get('overflow');
underflow = sl_out.get('underflow');
DUTDataOut = sl_out.get('DUTDataOut');
radioDataOut = sl_out.get('radioDataOut');

Plot the overflow and underflow signals to verify that no violations occur during the simulation.

figure;
subplot(2,1,1);
plot(overflow);
title('Overflow');
xlabel('Sample');
ylabel('Flag');
ylim([-0.1 1.1]);
xlim([1 length(overflow)]);

subplot(2,1,2);
plot(underflow);
title('Underflow');
xlabel('Sample');
ylabel('Flag');
ylim([-0.1 1.1]);
xlim([1 length(underflow)]);

If the design is correct, both signals will remain at 0 throughout the simulation, indicating that the DUT produces data at a rate that matches the radio consumption rate.

fprintf('Total overflow events: %d\n', sum(overflow));
fprintf('Total underflow events: %d\n', sum(underflow));
Total overflow events: 0
Total underflow events: 0

Verify the transmitted tone by examining the DUT output data.

figure;
numSamples = min(2048, length(DUTDataOut));
plot(real(double(DUTDataOut(1:numSamples))));
hold on;
plot(imag(double(DUTDataOut(1:numSamples))));
hold off;
title('DUT Output - Transmitted Tone');
xlabel('Sample');
ylabel('Amplitude');
xlim([1 numSamples]);
legend('Real','Imaginary');

Verify that the radio output data matches the DUT output data. Due to pipeline latency, the radio output may contain fewer samples. Compare only the overlapping portion.

numCompare = min(length(DUTDataOut), length(radioDataOut));
dataMismatch = DUTDataOut(1:numCompare) - radioDataOut(1:numCompare);
fprintf('Number of samples compared: %d\n', numCompare);
fprintf('Number of samples mismatch: %g\n', max(abs(double(dataMismatch))));
Number of samples compared: 1024
Number of samples mismatch: 0

Configure IP Core

When you are satisfied with the simulated behavior of the model, you can proceed to integrate your design into a custom IP core by generating HDL code and mapping the model inputs and outputs to the hardware interfaces.

First, use the hdlsetuptoolpath (HDL Coder) function to set up the tool chain. Specify the path to your Vivado® bin directory. For more information, see Set Up Third-Party Tools.

hdlsetuptoolpath('ToolName','Xilinx Vivado', ...
    'ToolPath','/opt/Xilinx/Vivado/2021.1/bin');

From the Apps tab in the Simulink Toolstrip, select HDL Coder. Then open the HDL Code tab.

Configure Output Options

In the HDL Code tab, configure the output options:

  • Ensure the ToneTransmitter subsystem is pinned in the Code for option. To pin this selection, select the ToneTransmitter subsystem in the Simulink model and click the pin icon.

  • Select IP Core as the Output > IP Core option.

HDL Code tab in the Simulink Toolstrip

Configure HDL Code Generation Settings

Open the Configuration Parameters dialog box by clicking Settings in the HDL Code tab.

In the HDL Code Generation pane, ensure that Language is set to Verilog. By default, HDL Coder generates the Verilog® files in the hdlsrc folder. You can select an alternative location. If you make any changes, click Apply.

HDL Code Generation panel in the Configuration Parameters window

In the Target pane, configure these settings:

  • Under Workflow Settings, select the IP Core Generation workflow. To set Project Folder, click Browse and select a target location for saving the generated project files. If you do not specify a project folder, the software saves the generated project files in the working directory.

  • Under Tool and Device Settings, select your radio from the Target Platform list. This example uses a USRP N320 radio. If you are using a different radio, adjust the reference design parameters to match your radio.

  • Under Reference Design Settings, set Reference Design to the desired reference FPGA image for your design, based on how you set up your hardware. For a USRP N320 radio, you have one option: HG: 1GigE, 10GigE.

    Set the reference design parameters to these values:

    • Number of Input Streams — Set to 0 because the FPGA generates the tone and the DUT does not receive data from the radio.

    • Number of Output Streams — Set to 1 because the DUT transmits data through one antenna.

    • Sample Rate (S/s) — Set to any valid value for your radio, which is a supported MCR divided by a supported interpolation or decimation rate. This example uses a USRP N320 radio and a sample rate of 250 MS/s, which is the default value and corresponds to the maximum supported MCR, 250 MHz. For more information about supported values on your radio, see Determine Radio Device Capabilities.

    • Reference Design Optimization — Set to Moderate. This setting uses a static stream connection between the DUT and the radio, which prevents an underflow at the start of transmission. Without no optimization, the design uses a dynamic connection that can produce a brief underflow when streaming begins. The underflow does not affect steady-state operation.

    • DUT Clock Source — Set to Radio. When you select this setting, the DUT is clocked at the MCR used by the radio to achieve the specified sample rate.

    • Stream Port FIFO Length (Samples) — Set to Auto. This setting automatically calculates the buffer length for each DUT output data streaming port.

    • Register Port FIFO Length (Samples) — Set to Auto. This setting automatically calculates the buffer length for each DUT register port.

    Under Objectives Settings, because the DUT Clock Source is set to Radio, the Target Frequency is fixed at the highest supported MCR of the radio.

Click Apply.

HDL Code Generation > Target panel in the Configuration Parameters window

To apply these settings and close the Configuration Parameters window, click OK.

For more information, see Configure HDL Code Generation Settings.

Map Target Interfaces

In the HDL Code tab, click Target Interface to open the Interface Mapping table in the IP Core editor. To populate the table with your user logic, click the Reload IP core settings button: Reload IP core settings and interface mapping table from model icon.

IP Core Interface Mapping table for the tone transmitter example

The Source, Port Type, and Data Type columns are populated based on the Simulink model. In this example, the Interface column appears prepopulated because the model is saved with the interface mapping already assigned.

  • The Inc port maps to a Write Register interface. This register sets the NCO frequency increment value.

  • The ValidIn port maps to a Write Register interface. This register enables the tone generation.

  • The NCORst port maps to a Write Register interface. This register resets the NCO block.

  • The DPRst port maps to a Write Register interface. This register resets the Data Packager block.

  • The Data_Out, Valid_Out, Last_Out, EoB_Out, and Ready_In ports map to a Stream Port Output0 interface.

The IP Core editor populates the Interface Mapping column automatically based on the signal names in the model. If the mapping is incorrect, manually adjust the Interface Mapping column.

To set the interface options for the streaming interface, open the Set Interface Options window by clicking Options in the far right of the table.

For the Data_Out options, select a transmit antenna as the sink connection. The DUT transmits the tone through this antenna on the radio.

Data_Out interface options showing transmit antenna selection

When you have populated the table, validate the interface mapping by clicking the Validate IP core settings button: Validate IP core settings and interface mapping icon.

For more information, see Map Target Interfaces.

Generate and Load Bitstream

To generate a bitstream from the configured IP core, select Build Bitstream > Deployment Settings.

Deployment Settings button in Build Bitstream drop-down menu

  • Ensure that the Run build process externally option is selected. This setting is the default and it ensures that the bitstream build executes in an external shell, which allows you to continue using MATLAB while building the FPGA image.

  • In the Program Target Device settings, set the IP address. The default is 192.168.10.2. If your radio has a different IP address, update this value.

Deployment Settings window

Click Build Bitstream to create a Vivado IP core project and build the bitstream. After the basic project checks complete, the Diagnostic Viewer displays a Build Bitstream Successful message along with warning messages. However, you must wait until the external shell displays a successful bitstream build before moving to the next step. Closing the external shell before this time terminates the build.

The bitstream for this project generates with the name n3xx.bit in the build_N320_HG/build_N320_HG folder of the working directory after a successful bitstream build. If you are using a different radio, the name and location reflect your radio.

To load the bitstream onto the device now, select Build Bitstream > Program Target Device. Alternatively, you can load the bitstream later by using the programFPGA function in the generated host interface script.

For more information, see Generate Bitstream and Program FPGA.

Generate Host Interface Scripts

To generate MATLAB scripts that enable you to connect to and run your deployed design on your radio, in the HDL Code tab, click Host Interface Script. This step generates two scripts in your working directory based on the target interface mapping that you configured for your IP core.

  • gs_wtToneTransmitterUSRPTargetingSL_interface.m — Host interface script that creates an fpga object for interfacing with your DUT running on the FPGA from MATLAB. The script contains code that connects to your hardware and programs the FPGA and code samples to get you started with running the algorithm on your radio. For more information, see Interface Script File.

  • gs_wtToneTransmitterUSRPTargetingSL_setup.m — Setup function that configures the fpga object with the hardware interfaces and ports from your DUT algorithm. The function contains DUT port objects that have the port name, direction, data type, and interface mapping information, which it maps to the corresponding interfaces. For more information, see Setup Function File.

    Note

    The number of samples per host-side readPort or writePort operation, specified in the FrameSize name-value argument of the addRFNoCStreamInterface function, is set by default to 1e5. To change this value or the value of the Timeout name-value argument, edit the setup function file.

Verify Tone Transmitter Algorithm Using MATLAB

To verify the tone transmitter algorithm running on your radio, use this modified version of the host interface script to set up the device, configure the DUT, transmit a tone, and verify the output frequency using MATLAB.

Open Live Script

You can open this live script in MATLAB from the example working directory and use it interactively. In the Files panel, navigate to your example working directory and open VerifyToneTransmitterUsingMATLABExample.m.

Select Radio

Call the radioConfigurations function. The function returns all available radio setup configurations that you saved using the Radio Setup wizard.

savedRadioConfigurations = radioConfigurations;

To update the menu with your saved radio setup configuration names, click Update. Then select the radio to use with this example.

savedRadioConfigurationNames = string({savedRadioConfigurations.Name});
radioConfig = savedRadioConfigurationNames(1) ;
transmitAntennas = hTransmitAntennas(radioConfig);
receiveAntennas = hCaptureAntennas(radioConfig);

Create Radio Object

Use the radioConfigurations function with the configuration name to create a radio object.

radio = radioConfigurations(radioConfig);

Create usrp System Object

Create a usrp System object with the specified radio. This System object controls the radio hardware.

hDevice = usrp(radio);

Program FPGA

If you have not yet programmed your device with the bitstream, select the load bitstream option to use the programFPGA function. Update the code with your bitstream and device tree file. You can find these files in the programFPGA call in the generated host interface script, gs_wtToneTransmitterUSRPTargetingSL_interface. If your radio is a USRP X310, you need only a bitstream file to program the FPGA.

loadBitstream = false;
if(loadBitstream)
    programFPGA(hDevice, ...
        "build_N320_HG/build-N320_HG/n3xx.bit", ...    % replace with your .bit file
        "build_N320_HG/build/usrp_n320_fpga_HG.dts");  % replace with your .dts file
end

To configure the DUT interfaces according to the hand-off information file, use the describeFPGA function. Calling this function additionally sets the default values for the SampleRate, DUTOutputAntennas, and DUTInputAntennas properties based on the selections you made in Simulink.

% Replace with your hand-off information file
describeFPGA(hDevice,"wtToneTransmitterUSRPTargetingSL_wthandoffinfo.mat");

Configure Device

Configure the usrp System object to specify the sample rate, antennas, and antenna gain values.

Set the transmit and receive center frequencies.

hDevice.TransmitCenterFrequency = 2450000000;
hDevice.ReceiveCenterFrequency = 2450000000;

Set the transmit and receive antenna gain.

hDevice.TransmitRadioGain =35;
hDevice.ReceiveRadioGain =35;
hDevice.DUTOutputAntennas = transmitAntennas(1);
hDevice.CaptureAntennas = receiveAntennas(1);

Create and Set Up FPGA Object

To connect to the DUT on the FPGA of your radio, create an fpga object with your usrp System object.

hFPGA = fpga(hDevice);

Set up the fpga object using the generated setup function.

gs_wtToneTransmitterUSRPTargetingSL_setup(hFPGA);

Set Up Device Object

To establish a connection with the radio hardware, call the setup function on the usrp System object. This action connects to the radio, applies the radio front end properties, and validates that the bitstream file matches the hand-off information file.

setup(hDevice);

Configure and Start DUT

Use the writePort function to configure the tone transmitter DUT on the FPGA.

Set the NCO tone frequency.

toneFrequency = 2000000;
hSetToneFrequency(hDevice,hFPGA, toneFrequency)

Enable data valid to start the tone transmission.

writePort(hFPGA, "DPRst", false);
writePort(hFPGA, "NCORst", false);
writePort(hFPGA, "validIn", 1);
pause(0.5);

Start Radio Transmission

Call the usrp System object to start the radio transmission. The FPGA streams the packetized tone data to the radio front end.

hDevice(50000);

Capture and Verify Output

Capture data from the receive antenna and verify the transmitted tone frequency using a periodogram.

numSamples = 50000;
data = hDevice.capture(numSamples);

Compute the power spectral density and find the peak frequency.

[pxx, f] = periodogram(single(data), [], length(data), hDevice.SampleRate, 'centered');
[~, index] = max(pxx);
maxFreq = f(index);

Compare the measured and expected frequencies. The relative error should be less than 0.1%.

relativeError = abs(maxFreq - toneFrequency) / hDevice.SampleRate;
fprintf('Expected frequency: %.2f kHz\n', toneFrequency/1e3);
Expected frequency: 2000.00 kHz
fprintf('Measured frequency: %.2f kHz\n', maxFreq/1e3);
Measured frequency: 1999.87 kHz
fprintf('Relative error: %.4f%%', relativeError*100);
Relative error: 0.0001%

Plot the power spectral density to visualize the transmitted tone.

figure;
plot(f/1e3, 10*log10(pxx));
xlabel('Frequency (kHz)');
ylabel('Power/Frequency (dB/Hz)');
title('Captured Spectrum - Tone Transmitter Output');
grid on;

Stop DUT and Release Hardware

Reset the NCO and Data Packager to stop the tone transmission.

hStopDUTTransmit(hFPGA)

Release the hardware objects.

release(hFPGA);
release(hDevice);

Next Steps

This example demonstrates the recommended pattern for streaming transmit pipelines on NI USRP radios. Provide samples from your algorithm, and let the Data Packager handle the streaming protocol. Use the Radio Simulator block to validate the streaming behavior in simulation, where it acts as a radio sink for transmit designs or a radio source for receive designs.

To create your own transmit pipeline, replace the NCO tone generator with your signal processing algorithm, such as a modulator, filter chain, or custom waveform generator. Keep the Data Packager and streaming interface unchanged. The Data Packager handles packetization and buffering regardless of the upstream algorithm.

For a receive-path example that uses a stream input from the radio, see Getting Started with NI USRP Targeting.

See Also

Topics