Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

A Software-Defined Radio For The Masses, Part 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

A Software-Defined Radio

for the Masses, Part 3


Learn how to use DSP to make the PC sound-card interface
from Part 2 into a functional software-defined radio.
We also explore a powerful filtering technique
called FFT fast-convolution filtering.

By Gerald Youngblood, AC5OG

P
art 11 of this series provided a sound card for signal processing. The quadrature signals. The sound-card
general description of digital full-duplex DirectX8 interface, de- interface provides an input buffer ar-
signal processing (DSP) as used scribed in Part 2, accomplishes the ray, inBuffer(), and an output buffer
in software-defined radios (SDRs) and input and output of the sampled array, outBuffer(), through which the
included an overview of a full-featured
radio that uses a PC to perform all
DSP and control functions. Part 22
described Visual Basic source code
that implements a full-duplex quadra-
ture interface to a PC sound card.
As previously described, in-phase
(I) and quadrature (Q) signals give the
ability to modulate or demodulate vir-
tually any type of signal. The Tayloe
Detector, described in Part 1, is a
simple method of converting a modu-
lated RF signal to baseband in quadra-
ture, so that it can be presented to the
left and right inputs of a stereo PC
1Notes appear on page 36.

8900 Marybank Dr
Austin, TX 78750
AC5OG@arrl.net Fig 1—DSP software architecture block diagram.

Nov/Dec 2002 27
DSP code receives the captured sig- • Conversion from the time domain • FFT fast-convolution filtering.
nal and then outputs the processed into the frequency domain using • Conversion back to the time domain
signal data. a fast Fourier transform (FFT). with an inverse fast Fourier trans-
This article extends the sound-card • Cartesian-to-polar conversion of the form (IFFT).
interface to a functional SDR receiver signal vectors. • Digital automatic gain control (AGC)
demonstration. To accomplish this, the • Frequency translation from the with variable hang time.
following functions are implemented 11.25 kHz-offset baseband IF to • Transfer of the processed signal to
in software: 0 Hz. the output buffer for transmit or
• Split the stereo sound buffers into I • Sideband selection. receive operation.
and Q channels. • Band-pass filter coefficient genera- The demonstration source code may
tion.

Public Const Fs As Long = 44100 ‘Sampling frequency in samples per


‘second
Public Const NFFT As Long = 4096 ‘Number of FFT bins
Public Const BLKSIZE As Long = 2048 ‘Number of samples in capture/play block
Public Const CAPTURESIZE As Long = 4096 ‘Number of samples in Capture Buffer
Public Const FILTERTAPS As Long = 2048 ‘Number of taps in bandpass filter
Private BinSize As Single ‘Size of FFT Bins in Hz

Private order As Long ‘Calculate Order power of 2 from NFFT


Private filterM(NFFT) As Double ‘Polar Magnitude of filter freq resp
Private filterP(NFFT) As Double ‘Polar Phase of filter freq resp
Private RealIn(NFFT) As Double ‘FFT buffers
Private RealOut(NFFT) As Double
Private ImagIn(NFFT) As Double
Private ImagOut(NFFT) As Double

Private IOverlap(NFFT - FILTERTAPS - 1) As Double ‘Overlap prev FFT/IFFT


Private QOverlap(NFFT - FILTERTAPS - 1) As Double ‘Overlap prev FFT/IFFT

Private RealOut_1(NFFT) As Double ‘Fast Convolution Filter buffers


Private RealOut_2(NFFT) As Double
Private ImagOut_1(NFFT) As Double
Private ImagOut_2(NFFT) As Double

Public FHigh As Long ‘High frequency cutoff in Hz


Public FLow As Long ‘Low frequency cutoff in Hz
Public Fl As Double ‘Low frequency cutoff as fraction of Fs
Public Fh As Double ‘High frequency cutoff as fraction of Fs
Public SSB As Boolean ‘True for Single Sideband Modes
Public USB As Boolean ‘Sideband select variable
Public TX As Boolean ‘Transmit mode selected
Public IFShift As Boolean ‘True for 11.025KHz IF

Public AGC As Boolean ‘AGC enabled


Public AGCHang As Long ‘AGC AGCHang time factor
Public AGCMode As Long ‘Saves the AGC Mode selection
Public RXHang As Long ‘Save RX Hang time setting
Public AGCLoop As Long ‘AGC AGCHang time buffer counter
Private Vpk As Double ‘Peak filtered output signal
Private G(24) As Double ‘Gain AGCHang time buffer
Private Gain As Double ‘Gain state setting for AGC
Private PrevGain As Double ‘AGC Gain during previous input block
Private GainStep As Double ‘AGC attack time steps
Private GainDB As Double ‘AGC Gain in dB
Private TempOut(BLKSIZE) As Double ‘Temp buffer to compute Gain
Public MaxGain As Long ‘Maximum AGC Gain factor

