hmwk 5655 15 set3 sp2020mwickert/ece5655/lecture_notes/arm/...ece 5655/4655 page 3 assignment #3 be...

10
ECE 5655/4655 Laboratory Problems Assignment #3 Due March ~20, 2020 Make Note of the Following: This assignment will be written up more like a lab report Include the observations made from the scope etc., also include a block dia- gram of how the test equipment is configured around the Cypress FM4 As appropriate, use the Digilent Analog Discovery for any and all measure- ment needs; ask for input if you feel uncertain about capabilities Analog I/O Using the Wolfson Audio Codec 1. In this problem you will perform a number of experiments using a basic audio loop-thru project similar to the Slider GUI zip package linked under Appendix A. The ZIP package for Lab3 contains the main module fm4_loop_intr_GUI.c useful for this purpose. //White noise generator for noise testing int32_t rand_int(void) { static int32_t a = 100001; a = (a*125) % 2796203; return a; } For this part of the exercise use a 48 kHz sampling rate on the Cypress FM4. Later you will use and audio capture bandwidth that well exceeds the 24 kHz folding frequency when using a PC sound system sampling at 96 ksps. a.) In the appropriate ISR routine pass the input samples directly to the output. Input a sinusoid from an Agilent 33600A/Keysight DSOX6004A function generator. The Analog Discovery also works here. Determine the maximum input level of the input A/D and the maximum output level of the D/A. This will likely require that you perform some scaling experiments as you pass samples read from the A/D directly over to the D/A. Using a GUI slider P_vals[] variable is helpful here. Do not alter the default codec gain settings for this experiment. Note these settings are hidden away in the codec library, but you do have access to them. The idea is to determine the exact dynamic range values for the default settings for future reference. I realize that these values can change if the codec attenuator settings are altered, but this is a starting point. The overload point for both the input and output signal should be observable on a scope connected to the DAC output. b.) Using the same configuration as in part (a), now apply an pulse train at the input and measure the rising edge time delay in going from the analog input to the analog output. Be sure to use a long enough period so that additional cycles do not creep in should the time delay be longer than you anticipate. Note the time delay is clearly a function of the sampling clock, but with this

Upload: others

Post on 29-Jul-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: hmwk 5655 15 set3 sp2020mwickert/ece5655/lecture_notes/ARM/...ECE 5655/4655 Page 3 Assignment #3 be spectrum analyzed using Python. You may need to scale the output of the uniform

ECE

5655

/465

5 La

bora

tory

Pro

blem

sAssignment #3Due March ~20, 2020

Make Note of the Following:• This assignment will be written up more like a lab report• Include the observations made from the scope etc., also include a block dia-

gram of how the test equipment is configured around the Cypress FM4• As appropriate, use the Digilent Analog Discovery for any and all measure-

ment needs; ask for input if you feel uncertain about capabilities

Analog I/O Using the Wolfson Audio Codec1. In this problem you will perform a number of experiments using a basic audio

loop-thru project similar to the Slider GUI zip package linked under AppendixA. The ZIP package for Lab3 contains the main module fm4_loop_intr_GUI.cuseful for this purpose.//White noise generator for noise testingint32_t rand_int(void){

static int32_t a = 100001;a = (a*125) % 2796203;return a;

}

For this part of the exercise use a 48 kHz sampling rate on the Cypress FM4.Later you will use and audio capture bandwidth that well exceeds the 24 kHzfolding frequency when using a PC sound system sampling at 96 ksps. a.) In the appropriate ISR routine pass the input samples directly to the output.

Input a sinusoid from an Agilent 33600A/Keysight DSOX6004A functiongenerator. The Analog Discovery also works here. Determine the maximuminput level of the input A/D and the maximum output level of the D/A. Thiswill likely require that you perform some scaling experiments as you passsamples read from the A/D directly over to the D/A. Using a GUI sliderP_vals[] variable is helpful here. Do not alter the default codec gain settingsfor this experiment. Note these settings are hidden away in the codec library,but you do have access to them. The idea is to determine the exact dynamicrange values for the default settings for future reference. I realize that thesevalues can change if the codec attenuator settings are altered, but this is astarting point. The overload point for both the input and output signal shouldbe observable on a scope connected to the DAC output.

