Lab 3

pdf

School

University of California, San Diego *

*We aren’t endorsed by this school

Course

170

Subject

Aerospace Engineering

Date

Dec 6, 2023

Type

pdf

Pages

18

Uploaded by GeneralFlowerDragon7

Report
MAE 170 [FA23]: LAB 3 Acquiring Signals: A/D Conversion, Sampling, and Aliasing Submit your answers to the questions posed in this lab to gradescope and turnitin via the Canvas course website by 11:59 pm (midnight) the evening before your next lab section. Learning objectives LLO2-1: Learn how to determine the resolution of a signal processing device. LLO2-2: Understand the importance of sampling rate, and be able to predict onset of aliasing and aliased frequencies. LLO2-3: Understand and be able to apply signal conditioning techniques, such as analog filtering. LLO2-4: Understand the origin of, and be able to identify, signal processing artifacts (e.g. from aliasing) LLO2-5: Be able to interpret frequency domain information and apply Fast Fourier transforms (amplitude, shape of typical signals, resolution in frequency domain, sampling rate) LLO2-6: Be able to acquire analog signals with an arduino and/or an oscilloscope and download the information in an automatable fashion (including, where helpful, real-time analysis). LLO2-7: Gain experience with communicating observations and their experimental context via technical writing LLO2-8: Gain experience with presenting information visually in a manner that is accessible and information dense. LLO2-9: Gain experience with norms and ethics in data analysis and presentation.
MAE 170 [FA23]: LAB 3 PRE-LAB: Practice visualizing the effect of aliasing, via the time and frequency domain. To actively see what happens to a discretely sampled single, fixed frequency (~125 Hz) signal as you change the sampling frequency, use Aliasing.mlapp , which is found on canvas under files→Lab 2→Matlab files . View the Arduino Lecture 2 video . View the following Matlab tutorial videos: Using Basic Plotting Functions Processing an Excel file in MATLAB Note: dlmread works in an analogous manner for text files, with varied data delimiters Read the following via the custom course textbook: Part B (Ohm’s and Kirchoff’s laws, parallel and series circuits) Part A.1-3, 7, 8, 13, 14, 15 Review the appendix for this set of lab instructions. We expect that you have read, in detail, the lab instructions before coming to the lab. Much of Part I can be tested, and a portion of Part III completed, before coming into the lab (and it is highly recommended you do so). 2
MAE 170 [FA23]: LAB 3 IN-LAB: Part I: Arduino analog-to-digital (A/D) voltage measurement resolution, and basic Matlab serial data stream reading For this part of the lab, we are going to characterize the A/D voltage measurement resolution of the Arduino analog input channel using the digital multimeter (DMM), and practice reading the Arduino’s serial data stream using Matlab (note that USB = Universal Serial Bus). Construct a voltage divider and potentiometer circuit as is shown in Fig. 1, which will be used to provide an adjustable constant voltage source. Use a 100 k resistor and the potentiometer provided as part of your Arduino kit. Use your digital multimeter to measure the voltage across the potentiometer resistance as you turn the potentiometer knob. Figure 1: Setup to measure Arduino analog input channel A0 A/D resolution, using the built-in 5 V Arduino power supply, with a voltage divider. The yellow box is the DMM. Make sure you set your DMM to measure DC Volts, and that you set the voltage measurement range appropriately. Typically, you want to be at the lowest setting that exceeds your expected measured value. If your DMM measurement is saturating, 3
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
MAE 170 [FA23]: LAB 3 increase the measurement range on your DMM (or vice versa, if your measured signal is too small to achieve satisfactory precision). Be sure to note the units on your DMM display. Upload the following script to the Arduino, which reads the voltage on analog input channel A0, and writes the information to the serial output stream in the format: “data on serial stream in counts, time in microseconds”. Key note: This process is an analog to digital conversion (A/D). Example code: // Arduino serial read script // the setup routine runs once when you press reset: void setup() { // initialize serial communication at 115200 bits per second: Serial.begin(115200); } // the loop routine runs over and over again forever // the loop contains reading the analog in A0 pin and writing the voltage to the serial port // followed by the time in microseconds: void loop() { Serial.print(analogRead(A0)); Serial.print(", "); Serial.println(micros()); } Open the serial monitor under the tools drop down menu in the Arduino IDE. Turn the knob on the potentiometer from left to right and observe how the data in the first column changes. Q1: Is the variable voltage applied to channel A0 an analog or digital signal? Q2: What are the minimum and maximum values in the serial stream (first column, in “counts”, where counts are the Arduino input channel A/D measurement intervals)? What voltages do these minimum/maximum counts correspond to on your DMM? Q3: Given the information in Q2, approximately what is the resolution of your Arduino input channel A0 A/D converter (in volts)? As described in lecture, we can define the resolution via the following equation: 4
MAE 170 [FA23]: LAB 3 , (1) ∆𝑋 = |𝑋 ?𝑎𝑥 −𝑋 ?𝑖? | 2 ? where in Eq. (1), is your resolution (in this case, in units of Volts), is the lower ∆𝑋 𝑋 ?𝑖? value of your range, is the upper value of your range, and is the number of bits. 𝑋 ?𝑎𝑥 ? Q4: What does the denominator in Eq. (1) represent? The Arduino analog input channels on default settings have a range of 0 to 5 V, which corresponds to counts, or of 0 to 1023. Q5: What is the number of bits of the Arduino analog input channel A0 A/D converter? Q6: What is the resolution (in volts) of the Arduino analog input channel A0 A/D converter, based on Eq. (1)? How does this compare to what you found in Q4? Discuss any differences and speculate as to potential causes. We are now going to use Matlab on your computer to read the serial stream (in this case being constantly sent by the Arduino, via the script you uploaded, with information about the voltage on the A0 pin), instead of the Arduino IDE serial monitor. In the future this will allow more complex functionalities and analysis of your experimental data. In the following, you are going to build a Matlab script, using the code snippets below, that reads the data from the serial port for some specified sampling time, at some specified sampling rate, and generates a figure with that data. This process repeats until a key (other than “P”) is pressed, whereafter it saves the measured data into a figure file, a comma separated value (CSV) file, and a mat file, all of which show the same time vs. voltage data, but give you a variety of ways to access your data. The three files will be saved to your current active Matlab directory, which is the same as the folder where the code you are running is located. For any uncertainties in the Matlab script syntax, you can copy each command into a google search. Matlab maintains a highly comprehensive description of every function online. You can also use the “help” function in the Matlab command line ( https://www.mathworks.com/help/matlab/ref/help.html ). Clear variables, windows, and reset instrument interface objects. close all ; %close all open windows clear all ; %clear all variables clc; %clear output screen instrreset; % reset interface objects 5
MAE 170 [FA23]: LAB 3 Set your sampling time and sampling rate for your Arduino/script. %% Parameters to set T = 5; % Total sampling time in seconds fs = 500; % Hz Make a “serial” object, corresponding to your Arduino, so that Matlab knows what to talk to. Be sure that the BaudRate and COM port specified in the yellow highlighted line s = serial( 'COM3' , 'BaudRate' ,115200); matches that of your Arduino. Enter the command ‘serialportlist’ into the command window to find the com port number of your Arduino. % create the serial object 's' % you must replace the port name with the port on your machine % you can find this through the arduino interface (tools->port) % the baud rate must match what you selected in your serial read ... % Ardino code s = serialport( 'COM3' ,115200); Make a blank Figure, open your serial object (Arduino) and initialize several flags, counters, index variables, and the time and amplitude vectors. Please review each of the comments in the list below. %% Main code figure(01); % setup figure 01 flag=0; %set flag for timer i=1; % set sample counter dt_set=1/fs; % set time step target timer=0; % initialize timer L=T*fs*2; % oversized vector length time=zeros(L,1); % initialize time vector A=zeros(L,1); % initialize amplitude vector waittime=1; %set initial wait time before sampling in seconds t=0; % initialize time variable ind=0; % initialize index variable a=0; % initialize amplitude variable dump= '' ; % initialize text dump variable out= '' ; % initialize serial output string variable tic; % start timer Create another loop inside the main one, which you will read and discard any information that may be stuck in the serial stream. disp( 'Begin to slowly turn the potentiometer knob back and forth over the next 5 seconds' ) while toc<waittime % read and dump serial data until wait time is reached 6
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
MAE 170 [FA23]: LAB 3 flush(s); end Create another loop inside the main one, read data from the serial stream for your specified sampling time at a rate as close to your specified sampling rate as possible. while flag==0 out=char(readline(s)); % reading the serial port ind=find(out== ',' ,1); a=str2double(out(1:ind-1)); t=str2double(out(ind+2:end))/1E6; if (t-timer)>dt_set % condition to take sample at set sampling rate time(i) = t; % establishing time steps for sampling frequency A(i)=a; timer=time(i); i=i+1; if t>(T+time(1)) % condition to end loop when end time is reached flag=1; end end end Close your serial object. disp( 'Done! Be sure to zoom in to see the finite Arduino resolution.' ) clear s; % closes serial port Make the time vector start at 0, convert the counts to voltage, and calculate the actual, average sampling frequency attained by the Arduino. reps=i-1; time = time(1:reps)-time(1); % setup a vector for time voltage = 5/1023*A(1:reps); % convert serial amplitude to voltage dt_avg = time(end)/reps; % find the average time interval between samples fs_avg=1/dt_avg; % calculate the average sampling frequency from dt_avg Plot your data. Note the automated, time saving method for creating well formatted figures. %% Create plot figure(01); % setup figure 01 % plot time vs. voltage, set plotting style to line and dots of size 8 plot(time, voltage(1:reps), '-o' , 'LineWidth' ,2, 'MarkerSize' ,4); xlabel( 'time (s)' ); % x-axis label name ylabel( 'voltage (V)' ); % y-axis label name ylim([min(voltage)-abs(0.1*max(voltage)) ... 7
MAE 170 [FA23]: LAB 3 max(voltage)+abs(0.1*max(voltage))]); % set y plot range title([ 'Voltage vs. Time Sample' ]); % set title % get current plot axes, set font and line width set(gca, 'FontSize' ,22, 'LineWidth' ,2); set(gcf, 'units' , 'normalized' ); % set plot sizing to normalized units drawnow % draw the figure now Save your data. save( 'MAE170_lab2part1' , 'time' , 'voltage' ); % save time and voltage to mat file csvwrite( 'MAE170_lab2part1' , [time, voltage] ); % save time and voltage to csv file saveas(gcf, 'MAE170_lab2part1' ); % save figure Slowly turn the knob on your potentiometer while the code is running, and observe the changing voltage in the generated figure. Q7: Resave the figure file that you generated (zooming in until you can show the discrete steps induced by finite, digital resolution) as a .jpg image, and upload it with your lab assignment submission, as an answer to this question. 8
MAE 170 [FA23]: LAB 3 Part II: Signals and sampling In this section, as demonstrated in the Lab 2 demonstration video, you will use an Arduino and an oscilloscope to sample a time varying signal, and investigate the phenomena of “Aliasing”. Connect your hardware as shown in Fig. 2. Figure 2: Setup used to generate (via signal generator) a sine wave and measure it with both an oscilloscope (the yellow box) and an Arduino. Set your signal generator to generate a continuous sine wave at a frequency of your choice, with an amplitude less than 1 Vpp, and an offset, such that the entire signal is above 0 V . The output from the signal generator can be split using a BNC ‘T’ junction, so that one part of the split output connects to the oscilloscope, and the other connects to flea clips. The oscilloscope is connected to the computer via the USB port in the back of the scope. The flea clips are connected to wire leads, which are then 9
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
MAE 170 [FA23]: LAB 3 connected to the GND and A0 ports on the Arduino. Make sure to turn the output of the function generator on by pressing the ‘Channel’ key and choosing from the menu on the screen, and that it is set to “High Z” mode. As for the prior part, you will construct a Matlab script to not only read your Arduino, but also to read the oscilloscope data! This first portion should be familiar from the last Part’s Matlab script, and is intended to read the serial stream from the Arduino, but now only once per each time the script is run, for a sample time of one second. close all ; %close all open windows clear all ; %clear all variables clc; %clear output screen instrreset; % reset interface objects %% Parameters to set sampleT=1; %Set sampling time in seconds % create the serial object 'dataLogger' % you must replace the port name with the port on your machine % you can find this through the arduino interface (tools->port) % the baud rate must match what you selected in your serial read ... % Ardino code dataLogger=serialport( 'COM4' ,115200); %Connect to arduino %% Arduino data capture newV=0; %intialize variables newT=0; %intialize variables tempText=readline(dataLogger); startV = str2double(extractBefore(tempText, ',' )); startT = str2double(strtrim(extractAfter(tempText, ',' ))); vArduino = [startV*5.0/1023]; tArduino = [0]; while newT<sampleT tempText=readline(dataLogger); newV=str2double(extractBefore(tempText, ',' ))*5.0/1023; newT=(str2double(strtrim(extractAfter(tempText, ',' )))-startT)/1E6; vArduino = [vArduino newV]; tArduino = [tArduino newT]; end clear dataLogger ; %delete dataLogger variable so you can use the com port again Now we will set up the process to read data from the oscilloscope. We are going to make a separate function called “oscread”, and call that function. The function call is the following line. %% Read oscilloscope data 10
MAE 170 [FA23]: LAB 3 [vOscope,tOscope]=oscread(); Now write the function. function [wave,time] = oscread() Set the buffer size (how much data it can acquire at one time) and set up the oscilloscope communication object (see the VISA protocol https://www.mathworks.com/help/instrument/visa-interface.html , as well as the Programming guide for our Rigol Oscilloscopes: https://www.batronix.com/pdf/Rigol/ProgrammingGuide/DS1000DE_ProgrammingGuide _EN.pdf ). The oscilloscope device ID (highlighted in teal) must be adjusted to match the ID printed on the front/back of the particular oscilloscope (also can be found under utility → system info on the oscilloscope). %% may need to use tmtool to scan for oscilloscope resource buffer=2048; % buffer size % set oscilloscope visa object oscObj = visa( 'NI' , 'USB0::0x1AB1::0x0588::DS1ET213707925::0' ); oscObj.InputBufferSize = buffer; % Set the buffer size Open the oscilloscope connection object. fopen(oscObj) % Open oscilloscope connection Tell the oscilloscope to pull data from Channel 1 using text (fprint) commands. fprintf(oscObj, ':wav:data?' ); % Pull data from Channel 1 [data,len]=fread(oscObj,buffer); % Read data to matlab Ask the oscilloscope what scales it is set for (time and voltage). timebase=str2double(query(oscObj, ':TIMebase:SCALe?' )); %get timescale %get vertical scale and offset verticalscale=str2double(query(oscObj, ':CHANnel1:SCALe?' )) verticaloffset=str2double(query(oscObj, ':CHANnel1:OFFSet?' )) Use the acquired scales to correctly set the time and amplitude values. wave=(125-data(12:len-1)')*verticalscale/25-verticaloffset; % calibration determined by inspection T=timebase*12; % calculate total time dt=T/length(wave); % calculate time step 11
MAE 170 [FA23]: LAB 3 time=[0:dt:T-dt]; % setup time vector Close your objects and end the loop. fclose(oscObj); % close oscilloscope connection delete(oscObj); % delete oscilloscope object clear oscObj ; % clear oscilloscope object end When you run your Matlab function, you should now have four vectors: tArduino - The time intervals of the arduino measurements in seconds tOscope - The time intervals of the oscilloscope measurements in seconds vArduino - The voltage measured by the arduino for the pir vOscope - The voltage measurement of the oscilloscope Note: The matlab code will lock the manual control of the oscilloscope; to return control to manual mode, the “FORCE” button (with the “Local” label next to it) on the oscilloscope can be pressed. Now that we have our tools set up, we can acquire data to analyze. We suggest you may also want to augment the above script by using snippets of the script from Part I, to make it easier to save your data, plot what you recorded from your devices, and analyze the response of your devices (e.g. average sampling frequency). Record several data sets, saving the four voltage and time vectors shown above, for different signal frequencies that are prescribed by your signal generator. We suggest you choose one or two frequencies below half of your Arduino’s sampling frequency, and one or two above. Now that your data is acquired and recorded, we are going to create a second, separate, post-processing script to analyze your time-voltage data via “Fast Fourier Transform (FFT)” ( https://en.wikipedia.org/wiki/Fast_Fourier_transform ). We are going to first create the script for a “fake” signal, which you should then replace with your measured data. The sampling frequency Fs should be matched to your average sampling frequency from each data set. The signal variable can be replaced with your measured signal. Fs = 10000; time = (0:1/Fs:1); % Time vector signal = sin(2*pi*30*time); 12
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
MAE 170 [FA23]: LAB 3 Plot your time-voltage signal. figure(1); plot(time, signal, '-ob' , 'LineWidth' ,2, 'MarkerSize' ,4); set(gca, 'FontSize' ,22, 'LineWidth' ,2); xlabel( 'time (s)' ) ylabel( 'Amplitude (a.u.)' ); Call a function you created to calculate the FFT of your data. [freq, amp]=MAE170fft(time, signal); Plot your FFT spectrum. figure(2) semilogy(freq, amp, '-ob' , 'LineWidth' ,2, 'MarkerSize' ,4); set(gca, 'FontSize' ,22, 'LineWidth' ,2); xlabel( 'frequency [Hz]' ) ylabel( '|FT|' ); Create your FFT calculation function. function [frequencyVar, amplitudeVar] = MAE170fft(tVar, yVar) reps=length(tVar); % obtain number of samples fs=1/mean(diff(tVar)); % calculate mean sampling rate % calculate oscilloscope signal PSD [PSD,f_psd] = periodogram(yVar, ... rectwin(reps),reps,fs, 'onesided' ); frequencyVar = f_psd; amplitudeVar = sqrt(PSD); end Q8: (a) Identify the frequency with the largest amplitude, greater than 10Hz, in each dataset by plotting the Fourier transforms of each dataset (these plots do not need to be turned in with your assignment). Plot these identified (most pronounced) frequencies vs. the input frequencies, using Matlab, in the form of discrete markers (this plot should be turned in with your assignment). (b) On the same plot, also plot two lines a piecewise line showing the predicted alias frequencies, given by Eq. (1) in the Appendix. Draw a vertical dashed line at the frequency where you predict aliasing to start occurring for each the Arduino’s sampling frequency. 13
MAE 170 [FA23]: LAB 3 Q9: What happens to the measured or aliased frequency when the input frequency crosses the dashed line corresponding to that group of datasets? Describe your answer in 1 to 3 sentences. Q10: One way to detect if an observed signal or frequency component is aliased, is to change the sampling frequency and repeat the measurement. What would happen to the measured frequency, if you do this, and the sample is (or is not) aliased? Q11: (BONUS): When analyzing the data there is a large peak around 0 Hz, what is the reason for this? 14
MAE 170 [FA23]: LAB 3 Part III: Technical writing Questions: Q12: This question pertains to WLO1: Be able to make observations and provide supported interpretations useful to others in the scientific and engineering community. Fig. 3 shows the data similar to what you will collect in Part II of this lab. Describe what was done to acquire this data and what can be observed in this figure, making sure to keep in mind the (WLO1) dimensions discussed in class (and listed previously at the end of lab 1). Note: H e re you are essentially writing a portion of the “Results” section of a lab report or scientific manuscript (it is not intended to include the “Discussion” section components). Figure 3: Frequency domain (amplitude of the Fourier transform, |FT|, vs. signal frequency) comparison between signals measured via the Arduino (red lines, circle markers) and via the oscilloscope (blue lines, square markers), where the input frequency is less (top panel) or greater than (bottom panel) the Nyquist frequency (f s /2) of the Arduino, which is represented by the vertical dashed line. 15
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
MAE 170 [FA23]: LAB 3 Q13: This question pertains to WLO2: Be able to present data visually in an accessible and information dense manner. In Q9, you created a figure. Write a caption for this figure, and ensure both the figure and the caption satisfy the dimensions of WLO2 provided below. WLO2: Be able to present data visually in an accessible and information-dense manner [Figures and Tables]. Organization of information: Effective consolidation of data; Appropriate amount of data displayed in one figure, such that figure is easily read and comparison between data sets can be easily conducted. Every figure must be referred to in the text. Data accuracy: Accuracy/precision of data evident. Figure formatting: Axes: 1) Appropriate size to be readable; 2) Clearly labeled with units specified; 3) Well placed axes; 4) Convenient (for clarity) choice of scaling (log vs. linear) for chosen discussion points; Closely fitted range selection (fits data displayed); 5) x-independent variable / y-dependent variable. Data markers and trendlines are easily readable. Clear differentiation between discretely and continuously sampled data. Theoretical vs. experimental vs. fitted trend lines clearly differentiated. Sparsely vs. near-continuous sampling is differentiated. Clear legend (if needed). Caption (below figure) allows the reader to fully interpret the data shown in the figure. Can be fully read in grayscale. The caption serves as the figure’s title. A title above the figure is not used with a caption. Tables: Clearly labeled rows and columns. Descriptive title and caption (on top of table). Appropriate amount of data, such that conclusions can be readily drawn by the reader. Every table must be referred to in the text. 16
MAE 170 [FA23]: LAB 3 APPENDIX Aliasing in analog-to-digital conversion (SWR – 2013) If a signal sampled at frequency f s has frequency components >f s /2, after sampling those signals will be “aliased” or “folded back” into the DC - f s /2 range. The alias frequencies can be calculated as f alias = |f in - N·f s | (1) where N (0,1,2…) indicates the frequency band which contains the f in component in the original signal, and f alias is the shifted frequency of the f in signal after sampling. The frequency bands N are defined here as N Freq band 0 DC - f s /2 1 f s /2 - 3f s /2 2 3f s /2 - 5f s /2 3 5f s /2 - 7f s /2 4 7f s /2 – 9f s /2 5 and so on… Example: Assume a sampling frequency f s of 100 kHz and an analog data stream containing signal components at the following f in frequencies: 27 kHz, 41 kHz, 82 kHz, 219 kHz, and 294 kHz. After sampling, the amplitudes of all the signals would be preserved but their frequencies would be shifted or “folded” from f in to f alias according to Eq. (1) above: Table 1: f in vs f alias f s f in N f alias = | f in – N(f s ) | Description 100 kHz 27 kHz 0 | 27 – 0(100) = 27 kHz Correct signal, good data 100 kHz 41 kHz 0 |41 – 0(100)| = 41 kHz Correct signal, good data 100 kHz 82 kHz 1 |82 – 1(100)| = 18 kHz Aliased signal, data is artifact 100 kHz 219 kHz 2 |219 – 2(100)| = 19 kHz Aliased signal, data is artifact 100 kHz 294 kHz 3 |294 – 3(100)| = 6 kHz Aliased signal, data is artifact 17
MAE 170 [FA23]: LAB 3 Notice that all of the out-of-band signals whose frequency is > f s /2 (i.e. greater than 50 kHz) have been shifted in frequency down into the DC – 50 kHz frequency band. This is the aliasing error resulting from sampling too slowly for the higher frequency components. To avoid these errors you would need to either increase f s to >588 kHz (294·2), or keep the 100 kHz f s and apply a <50 kHz low-pass filter to the data stream prior to the analog-to-digital converter. Acknowledgements Some elements of the lab instructions have been adapted from prior MAE170 iterations. 18
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help