Private FFTBins As Long ‘Number of FFT Bins for Display


Private M(NFFT) As Double ‘Double precision polar magnitude
Private P(NFFT) As Double ‘Double precision phase angle
Private S As Long ‘Loop counter for samples
Fig 2—Variable declarations.

28 Nov/Dec 2002
be downloaded from ARRLWeb.3 The single line of code for this and other quency of the sampled quadrature sig-
software requires the dynamic link important DSP functions (see Note 4). nal, the upper sideband is located in
library (DLL) files from the Intel The FFT effectively consists of a bins 1 through 2047, and the lower
Signal Processing Library4 to be lo- series of very narrow band-pass filters, sideband is located in bins 2048
cated in the working directory. These the outputs of which are called bins, through 4095. Bin 0 contains the car-
files are included with the demo soft- as illustrated in Fig 4. Each bin has a rier translated to 0 Hz. An FFT per-
ware. magnitude and phase value represen- formed on an analytic signal I + jQ
tative of the sampled input signal’s allows positive and negative frequen-
The Software Architecture content at the respective bin’s center cies to be analyzed separately.
Fig 1 provides a block diagram of frequency. Overlap of adjacent bins re- The Turtle Beach Santa Cruz sound
the DSP software architecture. The sembles the output of a comb filter as card I use has a 3-dB frequency re-
architecture works equally well for discussed in Part 1. sponse of approximately 10 Hz to
both transmit and receive with only a The PC SDR uses a 4096-bin FFT. 20 kHz. (Note: the data sheet states a
few lines of code changing between the With a sampling rate of 44,100 Hz, the high-frequency cutoff of 120 kHz,
two. While the block diagram illus- bandwidth of each bin is 10.7666 Hz which has to be a typographical error,
trates functional modules for Ampli- (44,100/4096), and the center fre- given the 48-kHz maximum sampling
tude and Phase Correction and the quency of each bin is the bin number rate). Since we sample the RF signal
LMS Noise and Notch Filter, discus- times the bandwidth. Notice in Fig 4 in quadrature, the sampling rate is
sion of these features is beyond the that with respect to the center fre- effectively doubled (44,100 Hz times
scope of this article.
Amplitude and phase correction
permits imperfections in phase and
Erase RealIn, ImagIn
amplitude imbalance created in the
analog circuitry to be corrected in the For S = 0 To CAPTURESIZE - 1 Step 2 ‘Copy I to RealIn and Q to ImagIn
frequency domain. LMS noise and RealIn(S \ 2) = inBuffer(S + 1) ‘Zero stuffing second half of
notch filters5 are an adaptive form of ImagIn(S \ 2) = inBuffer(S) ‘RealIn and ImagIn Next S
finite impulse response (FIR) filtering
that accomplishes noise reduction in Fig 3—Parsing input buffers into I and Q signal vectors.
the time domain. There are other tech-
niques for noise reduction that can be
accomplished in the frequency domain
such as spectral subtraction,6 correla-
tion7 and FFT averaging.8
Parse the Input Buffers to
Get I and Q Signal Vectors
Fig 2 provides the variable and
constant declarations for the demon-
stration code. The code for parsing the
inBuffer() is illustrated in Fig 3. The
left and right signal inputs must be
parsed into I and Q signal channels
before they are presented to the FFT
input. The 16-bit integer left- and
right-channel samples are interleaved,
therefore the code shown in Fig 3 must Fig 4—FFT output bins.
be used to split the signals. The arrays
RealIn() and RealOut() are used to
store the I signal vectors and the ar- nspzrFftNip RealIn, ImagIn, RealOut, ImagOut, order, NSP_Forw
rays ImagIn() and ImagOut() are used nspdbrCartToPolar RealOut, ImagOut, M, P, NFFT ‘Cartesian to polar
to store the Q signal vectors. This cor-
responds to the nomenclature used in Fig 5—Time domain to frequency domain conversion using the FFT.
the complex FFT algorithm. It is not
critical which of the I and Q channels
goes to which input because one can
simply reverse the code in Fig 3 if the
sidebands are inverted.
The FFT: Conversion to the
Frequency Domain
Part 1 of this series discussed how
the FFT is used to convert discrete-
time sampled signals from the time
domain into the frequency domain (see
Note 1). The FFT is quite complex to
derive mathematically and somewhat Fig 6—Offset baseband IF diagram. The local oscillator is shifted by 11.025 kHz so that
tedious to code. Fortunately, Intel has the desired-signal carrier frequency is centered at an 11,025-Hz offset within the FFT
provided performance-optimized code output. To shift the signal for subsequent filtering the desired bins are simply copied to
in DLL form that can be called from a center the carrier frequency, fc, at 0 Hz.

Nov/Dec 2002 29
two channels yields an 88,200-Hz ef- increases substantially near 0 Hz. of the sampling rate, as shown in
fective sampling rate). This means This is caused by several mechanisms: Fig 6.
that the output spectrum of the FFT 1/f noise in the active components, Fig 7 provides the source code for
will be twice that of a single sampled 60/120-Hz noise from the ac power shifting the offset IF to 0 Hz. The car-
channel. In our case, the total out- lines, microphonic noise caused by me- rier frequency of 11,025 Hz is shifted
put bandwidth of the FFT will be chanical vibration and local-oscillator to bin 0 and the upper sideband is
10.7666 Hz times 4096 or 44,100 Hz. phase noise. This can be a problem for shifted to bins 1 through 1023. The
Since most sound cards roll off near weak-signal work because most people lower sideband is shifted to bins 3072
20 kHz, we are probably limited to a tune CW signals for a 700-1000 Hz to 4094. The code allows the IF shift
total bandwidth of approximately tone. Fortunately, much of this noise to be enabled or disabled, as is re-
40 kHz. disappears above 1 kHz. quired for transmitting.
Fig 5 shows the DLL calls to the Given that we have 44 kHz of spec-
Intel library for the FFT and subse- trum to work with, we can offset the Selecting the Sideband
quent conversion of the signal vectors digital IF to any frequency within the So how do we select sideband? We
from the Cartesian coordinate system FFT output range. It is simply a mat- store zeros in the bins we don’t want
to the Polar coordinate system. The ter of deciding which FFT bin to des- to hear. How simple is that? If it were
nspzrFftNip routine takes the time ignate as the carrier frequency and possible to have perfect analog ampli-
domain RealIn() and ImagIn() vectors then offsetting the local oscillator by tude and phase balance on the
and converts them into frequency do- the appropriate amount. We then copy sampled I and Q input signals, we
main RealOut() and ImagOut() vec- the respective bins for the desired would have infinite sideband suppres-
tors. The order of the FFT is computed sideband so that they are located at sion. Since that is not possible, any
in the routine that calculates the fil- 0 Hz for subsequent processing. In the imbalance will show up as an image
ter coefficients as will be discussed PC SDR, I have chosen to use an off- in the passband of the receiver. Fortu-
later. NSP_Forw is a constant that set IF of 11,025 Hz, which is one fourth nately, these imbalances can be cor-
tells the routine to perform the for-
ward FFT conversion.
In the Cartesian system the signal
is represented by the magnitudes of
IFShift = True ‘Force to True for the demo
two vectors, one on the Real or x plane
and one on the Imaginary or y plane. If IFShift = True Then ‘Shift sidebands from 11.025KHz IF
These vectors may be converted to a For S = 0 To 1023
If USB Then
single vector with a magnitude (M) M(S) = M(S + 1024) ‘Move upper sideband to 0Hz
and a phase angle (P) in the polar sys- P(S) = P(S + 1024)
Else
tem. Depending on the specific DSP M(S + 3072) = M(S + 1) ‘Move lower sideband to 0Hz
algorithm we wish to perform, one co- P(S + 3072) = P(S + 1)
ordinate system or the other may be Next
End If