b.) Using the same configuration as in part (a), now apply an pulse train at theinput and measure the rising edge time delay in going from the analog inputto the analog output. Be sure to use a long enough period so that additionalcycles do not creep in should the time delay be longer than you anticipate.Note the time delay is clearly a function of the sampling clock, but with this

Page 2: hmwk 5655 15 set3 sp2020mwickert/ece5655/lecture_notes/ARM/...ECE 5655/4655 Page 3 Assignment #3 be spectrum analyzed using Python. You may need to scale the output of the uniform

ECE 5655/4655 Page 2 Assignment #3

signal sample processing loop, the latency should be minimal. Since the ADC pathwayinverts the signal apply a -1 in code to make the pulse train right-side up will be helpfulwhen observing the final output on the scope.

c.) Repeat (b) when using the DMA frames-based pass-through loop code found in the mod-ule, fm4_loop_dma_GUI.c, with a frame size of 128 (default) and 512 or 256 (see Chapter 5notes for details on changing this). Note from the analysis of the ping/pong buffer schemein notes Chapter 5, you know that the delay is at least two buffer lengths. Here you againare making the measurement in the analog domain using a scope.

d.) Using the vector network analyzer, see Figure 1, measure the frequency response magni-tude in dB as the analog output over the input (say using analyzer ports B/R). As an alter-native you can use the network analyzer capability of the Analog Discovery. Thefrequency range you sweep over should be consistent with the sampling frequency. Usewhat you learned in part (a) to properly set the input level to the A/D. A good safe level forthe input is 80-90% of full-scale.

Plots from the 4395A can be obtained in several ways. A reliable approach is to usethe instrument capability to save an Excel data file or a tiff image file to the 4395A 3.5infloppy drive. There are portable USB floppy drives in the lab for moving the captured filesto a PC. When using the Analog Discovery export the raw data as CSV and bring into theJupyter notebook for plotting, or export an image file from the Analog Discovery.

Comment on the locations of the critical frequencies, e.g., lower and upper band edgesas appropriate, with respect to known A/D antialiasing filter characteristics in combinationwith the known reconstruction filter characteristics. Try to verify the passband ripple thatwe know exits in both the A/D and D/A signal paths.

2. In this problem you will again work with the WM8731 codec, but this time you will use a uni-form white noise generator in C as a wideband signal source. The output of the D/A will then

Agilent 4395A

0 1 . . . .RF OutLine R BA

Activ

e Pr

obe/

Adap

ter

41802AAdapterpwrUSB

Line In

Line Out

Cypress FM4

Activ

e Pr

obe/

Adap

ter

WolfsonCodec

Cortex-M4Real-TimeDSP Platform

Figure 1: Agilent 4395A vector network analyzer interface to theWolfson codec.

Page 3: hmwk 5655 15 set3 sp2020mwickert/ece5655/lecture_notes/ARM/...ECE 5655/4655 Page 3 Assignment #3 be spectrum analyzed using Python. You may need to scale the output of the uniform

ECE 5655/4655 Page 3 Assignment #3

be spectrum analyzed using Python. You may need to scale the output of the uniform randomnumber generator before passing it to the codec output function. Suggestions for the FM4 are:

void PRGCRC_I2S_IRQHandler(void) {

union WM8731_data sample;int16_t xL, xR;

gpio_set(DIAGNOSTIC_PIN,HIGH);// Get L/R codec sample

sample.uint32bit = i2s_rx();

// Breakout and then process L and R samples with // slider parameters for gain control // Pass noise through the left channel xL = (float32_t)(((short)rand_int32())>>2); // scale noise by 4 xL *= FM4_GUI.P_vals[0]; //xL = (int16_t) (FM4_GUI.P_vals[0] * sample.uint16bit[LEFT]); xR = (int16_t) (FM4_GUI.P_vals[1] * sample.uint16bit[RIGHT]);

// Return L/R samples to codec via C union sample.uint16bit[LEFT] = xL; sample.uint16bit[RIGHT] = xR; i2s_tx(sample.uint32bit);

NVIC_ClearPendingIRQ(PRGCRC_I2S_IRQn);

gpio_set(DIAGNOSTIC_PIN,LOW);}

