MEC8063 Tutorial 4 Data Analysis

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

MEC8063 Introduction to Mechatronics Design

Tutorial 4 – Data Analysis

Objective: This tutorial will use some of the specialised functions of Labview to analyse data. We will also modify
these functions for our own requirements.

Reading: There is no specific reading for this tutorial.

1. Introduction

Now that you know the basics of using Labview we will use Labview to look an analysing some data. In the first
part of this tutorial, we will use artificial data to start with and then process the data collected in sensors tutorial
to calibrate these sensors. Then you will look at the principles behind signal processing techniques.

2. Using Labview to fit data

We shall use Excel to create some artificial data with noise (we could alternatively write a Labview program to do
this and save it to a file) and then see if we can fit an appropriate function to this data.

2.1 Creating the artificial data

We can create test data using any one of a number of programs (Labview, Matlab, Excel, etc). In this case we shall
use Excel. Open an Excel document and type the numbers 0 to 10 in the first column. In the second column use
the formula:

=5.2+4.1*A1*A1+RAND()-0.5

for B1 and similarly down the B column (copy B1 and paste it into cells B2 to B11). We are going to attempt to get
Labview to find the coefficients 5.2 and 4.1. Save the data with filename ‘testdata.txt’ as a tab delimited text file
(if it is saved in Excel format the data will not load into Labview).

2.2. Setting up the Labview program

Insert an XY Graph (Express – Graph Indicator – XY Graph) and three Numerical Indicators (Express – Num Inds –
Num Ind) on the Front Panel. Label the Numerical Indicators as Coefficient 0, 1 and 2, label the XY Graph as Data,
the x-axis as Time (s) and the y-axis as Signal (V). Expand the Plot 0 window. Right click on Plot 0 and change
Common Plots to a series of dots. Relabel Plot 0 as Data and Plot 1 as Fit.

Note: It is good practice when doing plots to show data points as points (circles, squares, etc) and any fitting to
this data as a continuous line (no points). If data points are connected with lines, this infers the value between
these points which is incorrect.

A Build XY Graph icon may have appeared automatically in the Block Diagram window (if you use the Express
route you will automatically get Build XY Graph icon, if you have found XY Graph from another route you may not
get this icon). The Build XY Graph icon is the easiest approach but for now delete this as we will build our own for
this exercise so you see how things work.

Open the file as in the previous tutorial and use the Index Array to get the x and y data into separate arrays. Insert
a General Polynomial Fit (Mathematics – Fitting – Polynomial Fit) icon and use the Context Help to correctly wire
in the x and y inputs. As you will see from Context Help, this icon has several outputs. Click on ‘Click here for more
details’ to get info about each terminal. Feed the Polynomial Coefficients to an Index Array icon and extract the 0,
1 and 2 indexes. Feed these values into your coefficient output windows. The program is shown in figure 1.

John Hedley, School of Engineering, 2024. Page 1


MEC8063 Introduction to Mechatronics Design
This will give us a polynomial fit and output the coefficients but it would also be good to see this fit (a visual
inspection of the fit is always a good idea, if the fit looks poor you should not use it and look for a better function
to fit to). Take the input x and y arrays and feed this into a Bundle (Programming – Cluster – Bundle). Additionally
take the x array and the Best Polynomial Fit from the General Polynomial Fit icon and feed this into a second
Bundle icon. The output of both Bundles can be then fed into separate graphs for inspection. A better way is to
Build Array (Programming – Array – Build Array) using these outputs and feed both sets of data into the graph. Do
this, save the program as Tutorial_4 and then run the program. The Block Diagram and output should look similar
to that of figure 1.

Have we missed something from our program? Our data was generated as a 2nd order polynomial (terms of x
squared) so we should tell the General Polynomial Fit that we are looking for a polynomial of order 2 solution.
Therefore we should wire a value of 2 into the appropriate connection of this icon. Fortuitously the default value
for fitting is 2 and therefore the fit should be appropriate.

Figure 1: The fitting program is limited by the constraint of having to use the formula a0+a1x+a2x2.

2.3. Problems with the program