more efficient. I use the polar coordi- End If


nate system for most of the signal pro-
cessing in this example. The Fig 7—Code for down conversion from offset baseband IF to 0 Hz.
nspdbrCartToPolar routine converts
the output of the FFT to a polar vec-
tor consisting of the magnitudes in M()
and the phase values in P(). This func-
If SSB = True Then ‘SSB or CW Modes
tion simultaneously performs Eqs 3
If USB = True Then
and 4 in Part 1 of this article series.
For S = FFTBins To NFFT - 1 ‘Zero out lower sideband
Offset Baseband IF Conversion M(S) = 0
Next
to Zero Hertz
Else
My original software centered the For S = 0 To FFTBins - 1 ‘Zero out upper sideband
RF carrier frequency at bin 0 (0 Hz). M(S) = 0
With this implementation, one can Next
display (and hear) the entire 44-kHz End If
spectrum in real time. One of the prob- End If
lems encountered with direct-conver-
sion or zero-IF receivers is that noise Fig 8—Sideband selection code.

Fig 9—FFT fast-convolution-filtering block diagram. The filter impulse-response coefficients are first converted to the frequency
domain using the FFT and stored for repeated use by the filter routine. Each signal block is transformed by the FFT and subsequently
multiplied by the filter frequency-response magnitudes. The resulting filtered signal is transformed back into the time domain using the
inverse FFT. The Overlap/Add routine corrects the signal for circular convolution.