To ignore the A/D samples and use the noise generator samples instead, comment and uncom-ment lines as shown above. When this program is run the noise generator is output to the D/A,which also includes the a lowpass reconstruction filter (part of the delta-sigma D/A). In thediscrete-time domain we know that the power spectrum will be flat (white). Since here thenoise generator output is connected directly to the D/A (see Figure 2), the PSD of the outputshould have shape corresponding to the magnitude squared of the D/A lowpass filter fre-quency response, in cascade with perhaps other analog circuit poles and zeros.

Rather than using the analog spectrum analyzer as in Problem 1, this time we will use thePC audio system to capture a finite record of D/A output. The audio capture will be madeusing the DSP_io_stream class found in sk_dsp_comm.pyaudio_helper. The details can befound in the Jupyter notebook Assignment3_sp2018.ipynb, which is inside the Python folderof the ZIP package. A 30 second capture at 48 kHz seems to work well. Since the FM4 sam-pling rate was reduced to 32 kHz, the capture bandwidth is wide enough to see the audio

WhiteNoise

IdealD/A

Board

Sin f No f=

Sout f No Hshape f 2=

WolfsonAnalogOutput

y n ya t

Figure 2: Model for the noise spectrum produced at the codec output.

ShapingFilter

Composite shaping filter

Page 4: hmwk 5655 15 set3 sp2020mwickert/ece5655/lecture_notes/ARM/...ECE 5655/4655 Page 3 Assignment #3 be spectrum analyzed using Python. You may need to scale the output of the uniform

ECE 5655/4655 Page 4 Assignment #3

codec filtering action beyond kHz.Using pyaudio_helper to Measure Frequency Response Using White Noise ExcitationRather than using the network analyzer as in Problems 1–2, this time you will use the PC dig-ital audio system to capture a finite record of DAC output as shown in Figure 2. Use the same

FIR filter as used in Problem 2. The capture tool follows from Lab 2 using pyaudio_helper. A10 second capture at 96 kHz seems to work well. Since the sampling rate is 482 ksps, the 96kHz provides a 2x oversampling to see the full response of the filter in cascade with the D/A(sigma-delta) reconstruction filter frequency response. The Lab 4 Jupyter notebook, FIR Fil-ter Design and C Headers.ipynb, contains audio capture details specific for the needs of thislab. Sample capture .wav files and plots are included.

To get this setup you first need to add a function to your code so that you can digitally gen-erate a noise source as the input to your filtering algorithm. Add the following uniform ran-dom number generator function to the ISR code module:

// Uniformly distributed noise generatorint32_t rand_int32(void){ static int32_t a_start = 100001;

a_start = (a_start*125) % 2796203;

return a_start;

}

Note the code is already in place in the project you extract from the Lab 4 zip file. Now youwill drive your filter algorithm with white noise generated via the function rand_int32(). Inyour filter code you will replace the read from the audio code with something like to follow-

fs 2 16=

FM4 PCSound

Card or Capture ~10 secondsusing 96 kpssampling rate

Fill a capture bufferin a DSP_IO object

Apply psd()to createfrequencyresponseestimate. f

|H(f)|dB

PCWorkstation/

To Line/Mic Input

Out

pyaudio_helpercapture

Run whitenoise codeas DAC/filter input

Save .wavand est.PSD inJupyter

notebook

Figure 2: Waveform capture using a PC audio dongle and pyaudio_helper.

AudioDongle

DSP_IO.data_capture

Signal samples are in:

