%% Acquire Signal Spectrum on a Rohde & Schwarz(R) Spectrum Analyzer using the IVI-C Driver
% This example shows how to initialize the driver, read a few properties of 
% the driver and acquire signal spectrum using Rohde & Schwarz spectrum
% analyzer and visualize the spectrum in MATLAB(R).

%%
% Copyright 2015 The MathWorks, Inc.

%% Requirements
% This example requires the following to be installed on the computer:
%
% * Rohde & Schwarz Spectrum Analyzer IVI-C x64 driver version 1.0 or
% newer
%

%% Enumerate Available IVI-C Drivers On The Computer
% This enumerates the IVI drivers that have been installed on the computer.
IviInfo = instrhwinfo('ivi');
IviInfo.Modules

%% Create MATLAB Instrument Driver And Connect To The Instrument

% Create the MATLAB instrument driver
makemid('rsspecan','rsspecan.mdd')

% Use icdevice with the MATLAB instrument driver name and instrument's 
% resource name to create a device object. In this example the instrument 
% is connected by GPIB at board index 0 and primary address 1.
myInstrument = icdevice('rsspecan.mdd', 'GPIB0::01::INSTR','optionstring','simulate=true');

% Connect driver instance
connect(myInstrument);

%% Get General Device Properties
% Query information about the driver and instrument
Utility = get(myInstrument,'Utility');
InherentIviAttributesInstrumentIdentification = get(myInstrument, 'Inherentiviattributesinstrumentidentification'); 
InherentIviAttributesDriverIdentification = get(myInstrument,'Inherentiviattributesdriveridentification'); 
Revision = get(InherentIviAttributesDriverIdentification, 'Revision');
Vendor = get(InherentIviAttributesDriverIdentification, 'Driver_Vendor');
Description = get(InherentIviAttributesDriverIdentification, 'Description');
InstrumentModel = get(InherentIviAttributesInstrumentIdentification, 'Model');
FirmwareRev = get(InherentIviAttributesInstrumentIdentification, 'Firmware_Revision'); 
% Print the queried driver properties
fprintf('Revision:        %s\n', Revision);
fprintf('Vendor:          %s\n', Vendor);
fprintf('Description:     %s\n', Description);
fprintf('InstrumentModel: %s\n', InstrumentModel);
fprintf('FirmwareRev:     %s\n', FirmwareRev);
fprintf(' \n');

%% Attributes and Variables Definition

% These constants are defined in the IVI header file 'IviSpecAn.h'
IVISPECAN_VAL_DETECTOR_TYPE_AUTO_PEAK = 1;
IVISPECAN_VAL_VERTICAL_SCALE_LINEAR = 1;
IVISPECAN_VAL_AMPLITUDE_UNITS_DBM = 1;

%% Setting Center frequency and Span
% Configure the frequency range of the spectrum analyzer using the center
% frequency and the frequency span.
% 

FrequencyCenter = 2E+9;
FrequencySpan = 500E+6;
Configuration = get(myInstrument, 'Configuration');
invoke(Configuration, 'configurefrequencycenterspan', FrequencyCenter,FrequencySpan);

%% Setting Single Sweep
% Configure the acquisition attributes of the spectrum analyzer.
SweepModeContinuous = false;
NumberOfSweeps = 1;
DetectorTypeAuto = true;
DetectorType = IVISPECAN_VAL_DETECTOR_TYPE_AUTO_PEAK;
VerticalScale = IVISPECAN_VAL_VERTICAL_SCALE_LINEAR;
Configuration = get(myInstrument, 'Configuration');
invoke(Configuration, 'configureacquisition', SweepModeContinuous,NumberOfSweeps,DetectorTypeAuto,DetectorType,VerticalScale);

%% Configure Reference Level and Range
% Configure the vertical attributes of the spectrum analyzer. This
% corresponds to attributes like amplitude units, input attenuation, input
% impedance, reference level, and reference level offset 
AmplitudeUnits = IVISPECAN_VAL_AMPLITUDE_UNITS_DBM;
InputImpedance = 50.0;
ReferenceLevel = -10.0;
ReferenceLevelOffset = 0;
AttenuationAuto = false;
Attenuation = 10.0;
invoke(Configuration, 'configurelevel', AmplitudeUnits, InputImpedance, ReferenceLevel, ReferenceLevelOffset, AttenuationAuto, Attenuation);

%% Configure Resolution Bandwidth (RBW), Video Bandwidth (VBW) and Sweep Time
% Configure the coupling and sweeping attributes of the spectrum analyzer 
ResolutionBandwidthAuto = false;
ResolutionBandwidth = 1.0E+6;
VideoBandwidthAuto = false;
VideoBandwidth = 1.0E+6;
SweepTimeAuto = false;
SweepTime = 5.0E-3;
invoke(Configuration, 'configuresweepcoupling', ResolutionBandwidthAuto,ResolutionBandwidth,VideoBandwidthAuto,VideoBandwidth,SweepTimeAuto,SweepTime);

%% Perform the sweep
% Initiate a signal acquisition based on the present instrument
% configuration. It then waits for the acquisition to complete, and returns
% the trace as an array of amplitude values. The amplitude array returns
% data that represent the amplitude of the signals of the sweep from the
% start frequency to the stop frequency. The Amplitude Units attribute
% determines the units of the points in the amplitude array. 
Tracename = 0;
MaximumTimeMs = 5000;
ArrayLength = 501;
AmplitudeX = 1.75e+09:0.1e+07:2.25e+09;
AmplitudeY = zeros(ArrayLength,1);
Measurement = get(myInstrument, 'Measurement');
[ActualPointsY,AmplitudeY] = invoke(Measurement, 'readytrace', Tracename,MaximumTimeMs,ArrayLength,AmplitudeY);

%% Visualize Data And Display Any Errors

% Display the acquired spectrum
plot(AmplitudeX,AmplitudeY);
title('Spectrum Analyzer Trace Plot');
xlabel('Frequency (Hz)'); 
ylabel('Amplitude (dBm)');

% If there are any errors, query the driver to retrieve and display them.
ErrorNum = 1;
while (ErrorNum ~= 0)
    [ErrorNum, ErrorMsg] = invoke(Utility, 'errorquery');
    fprintf('ErrorQuery: %d, %s\n', ErrorNum, ErrorMsg);
end

%% Disconnect Device Object And Clean Up
disconnect(myInstrument);
% Remove instrument objects from memory.
delete(myInstrument);

%%



%% Additional Information:
% This example shows the setup and acquisition of data from an spectrum
% analyzer using the IVI driver. Once the measured spectrum is retrieved
% from the instrument, MATLAB can be used to visualize and perform analyses
% on the data using the rich library of functions in the Signal Processing
% Toolbox(TM) and Communications Systems Toolbox(TM). Using Instrument Control
% Toolbox(TM), it is possible to automate control of instruments, and, build
% test systems that use MATLAB to perform analyses that may not be possible 
% using the built-in capability of the hardware.