30 Nov/Dec 2002
rected through DSP code either in the 64 taps, and it produces exactly the (bin 0), as shown in Fig 4. Fig 10 illus-
time domain before the FFT or in the same result. trates the process of FFT convolution
frequency domain after the FFT. These For me, FFT convolution is easier of a transformed filter impulse re-
techniques are beyond the scope of this to understand than direct convolution sponse with a transformed input sig-
discussion, but I may cover them in a because I mentally visualize filters in nal. Once the signal is transformed
future article. My prototype using the frequency domain. As described in back to the time domain by the inverse
INA103 instrumentation amplifiers Part 1 of this series, the output of the FFT, we must then perform a process
achieves approximately 40 dB of op- complex FFT may be thought of as a called the overlap/add method. This
posite sideband rejection without cor- long bank of narrow band-pass filters is because the process of convolution
rection in software. aligned around the carrier frequency produces an output signal that is
The code for zeroing the opposite
sideband is provided in Fig 8. The
lower sideband is located in the high-
numbered bins and the upper side-
band is located in the low-numbered
bins. To save time, I only zero the num-
ber of bins contained in the FFTBins
variable.
FFT Fast-Convolution
Filtering Magic
Every DSP text I have read on
single-sideband modulation and de-
modulation describes the IF sampling
approach. In this method, the A/D con-
verter samples the signal at an IF such
as 40 kHz. The signal is then quadra-
ture down-converted in software to
baseband and filtered using finite im-
pulse response (FIR)9 filters. Such a
system was described in Doug Smith’s
QEX article called, “Signals, Samples,
and Stuff: A DSP Tutorial (Part 1).”10
Fig 10—FFT fast convolution filtering output. When the filter-magnitude coefficients are
With this approach, all processing is multiplied by the signal-bin values, the resulting output bins contain values only within
done in the time domain. the pass-band of the filter.
For the PC SDR, I chose to use a
very different approach called FFT
fast-convolution filtering (also called
FFT convolution) that performs all fil- Public Static Sub CalcFilter(FLow As Long, FHigh As Long)
tering functions in the frequency do- Static Rh(NFFT) As Double ‘Impulse response for bandpass filter
main.11 An FIR filter performs convo- Static Ih(NFFT) As Double ‘Imaginary set to zero
Static reH(NFFT) As Double ‘Real part of filter response
lution of an input signal with a filter
Static imH(NFFT) As Double ‘Imaginary part of filter response
impulse response in the time domain.
Convolution is the mathematical Erase Ih
means of combining two signals (for
example, an input signal and a filter Fh = FHigh / Fs ‘Compute high and low cutoff
impulse response) to form a third sig- Fl = FLow / Fs ‘as a fraction of Fs
BinSize = Fs / NFFT ‘Compute FFT Bin size in Hz
nal (the filtered output signal).12 The
time-domain approach works very FFTBins = (FHigh / BinSize) + 50 ‘Number of FFT Bins in filter width
well for a small number of filter taps.
What if we want to build a very-high- order = NFFT ‘Compute order as NFFT power of 2
performance filter with 1024 or more Dim O As Long
taps? The processing overhead of the For O = 1 To 16 ‘Calculate the filter order
FIR filter may become prohibitive. It order = order \ 2
turns out that an important property If order = 1 Then
of the Fourier transform is that con- order = O
volution in the time domain is equal Exit For
End If
to multiplication in the frequency do- Next
main. Instead of directly convolving
the input signal with the windowed ‘Calculate infinite impulse response bandpass filter coefficients
filter impulse response, as with a FIR ‘with window
filter, we take the respective FFTs of nspdFirBandpass Fl, Fh, Rh, FILTERTAPS, NSP_WinBlackmanOpt, 1
the input signal and the filter impulse
‘Compute the complex frequency domain of the bandpass filter
response and simply multiply them nspzrFftNip Rh, Ih, reH, imH, order, NSP_Forw
together, as shown in Fig 9. To get back nspdbrCartToPolar reH, imH, filterM, filterP, NFFT
to the time domain, we perform the
inverse FFT of the product. FFT con- End Sub
volution is often faster than direct con-
volution for filter kernels longer than Fig 11—Code for the generating bandpass filter coefficients in the frequency domain.