This has given us a general polynomial fit. However this has given us a value for Coefficient 1 (albeit it is
approximately 0 which is close to being correct) which was not present in our original data file. Also what if we do
not want a general polynomial but want to fit to a specific function. We will now change the program to do a
general fit.

There are a variety of fitting functions available; we will use the non – linear Levenberg Marquardt routine. Insert
a Nonlinear Lev-Mar Fit icon (Mathematics – Fitting – Nonlinear Curve Fit) and wire up the X and Y inputs and the
Best Fit Parameters and Best Nonlinear Fit as before. It is easiest to do this with the General Polynomial Fit icon
still in place and then once you have finished the wiring delete the General Polynomial Fit icon.

Note: Take care making these connections, note careful from the Context Help which wire corresponds to which
input / output as this differs from the General Polynomial Fit icon.

We will only be fitting two coefficients so delete Coefficient 2 and shrink the Index Array icon that accesses the
coefficients.

John Hedley, School of Engineering, 2024. Page 2


MEC8063 Introduction to Mechatronics Design
Although the program will now only fit the two required coefficients, we have not informed it what function to fit
to. To do this, we will enter the formula as a string. In the box under the Nonlinear Curve Fit icon, select Lev-Mar:
formula string as the input format. The formula is described by a text cluster, this can be either entered in the
Block Diagram part as String Constants (Programming – String – String Constant) or on the Front Panel as an input
string. We will use the format ‘a0+a1×x×x’ where the coefficients are a0 and a1. The format for this cluster is
described in the Context Help and shown in figure 2.

The final item required is an array of initial guesses for each parameter (generally speaking, for specialised curve
fitting you need to estimate the answer to give the fitting program a chance to solve the problem). From your
data, we can visually estimate a0 to be about 0 (around 0 intercept on the y-axis) and a1 to be about 4 (as we
know the last data point is a1*10*10 which is about 400) – in fact these values are 5.2 and 4.1 as programmed in
Excel although we are pretending not to know this. Create an array containing these 2 values and feed it into the
Initial Parameters input of the Fitting icon. Your program should look something like figure 2. Try running the
program, how does the output compare to that of the 2nd order polynomial fitted earlier? We are still not getting
the exact answer (as there is noise in the data) but it is a better estimate. Make sure a visual inspection of the fit
looks reasonable, if the fit looks poor then your fitting function is incorrect or your initial estimate of the
parameters is poor.

Figure 2: Using Labview to fit your own defined function.

2.3.1. Exercises

Your program can be improved. Have a go at programming the following bullet points.

• It is useful to know how many data points you have. Have your program display the number of data points used,
i.e. 11 (the program should calculate 11, this should not be entered as a constant).
• You should display numbers to a reasonable number of places (usually reflecting the accuracy in the value). Set
the properties of the output boxes to show only 2 decimal places for the fitted coefficients.
Note: We are not discussing accuracy of measurement in this module but for those interested, “Practical Physics”
by G. L. Squires gives a good explanation.
• Allow the user to enter the formula from the Front Panel in the form of a string input. This should then be wired
into the Nonlinear Lev-Mar Fit icon.
• Save the data - the data should be saved as x,y,fitted-y columns (as given on the plot). It is also useful to save
out the fitted parameters (maybe in a 4th column or row) and some descriptive text about the data (possibly via
a text entry box on the Front Panel). This allows anyone viewing the data to know exactly what it is.

John Hedley, School of Engineering, 2024. Page 3


MEC8063 Introduction to Mechatronics Design
3. Analysing our Arduino data

We will use the ideas developed in section 2 to try and fit our data recorded from our Arduino program.

3.1. Ultrasonic data

In Tutorial 3 we created an Excel file to calibrate the ultrasonic sensor. Create a Labview program to display this
data and fit a straight line to it (as we did in Excel). You can perform this fit with either the General Polynomial Fit
using order one or (more simply) use the Linear Fit icon. Add a numeric input onto your Front Panel to simulate
an ultrasonic duration measurement (input value of between 0 to 20000 microseconds) and program Labview to
display this value on a numeric output as a distance measurement by using the coefficients from the linear fit to
perform the appropriate calculation.