y t

y n

Pyy yy ej =

w2 H ej

2

proportional to

Laptop

Page 5: hmwk 5655 15 set3 sp2020mwickert/ece5655/lecture_notes/ARM/...ECE 5655/4655 Page 3 Assignment #3 be spectrum analyzed using Python. You may need to scale the output of the uniform

ECE 5655/4655 Page 5 Assignment #3

ing:

# Replace ADC with internal noise scaled//x = (float32_t) sample.uint16bit[LEFT];x = (float32_t) (rand_int32()>>4);

The procedure is to use pyaudio_helper to obtain a capture buffer of noise samples of about10s duration at 96 ksps. Ultimately you will have a .wav file archive that you can use forspectral analysis. The objective is to estimate the power spectral density of the filter output,denoted as in Figure 2. Note includes the frequency response of both the D/Aand the USB audio system. To estimate the power spectral density we use the matplotlibfunction psd(), wrapped to provide more convenient output arrays using

Py_wav, f_wav = ss.my_psd(y, NFFT, fs)

The spectral analysis function implements Welch’s method of averaged periodograms. Sup-pose that the .wav file is saved as FIR_4tap_MA.wav, then a plot of the frequency responsecan be created as follows:

fs,y_wav = ss.from_wav('FIR_4tap_MA.wav')# Choose channel 0 or 1 as appropriatePy_wav, f_wav = ss.my_psd(y_wav[:,0],2**10,fs/1e3)# Normalize using a reasonable value close to f = 0, but not zeroplot(f_wav,10*log10(Py_wav/Py_wav[10]))

One condition to watch out for is overloading of either the PC sound card line/mic input of ifusing the Sabrent USB sound card, the mic input. Figure 3 describes how to manage signalslevels from the filter output in the FM4 IRQ into the PC sound system internal level.

In summary, using the procedure described above, obtain a Python plot of the frequencyresponse magnitude in dB versus frequency of the FM4 DAC output channel. Normalize the

y n y n

Win10 Configure Audio Record Levels from the USB Audio Device Mic Input

Sabrent USB Audio Device

Mic In

To PC

FM4

Right-click speaker on lower right task bar, then Open

Sound settings

Avoid mic input over-load by set-ting the output gain slider on the FM4 to 0.1

With the Test button pressed you will see the amplitude level fluctuating beneath the slider. Avoid overflow

Choose the USB audio device

Figure 3: Controlling the input level to USB sound card.

Page 6: hmwk 5655 15 set3 sp2020mwickert/ece5655/lecture_notes/ARM/...ECE 5655/4655 Page 3 Assignment #3 be spectrum analyzed using Python. You may need to scale the output of the uniform

ECE 5655/4655 Page 6 Assignment #3

filter gain so that it is unity at its peak frequency response magnitude.3. Using the FM4 with Wolfson codec, and sampling rate of 48 kHz, generate a sinusoidal oscil-

lator that uses GUI slider app (FM4_GUI_slider.exe) that connects via the serial port. Writeyour code so that the frequency of oscillation can be tuned from 100 Hz to 20 kHz in 100 Hzsteps using one of the six P_vals[] available. The frequency determining variable will actu-ally should be a float32_t variable. The approach to generating the variable frequency oscil-lator is via the equation

where is the sample spacing, , and is the analog oscillation frequency. Theangular change between samples is denoted by . If we let , thenwe can write that

For more information on this technique see Chapter 5 of the Reay text. In C code we can builda float version of this using the library <math.h> for the trig function (this will not be particu-larly efficient in terms of CPU cycles, but will be interesting to investigate). Note: math.h isalso ready included via other headers in the project.

...#define pi 3.141592653589