Nov/Dec 2002 31
equal in length to the sum of the in- aging, digital squelch and spectrum bandwidth noise input and FFT aver-
put samples plus the filter taps mi- display. aging of the signal over several sec-
nus one. I will not attempt to explain Fig 14 shows the actual spectral onds. This provides a good picture of
the concept here because it is best de- output of a 500-Hz filter using wide- the frequency response and shape of
scribed in the references.13
Fig 11 provides the source code for
producing the frequency-domain
band-pass filter coefficients. The nspdbMpy2 filterM, M, NFFT ‘Multiply Magnitude Bins
CalcFilter subroutine is passed the
low-frequency cutoff, FLow, and the nspdbAdd2 filterP, P, NFFT ‘Add Phase Bins
high-frequency cutoff, FHigh, for the
filter response. The cutoff frequencies Fig 12—FFT fast convolution filtering code using polar vectors.
are then converted to their respective
fractions of the sampling rate for use
by the filter-generation routine,
nspdFirBandpass. The FFT order is ‘Compute: RealIn(s) = (RealOut(s) * reH(s)) - (ImagOut(s) * imH(s))
also determined in this subroutine, nspdbMpy3 RealOut, reH, RealOut_1, NFFT
based on the size of the FFT, NFFT. nspdbMpy3 ImagOut, imH, ImagOut_1, NFFT
nspdbSub3 RealOut_1, ImagOut_1, RealIn, NFFT ‘RealIn for IFFT
The nspdFirBandpass computes the
impulse response of the band-pass fil- ‘Compute: ImagIn(s) = (RealOut(s) * imH(s)) + (ImagOut(s) * reH(s))
ter of bandwidth Fl() to Fh() and a nspdbMpy3 RealOut, imH, RealOut_2, NFFT
length of FILTERTAPS. It then places nspdbMpy3 ImagOut, reH, ImagOut_2, NFFT
the result in the array variable Rh(). nspdbAdd3 RealOut_2, ImagOut_2, ImagIn, NFFT ‘ImagIn for IFFT
The NSP_WinBlackmanOpt causes
the impulse response to be windowed Fig 13—Alternate FFT fast convolution filtering code using cartesian vectors.
by a Blackman window function. For
a discussion of windowing, refer to the
DSP Guide.14 The value of “1” that is
passed to the routine causes the re-
sult to be normalized.
Next, the impulse response is con-
verted to the frequency domain by
nspzrFftNip. The input parameters
are Rh(), the real part of the impulse
response, and Ih(), the imaginary part
that has been set to zero. NSP_Forw
tells the routine to perform the for-
ward FFT. We next convert the fre-
quency-domain result of the FFT, reH()
and imH(), to polar form using the
nspdbrCartToPolar routine. The filter
magnitudes, filterM(), and filter phase,
filterP(), are stored for use in the FFT
fast convolution filter. Other than
when we manually change the band-
pass filter selection, the filter response
does not change. This means that we
only have to calculate the filter re-
sponse once when the filter is first se-
lected by the user.
Fig 12 provides the code for an FFT
fast-convolution filter. Using the Fig 14—Actual 500-Hz CW filter pass-band display. FFT fast-convolution filtering is used
nspdbMpy2 routine, the signal-spec- with 2048 filter taps to produce a 1.05 shape factor from 3 dB to 60 dB down and over
trum magnitude bins, M(), are multi- 120 dB of stop-band attenuation just 250 Hz beyond the 3 dB points.
plied by the filter frequency-response
magnitude bins, filterM(), to generate
the resulting in-place filtered magni- ‘Convert polar to cartesian
nspdbrPolarToCart M, P, RealIn, ImagIn, NFFT
tude-response bins, M(). We then use
nspdbAdd2 to add the signal phase ‘Inverse FFT to convert back to time domain
nspzrFftNip RealIn, ImagIn, RealOut, ImagOut, order, NSP_Inv
bins, P(), to the filter phase bins,
filterP(), with the result stored in- ‘Overlap and Add from last FFT/IFFT: RealOut(s) = RealOut(s) + Overlap(s)
place in the filtered phase-response nspdbAdd3 RealOut, IOverlap, RealOut, FILTERTAPS - 2
nspdbAdd3 ImagOut, QOverlap, ImagOut, FILTERTAPS - 2
bins, P(). Notice that FFT convolution
can also be performed in Cartesian ‘Save Overlap for next pass
For S = BLKSIZE To NFFT - 1
coordinates using the method shown IOverlap(S - BLKSIZE) = RealOut(S)
in Fig 13, although this method re- QOverlap(S - BLKSIZE) = ImagOut(S)
quires more computational resources. Next
Other uses of the frequency-domain
magnitude values include FFT aver- Fig 15—Inverse FFT and overlap/add code.