3.2. Magnetometer data

In Tutorial 3 we created an Excel file to calibrate the magnetometer sensor. Create a Labview program to display
this data and fit a circle to it. This is easiest done by creating a third column of data consisting of 0 and then using
the Fitting on a Sphere icon to fit your x,y,z data where the z data is the list of 0s. Add two numeric inputs onto
your Front Panel to simulate a x and y magnetometer measurement and program Labview (by using the
coefficients from the sphere fit) to display the compass heading on a numeric output.

Note: You will need to choose your input values carefully to try and replicate what the magnetometer would give,
for example when looking at Tutorial 3 figure 17 pick some point on this circle such as a value for x of 1000 and a
value for y of -500.

4. Signal processing

On many occasions we may have to analyse a signal from a sensor to determine what is present in this signal. We
may then wish to condition this signal in some respect, for example filter out any noise. This is known as signal
processing.

Imagine you have a signal which is a sine wave and is given by A0 sin(2𝜋𝜋ft) where A0 is the amplitude of the wave
and f is its frequency as shown in figure 3a. This is the simplest signal we can get. In reality, signals are a lot more
complicated than this as shown in figures 3b (sawtooth) and 3c (sine signal with noise).

Figure 3: Examples of a signal.

John Hedley, School of Engineering, 2024. Page 4


MEC8063 Introduction to Mechatronics Design
Every signal is made up of a series of sine waves (of different amplitudes, frequencies and possibly phase) so
rather than thinking of figure 1 as a plot of complexed signals, it is just a plot of a series of summed sine waves. To
demonstrate this, we will approach this issue from two perspectives. Firstly we will try and work out what set of
sine waves we need to make a certain signal shape and then secondly we will take a signal shape and try to
deduce what the sine waves were to produce this. This gives you a good insight on what you need to do to
process signals coming from sensors.

4.1. Generating and processing a signal

4.1.1. Fourier series

We will use Labview to create a sawtooth wave from a series of sine waves. In practise, there is a simpler way of
generating this waveform via software but for now we will use the Fourier series approach as this will give you an
insight into the mathematics behind the problem. More information on the Fourier series can be found at
https://en.wikipedia.org/wiki/Fourier_series.

We will not derive the required equation but just use it, for a sawtooth wave we need to generate the sum shown
in equation [1]:

2
𝑦𝑦 = ∑∞
𝑛𝑛=1 (−1)
𝑛𝑛+1
sin(𝑛𝑛2𝜋𝜋𝜋𝜋𝜋𝜋) . [1]
𝑛𝑛

Create the Labview program shown in figure 4 and see the output when changing the number of terms from 1 to
10. As the number gets larger, we are getting closer to a sawtooth shape.

Figure 4: Labview program to generate a sawtooth waveform. The 3 new icons we are using are ‘Sine’, ‘Power of
X’ and ‘Sum’. Note we need to increase the inner loop count i by one as the Fourier series has n starting at 1
whereas i starts at 0.

4.1.2. Generating a sawtooth waveform

Actual signal generation is a lot simpler than creating a Fourier series for example switching a digital pin on and
off will create a square waveform (which if generated mathematically is a Fourier series of sine waves) however it
is important that you realise this basic principle behind what constitutes an arbitrary waveform.

For this exercise we will write a simple program to produce a sawtooth voltage and then analyses it. Figure 5
shows the basic program to generate a sawtooth waveform and display it. The ‘film roll’ Flat Sequence structure is
to allow us to control order of execution of different parts of the program. One way to generate a sawtooth
waveform is to create a loop and divide the loop count by, what is effectively, the wavelength of the wave we
want to generate. Create the program shown in figure 5. We will have a wavelength of 10 for our sawtooth wave
so we will divide loop count i by 10 and use Quotient & Remainder icon to find the remainder. The remainder of

John Hedley, School of Engineering, 2024. Page 5


MEC8063 Introduction to Mechatronics Design
this division we set as the amplitude of the output which we can then subsequently scale to the required
amplitude (in this case divide by 2 to limit the output to below 5V). This is placed in a For loop and we will
increment the values of i (effectively our timebase) from 0 to 100.