//set sampling rate to 48 kspsfloat32_t signal = 0.0; //initial value for the signal sfloat32_t f0 = 1000.0; //initial value for oscillation frequencyfloat32_t delta = 0.1308996938995747; //2*pi*1000/48000.float32_t twopi = 2.0*pi;float32_t angle = 0.;...{...// inside interrupt service routine (use sinf() for float vs sin() for double)// or better still use the CMSIS-DSP functions arm_sin_f32() or arm_cos_f32()signal = 15000.0*arm_sin_f32(angle); //scale to half of full scale for short valuesangle += delta; //increment angle by proper delta valueif( angle >= twopi) angle -= twopi; // prevent float overflow by wrapping the phase...//To codec output with casting from float32_t to int16_t}...

The A/D inputs will not be used for anything in this example. The output only needs to appearon one channel, left or right.

4. Using the FM4 with Wolfson codec, and sampling rate of 48 kHz, write sampling loop codethat performs the following:

.

Your code need only implement this operation for one of the two I/O channels. Explain usingDSP math what is happening in the frequency domain. Explain what you hear when yousweep a sinusoid across the input and listen to the result at the output. I will expect a demo of

s n s nT 2f0nT sin 2f0fs----n

sin n sin= = = =

T fs 1 T= f0 2 f0 fs = n n=

n 1+ n 1+ n + n += = =

y n 1– nx n =

Page 7: hmwk 5655 15 set3 sp2020mwickert/ece5655/lecture_notes/ARM/...ECE 5655/4655 Page 3 Assignment #3 be spectrum analyzed using Python. You may need to scale the output of the uniform

ECE 5655/4655 Page 7 Assignment #3

this in the lab.To help you understand what is going when you multiply a discrete-time signal by con-sider

If is a discrete-time sinusoid signal

where is the sampling rate in Hz, then it follows that

There is more, since the frequency of a sinusoidal signal is unique only on a interval(cosine is a function) and cosine is also an even function, you can write

Hence, it follows that

.

Using Fourier transform theorems this result along with the general result can be obtainedmuch faster. The frequency translation theorem says that

where and here . This points to the notion of flipping the spec-trum about since you already know, or can recall, that the spectrum in the discrete-time domain is periodic with period , that is for any integer k. Torelate these results back to continuous-time signals on the frequency interval , justremember that and .

Variable Time Delay Filter Using a Circular Buffer5. Circular Buffer Background: In the development of finite impulse response filtering (FIR)

you encounter a sum-of-products formula which says the present output, , is formed as

,

in response to the present input and past inputs , whichcan viewed as a linear array , . This array is updated by shifting allarray entries to the right and placing the new present input on the left end at index zero. Thecircular buffer avoids this reshuffling by keeping a pointer to the oldest value [1]. The new-est value is written over the oldest value as each new input, , arrives to be filtered. All

1– n

s n 1– n n cos ejn= = =

x n

x n 0n cos 2 f0 fs cos= =

fs

y n s n x n n 0n coscos= =

12--- 0+ n cos 0– n cos+ =

2mod2

0+ n cos 0+ n 2n– cos=

0 – n cos 0– n cos==

y n 0– n cos=

FT x n ejcn

X ej c–

=

X ej FT x n = c = =

2 X ej k2 X ej =0 fs 2

f 2 fs= 2 f fs=

y n

y n x n k– hFIR k k 0=

MFIR 1–

state k hFIR k k 0=

MFIR 1–

= =

x n x n k– k 1 MFIR 1– =state k 0 k MFIR 1–

x n

Page 8: hmwk 5655 15 set3 sp2020mwickert/ece5655/lecture_notes/ARM/...ECE 5655/4655 Page 3 Assignment #3 be spectrum analyzed using Python. You may need to scale the output of the uniform

ECE 5655/4655 Page 8 Assignment #3

values remain static in the array as the pointer does all of the work. A graphical depiction ofthe linear array and the circular buffer approach is shown Figure 4. To access past values of

the input modulo index arithmetic is needed to step backwards through the array, modulo thearray length. The C language has the operator % for modulo math, but it does not work prop-erly when a negative index occurs. The function

// A mod function that takes negative inputs int16_t pmod(int16_t a, int16_t b){ int16_t ret = a % b; if(ret < 0) ret += b; return ret;}