32 Nov/Dec 2002
the filter. The shape factor of the 2048- ciated with windowing the signal be- flag, the inverse FFT is performed by
tap filter is 1.05 from the 3-dB to the fore performing the FFT. To overcome nspzrFftNip, which places the time-
60-dB points (most manufacturers such windowing attenuation, it is typi- domain outputs in RealOut() and
measure from 6 dB to 60 dB, a more cal to apply a 50-75% overlap in the ImagOut(), respectively. As discussed
lenient specification). Notice that the time-domain sampling process and previously, we must now overlap and
stop-band attenuation is greater than average the FFTs in the frequency add a portion of the signal from the
120 dB at roughly 250 Hz from the domain. I would appreciate comments previous capture cycle as described in
3-dB points. This is truly a brick-wall from knowledgeable readers on this the DSP Guide (see Note 13).
filter! hypothesis. Ioverlap() and Qoverlap() store the in-
An interesting fact about this phase and quadrature overlap signals
method is that the window is applied The IFFT and Overlap/Add— from the last pass to be added to the
to the filter impulse response rather Conversion Back to the Time new signal block using the nspdbAdd3
than the input signal. The filter re- Domain routine.
sponse is normalized so signals within Before returning to the time do-
the passband are not attenuated in the main, we must first convert back to Digital AGC with
frequency domain. I believe that this Cartesian coordinates by using Variable Hang Time
normalization of the filter response nspdbrPolarToCart as illustrated in The digital AGC code in Fig 16 pro-
removes the usual attenuation asso- Fig 15. Then by setting the NSP_Inv vides fast-attack and -decay gain

If AGC = True Then

‘If true increment AGCLoop counter, otherwise reset to zero


AGCLoop = IIf(AGCLoop < AGCHang - 1, AGCLoop + 1, 0)

nspdbrCartToPolar RealOut, ImagOut, M, P, BLKSIZE ‘Envelope Polar Magnitude

Vpk = nspdMax(M, BLKSIZE) ‘Get peak magnitude

If Vpk <> 0 Then ‘Check for divide by zero


G(AGCLoop) = 16384 / Vpk ‘AGC gain factor with 6 dB headroom
Gain = nspdMin(G, AGCHang) ‘Find peak gain reduction (Min)
End If

If Gain > MaxGain Then Gain = MaxGain ‘Limit Gain to MaxGain

If Gain < PrevGain Then ‘AGC Gain is decreasing


GainStep = (PrevGain - Gain) / 44 ’44 Sample ramp = 1 ms attack time
For S = 0 To 43 ‘Ramp Gain down over 1 ms period
M(S) = M(S) * (PrevGain - ((S + 1) * GainStep))
Next
For S = 44 To BLKSIZE - 1 ‘Multiply remaining Envelope by Gain
M(S) = M(S) * Gain
Next
Else
If Gain > PrevGain Then ‘AGC Gain is increasing
GainStep = (Gain - PrevGain) / 44 ’44 Sample ramp = 1 ms decay time
For S = 0 To 43 ‘Ramp Gain up over 1 ms period
M(S) = M(S) * (PrevGain + ((S + 1) * GainStep))
Next
For S = 44 To BLKSIZE - 1 ‘Multiply remaining Envelope by Gain
M(S) = M(S) * Gain
Next
Else
nspdbMpy1 Gain, M, BLKSIZE ‘Multiply Envelope by AGC gain
End If
End If

PrevGain = Gain ‘Save Gain for next loop

nspdbThresh1 M, BLKSIZE, 32760, NSP_GT ‘Hard limiter to prevent overflow

End If

Fig 16 – Digital AGC code.

Nov/Dec 2002 33
control with variable hang time. Both of 46 ms. PC SDR provides hang-time have the magnitudes stored in M(), it
attack and decay occur in approxi- loop settings of 3 (fast, 132 ms), 5 (me- is a simple matter to find the peak
mately 1 ms, but the hang time may dium, 230 ms), 7 (slow, 322 ms) and 22 magnitude and store it in Vpk with the
be set to any desired value in incre- (long, 1.01 s). The hang-time setting is function nspdMax. After checking to
ments of 46 ms. I have chosen to imple- stored in the AGCHangvariable. Once prevent a divide-by-zero error, we com-
ment the attack/decay with a linear the hang-time counter resets, the de- pute a gain factor relative to 50% of
ramp function rather than an expo- cay occurs on a 1-ms linear slope. the full-scale value. This provides 6 dB
nential function as described in DSP To determine the AGC gain require- of headroom from the signal peak to
communications texts.15 It works ex- ment, we must detect the envelope of the full-scale output value of the DAC.
tremely well and is intuitive to code. the demodulated signal. This is easily On each pass, the gain factor is stored
The flow diagram in Fig 17 outlines accomplished by converting from Car- in the G() array so that we can find
the logic used in the AGC algorithm. tesian to polar coordinates. The value the peak gain reduction during the
Refer to Figs 16 and 17 for the fol- of M() is the envelope, or magnitude, hang-time period using the nspdMin
lowing description. First, we check to of the signal. The phase vector can be function. The peak gain-reduction fac-
see if the AGC is turned on. If so, we ignored insofar as AGC is concerned. tor is then stored in the Gain variable.
increment AGCLoop, the counter for We will need to save the phase val- Note that Gain is saved as a ratio and
AGC hang-time loops. Each pass ues, though, for conversion back to not in decibels, so that no log/antilog
through the code is equal to a hang time Cartesian coordinates later. Once we conversion is needed.