We have now generated our sawtooth waveform. One last task is to control program execution (what icons we
would like to run first). Placing icons from left to right does not necessarily dictate what icons will run first so
sometimes we need to carefully control this. To do this we add a Programming – Structures – Flat Sequence and
place the sequence around the sawtooth generation. If you right click on this sequence, you can then Add Frame
After.

We are controlling the wavelength of our sawtooth (using the number 10 in the division) so our sawtooth
waveform should have a wavelength of 10 points. However the actual frequency we are generating will depend
on the time it takes the program to loop, if it takes 1s per loop then we have a frequency of 1/(10x1) = 0.1 Hz. If it
takes 1ms to loop then we have a frequency of 1/(10*0.001) = 100 Hz. The program runs very fast so the time
delay is very small (i.e. if we timed this signal which we will be doing in the next section we are generating a
sawtooth waveform at a very high frequency). We will control the actual timing by adding a delay in our program
to generate a slower signal. Place a Wait (ms) icon in the second grid of the sequence and wire a value of 50 (ms)
into this icon. As a wavelength is 10 loops then the time for 1 sawtooth wave is 500 ms corresponding to a
frequency of 2 Hz (i.e. 2 complete waves per second).

Note: In practice there are problems generating a specific frequency in software as it depends on program
execution time. For our slow signals here it is not a problem but for high frequency signals it can be a significant
issue. There are more robust ways to generate a signal of a specific frequency, something we will discuss in the
MEC8057 stage 4/MSc module.

Finally we want to display the results so place a XY Graph on the Front Panel and wire this up to your data. Adding
a loop count indicator helps you keep track on how long the program will take to finish.

Figure 5: A program to generate a sawtooth waveform.

John Hedley, School of Engineering, 2024. Page 6


MEC8063 Introduction to Mechatronics Design
4.2. Signal processing

We will now look at processing the signal we have created (noting that we are expecting something that looks like
our Fourier analysis for our sawtooth waveform in section 4.1.1). First of all we need to see what frequency
components are present in the signal. Place an Amplitude and Phase Spectrum icon (Signal Processing – Spectral –
Amplitude and Phase Spectrum) in the Block Diagram and wire up your data to the Signal input. This icon takes
the signal and also a value for the time between data points (the dt connection). Assuming the program runs very
fast then the time between data points is 50 ms and so we can wire this value into the icon, i.e. 0.05s.

We wish to view the output from the Amplitude and Phase Spectrum icon. It outputs y data and frequency step
(df) and for such an analysis, the starting frequency is 0 Hz. Thus we have f0 (=0), df and y[] and can use a
Waveform Graph to display the output (or alternative use f0 and df to work out a series of f data points and use
an XY Graph). Place a Waveform Graph on your Front Panel and label the x-axis as Frequency. We’ll need to
bundle the required data into this input as we did in Tutorial 2. The modifications to the program are shown in
figure 6.

Figure 6: Determining the frequency components.

Run the program and see if you are getting a series of sine waves (peaks at different frequencies) from this
analysis which make up your sawtooth. As seen in equation [1], the amplitude of each of these sine waves is
different so your plot should reflect this with peaks (lowest to highest) having amplitude ratios of 2/1 : 2/2 : 2/3 :
etc.

Note: As our sawtooth is always positive, we will have an additional frequency component which is the average of
the signal (this is a dc offset used to offset the sawtooth from its default –V to +V sweep to a 0 to +V sweep). So
you should see an additional peak at a frequency of 0.

John Hedley, School of Engineering, 2024. Page 7


MEC8063 Introduction to Mechatronics Design
As a quick exercise try changing the loop count from 100 to 1000. What difference do you notice? The resolution
on the frequency analysis should be a lot better. When finished change back to 100 for the remainder of this
tutorial.