solves this problem by returning nonnegative indices. A downside of using the circular buf-fer is that that both % and pmod are not single cycle operations. Reshuffling a linear arraytakes multiple clock cycles as well. Which requires fewer total clock cycles depends on thearchitecture factors. In dedicated DSP microprocessors hardware for circular buffer pointercontrol is built-in. On the Cortex-M family this is not the case [1].

Variable Delay Implementation: When implementing a pure delay filter modulo address-ing inefficiency is not a major concern, as a pure delay filter of samples has all zero tapsexcept for a single unity tap, e.g.,

where . Ignoring global variable initialization, the variable delay filtertakes the form

// Begin buffer processing// Write new input over oldest buffer valuecircbuf[ptr] = x;// Calculate delay index working backwardsdelay = (int16_t) FM4_GUI.P_vals[2];y = circbuf[pmod(ptr - delay,N_buff)];// Update ptr to write over the oldest value next time

x n x n 1– x n MFIR 1– –

x n x n 1–

Shift rightas each newsample arrives

Increment thepointer modulothe buffer lengthas each new sample arrives

pointer

x n MFIR 1– –

Increment by one moduloMFIR 1–

x n 2– x n MFIR 2– –

Step backwards toaccess older values; from0 jump up to index MFIR-1

to write new input values over the oldest value

0 1 MFIR 1–

Figure 4: Linear array holds dynamic values versus the circular buffer holdingstatic values with a dynamic pointer.

LinearBuffer

Circ.Buffer

(ptr)

nd

y n x n nd– =

0 nd NFIR 1–

Page 9: hmwk 5655 15 set3 sp2020mwickert/ece5655/lecture_notes/ARM/...ECE 5655/4655 Page 3 Assignment #3 be spectrum analyzed using Python. You may need to scale the output of the uniform

ECE 5655/4655 Page 9 Assignment #3

ptr = (ptr + 1) % N_buff;

a.) Fill in the rest of details in the above code snippets to implement a variable delay that isadjustable from 0 to 10 ms when kHz. The GUI slider control should take integersteps. Notice that since the buffer also holds the present sample value, the length of thebuffer has to be sample longer than you might think to get the desired time delay.

b.) Verify that the delay is adjustable over the expected 10 ms range using the oscilloscope.Show your results to the lab instructor. To make the testing clear input a 50 Hz squarewave turned pulse train by setting the duty cycle to about 5%. A sample display from theAnalog Discovery is shown in Figure 5.

c.) Record the ISR timing to see how efficient the time delay is, in spite of how long the cir-cular buffer is. Nice?

d.) The audio special effect known as flanging1 [2] is created by sinusoidally varying the timedelay at a low frequency. To get a test of this under manual control (slider control), input a1 kHz sinusoid from a bench function generator. Using speakers of earphones listen to thetime delayed output moving the time delay slider control up and down. By changing thetime in real time your compressing and then expanding the time axis, which should makethe tone you hear waver in frequency. Similar to the Doppler effect. Demonstrate this toyour lab instructor.

References[1] Joseph Yiu, The Definitive Guide to ARM Cortex-M3 and Cortex-M4 Processors, third edi-

tion, Newnes, 2014.

[2] Thad B. Welch, Cameron H.G. Wright, and Michael Morrow, Real-Time Digital Signal Pro-cessing from MATLAB to C with the TMS320C6x DSPs, second edition, CRC Press, 2012.

1. https://en.wikipedia.org/wiki/Flanging

fs 48=

DelayCase A

DelayCase B

Input Output

OutputInput

Volts

Volts

Figure 5: AD output from the fully implemented 0–10ms variable delay.

Page 10: hmwk 5655 15 set3 sp2020mwickert/ece5655/lecture_notes/ARM/...ECE 5655/4655 Page 3 Assignment #3 be spectrum analyzed using Python. You may need to scale the output of the uniform

ECE 5655/4655 Page 10 Assignment #3