Fig 17—Digital AGC flow diagram.

34 Nov/Dec 2002
The next step is to limit Gain to the The Fully Functional SDR-1000 • A real-time spectrum display with
MaxGain value, which may be set by Software one-click frequency tuning using a
the user. This system functions much The SDR-1000, my nomenclature mouse.
like an IF-gain control allowing Gain for the PC SDR, contains a significant • Dual, independent VFOs with data-
to vary from negative values up to the amount of code not illustrated here. I base readout of band-plan alloca-
MaxGain setting. Although not pro- have chosen to focus this article on the tion. The user can easily access and
vided in the example code, it is a essential DSP code necessary for modify the band-plan database.
simple task to create a front panel con- modulation and demodulation in the • Mouse-wheel tuning with the abil-
trol in Visual Basic to manually set frequency domain. As time permits, I ity to change the tuning rate with a
the MaxGain value. hope to write future articles that delve click of the wheel.
Next, we determine if the gain must into other interesting aspects of the • A multifunction digital- and analog-
be increased, decreased or left un- software design. readout meter for instantaneous
changed. If Gain is less than PrevGain Fig 19 shows the completed front- and average signal strength, AGC
(that is the Gain setting from the sig- panel display of the SDR-1000. I have gain, ADC input signal and DAC
nal block stored on the last pass had a great deal of fun creating—and output signal levels.
through the code), we ramp the gain modifying many times—this user in- • Extensive VFO, band and mode con-
down linearly over 44 samples. This terface. Most features of the user in- trol. The band-switch buttons also
yields an attack time of approximately terface are intuitive. Here are some provide a multilevel memory on the
1 ms at a 44,100-Hz sampling rate. interesting capabilities of the SDR- same band. This means that by
GainStep is the slope of the ramp per 1000: pressing a given band button
sample time calculated from the
PrevGain and Gain values. We then
incrementally ramp down the first 44
samples by the GainStep value. Once Private Sub cmdAGC_Click(Index As Integer)
ramped to the new Gain value, we
multiply the remaining samples by the MaxGain = 1000 ‘Maximum digital gain = 60dB
fixed Gain value.
If Gain is increasing from the Select Case Index
PrevGain value, the process is simply
Case 0
reversed. If Gain has not changed, all
AGC = True
samples are multiplied by the current AGCHang = 3 ‘3 x 0.04644 sec = 139 ms
Gain setting. After the signal block has Case 1
been processed, Gain is saved in AGC = True
PrevGain for the next signal block. AGCHang = 7 ‘7 x 0.04644 sec = 325 ms
Finally, nspdbThresh1 implements a Case 2
hard limiter at roughly the maximum AGC = False ‘AGC Off
output level of the DAC, to prevent End Select
overflow of the integer-variable out-
put buffers. End Sub

Send the Demodulated or Private Sub cmdFilter_Click(Index As Integer)


Modulated Signal to the
Output Buffer Select Case Index
The final step is to format the pro-
cessed signal for output to the DAC. Case 0
When receiving, the RealOut() signal CalcFilter 300, 3000 ‘2.7KHz Filter
is copied, sample by sample, into both Case 1
CalcFilter 500, 1000 ‘500Hz Filter
the left and right channels. For
Case 2
transmiting, RealOut() is copied to the
CalcFilter 700, 800 ‘100Hz Filter
right channel and ImagOut() is cop- End Select
ied to the left channel of the DAC. If
binaural receiving is desired, the I and End Sub
Q signal can optionally be sent to the
right and left channels respectively, Private Sub cmdMode_Click(Index As Integer)
just as in the transmit mode.
Select Case Index
Controlling the
Demonstration Code Case 0 ‘Change mode to USB
The SDR demonstration code (see SSB = True
Note 3) has a few selected buttons for USB = True
setting AGC hang time, filter selection Case 1 ‘Change mode to LSB
and sideband selection. The code for SSB = True
these functions is shown in Fig 18. The USB = False
code is self-explanatory and easy to End Select
modify for additional filters, different
hang times and other modes of opera- End Sub
tion. Feel free to experiment.
Fig 18 – Control code for the demonstration front panel.