Note: The easy way to think of this change in plot is consider beat frequencies, i.e. when you play two sound waves
of slightly different frequencies you hear a beat (a frequency which is the difference between the two initial
frequencies). If the difference between the initial frequencies is 1 Hz then you would get a beat of 1 Hz so you
would need to listen to at least 1s of sound to hear this beat. If the difference is 0.1 Hz then the beat is 0.1 Hz and
so you would need to listen to 10s of sound to hear this beat. Putting that in reverse, if you want to have better
frequency measurement resolution, you need to listen to the sound for longer. So increasing your loop count from
100 to 1000 gives you 10 times better resolution in your frequency plot.

4.3. Signal conditioning

We will now look at conditioning our data by filtering it. Place a Butterworth filter (Signal Processing – Filters –
Butterworth) in your program and set type to Lowpass. Wire your data to the X input. We require 3 more inputs.
For the sampling frequency, as we have set a dt of 50 ms in the previous section so we have a sampling frequency
of 1/0.05 (or 20 Hz) for this icon. Place in a Reciprocal icon (Programming – Numeric) and wire accordingly. From
our frequency analysis of section 4.2, we see we have frequency components at 2 Hz intervals (corresponding to
the sawtooth wavelength and higher harmonics). We will select one of these by setting the frequency limit on our
filter to be 3 (also change the filter order to 6, this will be explained later). If the filter works well, it should only
pass frequencies below 3 Hz, i.e. the d.c component and the 2 Hz fundamental frequency for our sawtooth wave.
Your program modifications should look like figure 7.

Figure 7: Adding a signal conditioning filter.

John Hedley, School of Engineering, 2024. Page 8


MEC8063 Introduction to Mechatronics Design
Wire the output signal into a second XY Graph, the x values for this is just the x values of our original data. Run
the program and check what the output looks like, is this what you expected? Our original plot was a sawtooth
but as we have now only passed the d.c component and a single frequency through the filter, this output is now
be a single sine wave raised above the x-axis. The filter takes a little time to respond so the initial part of the plot
will reflect this.

As an exercise, try changing the filter cutoff to 1 Hz, you should now only see the d.c component (the line will rise
to around 2.25 V). Change the filter order from 6 to 2 and run the program and you will see the signal now
oscillates. The filter is now order 2 (basically not as good) and so it is leaking in energy from the 2 Hz signal hence
the oscillations. Finally change the order to 10 (which as a higher order filter should work a lot better). You will
notice that you have more oscillations than the order 6 version. This is not spectral leakage but the gain in the
filter is causing oscillations in it causing it to take longer to settle (so higher is not always better). We will see this
effect again when we discuss PID control in tutorial 7.

Try changing the filter cut off value of the filter, firstly to 5, then to 9. What you are doing is including more of the
frequency components in your signal. The result of doing this should be similar to the exercise we did in figure 4
where we were including more frequencies in our Fourier series for sawtooth generation. You may also wish to
change filter type to highpass (or bandpass) so you select other frequencies you wish to view.

In practise, we do not use filters to generate the Fourier series (we already have it as our input signal) but use
them to eliminate components we do not want. So in this example let us say our frequency we wanted was 2 Hz
and everything else is noise (making the signal look like a sawtooth). By using a bandpass filter we eliminate all
the unwanted frequencies and keep a much cleaner (less noise) wanted signal. In practise, figure 1c is what our
original signal would look like and figure 1a would be what it looks like after applying such filters.

Note: This is a digital filter, we are filtering the signal after it has been digitised into values. Analogue filters
(electronic circuits) filter the signal prior to it being digitised.

Note: We can replicate a low pass filter (remove high frequency noise) very simply by taking an average of a
number of measurements. We will discuss filters more in the MEC8057 stage 4/MSc module.

4.4. Measuring actual frequencies

We assumed very fast execution time and predicted our sampling frequency. What we should do is measure this
so we need to record the time of the measurement. Place a Tick Count at the very start of the program (before
the For loop). We can use this as an indicator of when the program started. Add a 3rd grid to the sequence, place
the delay in the last grid square and place a Tick Count icon in the grid immediately after signal generation (i.e.
the middle grid space). Wire both of this Tick Count icons to a subtract icon and this will give you a timebase (in
milliseconds) for each of your waveform data points from when the program was started. The divide by 1000
converts the ms to s. You can wire the output from this as your x values for your XY Graphs (instead of using the
loop count i as your x values).