Nov/Dec 2002 35
multiple times, it will cycle through
the last three frequencies visited on
that band.
• Virtually unlimited memory capabil-
ity is provided through a Microsoft
Access database interface. The
memory includes all key settings of
the radio by frequency. Frequencies
may also be grouped for scanning.
• Ten standard filter settings are
provided on the front panel, plus in-
dependent, continuously variable
filters for both CW and SSB.
• Local and UTC real-time clock dis-
plays.
• Given the capabilities of Visual
Basic, the possibility for enhance-
ment of the user interface is almost
Fig 19—SDR-1000 front-panel display.
limitless. The hard part is “shooting
the engineer” to get him to stop de-
signing and get on the air. gladly put you in contact with those 8R. Lyons, Understanding Digital Signal
There is much more that can be who have built boards. I also plan to Processing (Reading, Massachusetts:
accomplished in the DSP code to cus- have a Web site up and running soon Addison-Wesley, 1997) pp 133, 330-340,
tomize the PC SDR for a given appli- to provide ongoing updates on the 429-430.
9D. Smith, KF6DX, Digital Signal Processing
cation. For example, Leif Åsbrink, project.
SM5BSZ, is doing interesting weak- Technology (Newington, Connecticut:
signal moonbounce work under ARRL, 2001; ISBN: 0-87259-819-5; Order
Notes #8195) pp 4-1 through 4-15.
Linux.16 1G. Youngblood, AC5OG, “A Software De-
10 D. Smith, KF6DX, “Signals, Samples and
Also, Bob Larkin, W7PUA, is using fined Radio for the Masses, Part 1,” QEX , Stuff: A DSP Tutorial (Part 1),” QEX (Mar/
the DSP-10 he first described in the Jul/Aug 2002, pp 13-21. Apr 1998), pp 5-6.
2G. Youngblood, AC5OG, “A Software De-
September, October and November 11 Information on FFT convolution may be
1999 issues of QST to experiment with fined Radio for the Masses, Part 2,” QEX , found in the following references:
Sep/Oct 2002, pp 10-18.
weak-signal, over-the-horizon micro- 3The demonstration source code for this R. Lyons, Understanding Digital Signal Pro-
wave propagation.17 project may be downloaded from ARRLWeb
cessing, (Addison-Wesley, 1997) pp 435-
436; M. Frerking, Digital Signal Processing
at www.arrl.org/qexfiles/. Look for in Communication Systems (Boston, Mas-
Coming in the Final Article 1102Youngblood.zip.
4The functions of the Intel Signal Processing sachusetts: Kluwer Academic Publishers)
In the final article, I plan to de- pp 202-209; and S. Smith, The Scientist
scribe ongoing development of the Library are now provided in the Intel Perfor- and Engineer’s Guide to Digital Signal Pro-
SDR-1000 hardware. (Note: I plan to mance Primitives (Version 3.0, beta) pack- cessing (San Diego, California: California
delay the final article so that I am able age for Pentium processors and Itanium Technical Publishing) pp 311-318.
architectures. An evaluation copy of IPP is 12 S. Smith, The Scientist and Engineer’s
to complete the PC board layout and
available free to be downloaded from Guide to Digital Signal Processing (Califor-
test the hardware design.) Included developer.intel.com/software/products/
will be a tradeoff analysis of gain dis- nia Technical Publishing) pp 107-122. This
ipp/ipp30/index. htm.Commercial use of is available for free download at www.
tribution, noise figure and dynamic IPP requires a full license. Do not use IPP DSPGuide.com.
range. I will also discuss various ap- with the demo code because it has only 13Overlap/add method: Ibid, Chapter 18,
proaches to analog AGC and explore been tested on the previous signal pro- pp 311-318; M. Freirking, pp 202-209.
frequency control using the AD9854 cessing library. 14 S. Smith, Chapter 9, pp 174-177.
5D. Hershberger, W9GR, and Dr S. Reyer,
quadrature DDS. 15 M. Frerking, Digital Signal Processing in
Several readers have indicated in- WA9VNJ, “Using The LMS Algorithm Communication Systems, (Kluwer Aca-
For QRM and QRN Reduction,” QEX ,
terest in PC boards. To date, all proto- demic Publishers) pp 237, 292-297, 328,
Sep 1992, pp 3-8.
type work has been done using 6D. Hall, KF4KL, “Spectral Subtraction for 339-342, 348.
16 See Leif Åsbrink’s, SM5BSZ, Web site at
“perfboards.” At least one reader has Eliminating Noise from Speech,” QEX ,
produced a circuit board, that person ham.te.hik.se/homepage/sm5bsz/.
Apr 1996, pp 17-19. 17 See Bob Larkin’s, W7PUA, homepage at
is willing to make boards available to 7J. Bloom, KE3Z, “Correlation of Sampled
www.proaxis.com/~boblark/dsp10.htm.
other readers. If you e-mail me, I will Signals,” QEX , Feb 1996, pp 24-28.


36 Nov/Dec 2002

You might also like