Next replace the 50 in your dt in your Amplitude and Phase Spectrum icon with an appropriate value, you can
work out dt as this is the difference between the time for two data points, i.e. two consecutive x values (note this
assumes all data points are equally spaced). The final program is shown in figure 8. Running the program will give
you similar results to previously.

John Hedley, School of Engineering, 2024. Page 9


MEC8063 Introduction to Mechatronics Design

Figure 8: Timestamping the data points.

Note: Although this Tick Count method works, it is not an ideal method to use for frequency analysis. Firstly it only
records to ms resolution and so limits the frequencies that you can measure. Secondly (and more importantly)
Windows is not a real time operating system, this means you cannot rely on the timing as Windows may decide it
wants to do other things. For example Labview may record 2 data points, then Windows decides it wants to run a
background virus check and then lets Labview record the next data point thus our time between data points may
vary (i.e. dt does not stay constant). We would therefore need to use other analysis techniques that can cope with
a non-periodic collection of data. It is therefore much better to collect data with hardware by specifying a
sampling rate for a set number of points rather than have the Labview software asking for one data point at a
time. The scenario is different for the Arduino which is a real time operating system (it is not doing background
operations although you need to be careful not to use blocking functions) and can record to microsecond
resolution. We will try this timing method on the Arduino when we look to measure motor speed in tutorial 7.

5. Practical exercises

5.1. Frequency analysis (note this may form part of the assignment so take a copy of the screenshot)

If we wished to use Labview to perform an automated frequency analysis, we could use data acquisition hardware
(see for example https://www.ni.com/en-gb/shop/data-acquisition/entry-level-usb-daq.html ) to feed our signal
into the computer and then analyse this with our Labview program. For this tutorial, we will perform frequency
analysis using the Picoscope.

Connect up a PicoScope and set the waveform generator to a Ramp Up signal type with 2 kHz frequency and 1V
amplitude and 1V offset. View your signal on the oscilloscope and then in Instruments, select Spectrum - this will
show you what frequency components are visible in your signal. If you click on the Spectrum icon, you can set the
range to be 49 kHz and for the Axis tab, set the x and the y-axis scales to be linear. The trace should be similar to
what is given in figure 6 however this time the axis kHz rather Hz. Do you notice any difference in the spectrum if
you have either a.c. coupling selected or d.c. coupling connected. Take a screenshot of your PicoScope spectrum
trace (include team member names in this screenshot).

Note: You may see additional spikes in the signal at frequencies you are not expecting (this is particularly evident it
you have the y-axis set to log). This is the effect of high frequency noise that is contaminating our spectrum at low
frequencies. This is known as aliasing and MEC8057 will discuss this effect and how to remove it.

John Hedley, School of Engineering, 2024. Page 10


MEC8063 Introduction to Mechatronics Design
5.2. Analysis of Arduino signal (note this may form part of the assignment so take a copy of the screenshot)

Output two PWM signals, one of 50% duty cycle from pin 10, the other 25% duty cycle from pin 9 of an Arduino.
Feed both signals into the 2 channels of a PicoScope and measure a) the time difference between the rising pulse
of the traces and b) the time it takes for the signal to settle for the 50% trace. Take two screenshots (one of each
measurement) making sure to include the names of fellow team members in this image. Can you explain why it
takes time for the signal to settle?

Note: For part (a), the difference between the pulses depends on which pins you use on the Arduino. If you use
pins 9 and 10 then the pulses start at a different time. If you use pins 5 and 6 they appear to start at the same
time. You should therefore use pins 9 and 10 and measure this difference in start time.

6. Summary

Labview can be used for a number of applications. In this tutorial, we have seen how we can use it to display data
and process this data to a form suitable for the user. It is always a good idea to save data where possible (the
original data plus any processing you have done to it) for future reference – for example if your system suddenly
crashed this saved data could be used to determine what had gone wrong.

John Hedley, School of Engineering, 2024. Page 11

You might also like