Lab 5 - ADC with Matlab
In questa pagina 8
Aim
Create a MATLAB script that generates a simple signal and takes it through the stages of an analog-to-digital conversion: sampling, quantisation, parameter estimation (RMS value) and noise addition with SNR evaluation. Background theory: Sampling and the Sampling TheoremSampling multiplies a continuous-time signal by a pulse train, which replicates its spectrum every omega_s; if the signal is band-limited with maximum angular frequency omega_M and omega_s exceeds 2 omega_M, an ideal low-pass filter recovers it exactly (Shannon theorem and sinc interpolation formula).Sampling and the Sampling Theorem →, Aliasing and Anti-Aliasing FiltersAliasing is the overlap of spectral replicas that occurs when the band-limited or Nyquist assumptions of the sampling theorem fail; an anti-aliasing low-pass filter with cut-off omega_s/2 applied before sampling removes it at the price of losing the high frequencies; two worked exercises.Aliasing and Anti-Aliasing Filters →; the same quantisation concepts appear in Non-Idealities in a Control Loopmodels and control consequences of the main non-idealities of a feedback loop, namely sensor bias, noise, quantization and limited bandwidth, actuator saturation and limited bandwidth, time delays with Pade approximations, disturbances and parameter or model uncertainties.Non-Idealities in a Control Loop →.
1.1 Script Matlab - foreword
- MATLAB executes single instructions from the Command Window, or a series of instructions arranged in a script: a text file created with the MATLAB Editor, with the
.mextension. - Scripts execute instructions sequentially; usual programming statements (
forcycles, conditionalsif...then...else) can be used. - Good practice is to begin scripts with:
clc- clears the command window;clear all- deletes all the variables in the workspace;close all- closes all open windows generated by previously executed scripts and commands.
1.2 Continuous signal generation
The signal to be generated is
Parameters set with assignment instructions: V_0 amplitude, F_0 frequency, Phi_0 initial phase.
- MATLAB does not require explicit declaration of variables (unlike C/C++): they are defined the first time an instruction uses them. It is however good practice to declare all variables at the beginning of the script. All variables appear in the Workspace for debugging.
- MATLAB knows nothing about units of measurement: use comments (anything after
%) to note, for example, thatF_0 = 20;is a frequency of 20 Hz. - Group all assignments in a dedicated part of the code. Example on the sheet:
% *********************
% Signal parameters
% *********************
V_0 = 1; % amplitude [V]
F_0 = 20; % frequency [Hz]
Phi_0 = pi/6; % initial phase [rad]- All instructions end with
;to avoid displaying the result in the Command Window. - The simulated signal is a vector of numerical values. Its duration
T_W(seconds) must be chosen considering that the signal will be shown in afigurewith one or moreplotcommands; chooseT_W(also non-integer) so that the number of periods shown is limited, otherwise it is nearly impossible to look at the signal in detail. - A true continuous-time signal cannot be obtained on a computer; with a sufficiently high number of points in
T_Wthe samples are close enough to approximate the continuous trend.
Time axis of the "continuous" signal:
t = linspace(0, T_W, N);This imposes equidistant points in the interval from 0 to ; each point is from the closest.
Continuous sinusoidal signal:
V = V_0 * sin(2*pi*F_0*t + Phi_0);Display:
figure
plot (t, V)
legend("Continuous Signal")Be careful (sheet): the parameters of linspace do not give explicit hints on the sampling period. Pay attention to the value of to avoid inappropriate choices.
1.3 ADC: signal sampling
To represent a sampled signal define a sampling frequency F_s and a vector of time values spaced by T_s = 1/F_s. The approximate number of samples in the interval is
N_sample = round(T_W / T_s);(round() rounds to the closest integer). The vector of sampling time instants:
t_sample = [0:1:(N_sample - 1)] * T_s;The sampled signal V_sample is obtained by substituting the vector t with t_sample in the signal expression:
V_sample = V_0 * sin(2*pi*F_0*t_sample + Phi_0);Comparison of the continuous and sampled signal in the same chart:
figure
plot (t, V)
hold on
plot (t_sample, V_sample, '*r')hold on superimposes several plots on the same figure; the characters in single quotes select plot features (colour, solid/dashed/dotted line; see the help/doc of plot()).
The procedure can be repeated for different sampling frequencies to verify that, according to the Nyquist-Shannon sampling theorem, the value of F_s is adequate.
Detailed view of the sampled signal:
figure
plot (t_sample, V_sample)With the plain plot command the samples are linked with segments: this can be considered a reconstruction of the continuous signal by linear interpolation of the samples.
At this stage the signal is discretised over time but not over its amplitude. The appearance of the signal depends both on the sampling frequency and on the initial phase Phi_0.
Question on the sheet: which sampling frequency allows visualising a waveform of the sampled signal similar to that of the continuous signal? Compare this value with the minimum one required by the sampling theorem.
1.4 ADC: signal quantisation, uniform quantiser
The quantiser is defined by:
- the full-scale value
V_FS, with which the input amplitude is specified in the range ; Nbit, the number of bits . There are quantisation levels, whose numerical values belong to the set
Needed operations: evaluation of the quantisation step and of the quantised value. With rounding quantisation (the MATLAB function round()) the signal amplitude is expressed as a "number of quantisation steps"; the integer obtained must then be checked against the range allowed by Nbit.
Quantisation step (linear characteristic):
Delta_q = V_FS/(2^Nbit);Quantisation level of each sample:
q(i) = round(V_sample(i)/Delta_q);The integer values must be limited to the allowed range (saturation effect of the quantiser):
- if then ;
- if then .
Quantised value of the samples:
V_q(i) = q(i) * Delta_q;Quantisation error: difference between the quantised signal and the real (sampled) one:
e_q(i) = V_q(i)-V_sample(i);The quantisation error cannot be avoided but can be mitigated; the most immediate way is to increase the number of bits, which implies a more complex and expensive device. At this stage the signal is discretised also over its amplitude.
Note on the sheet (to try on your own): to verify the quantiser, use as input vector V_test a linear ramp from to (generate it with linspace()), with a number of samples much larger than the number of levels (). The plot of the quantised signal should reproduce the quantisation characteristic, and the difference between the input ramp and the quantised signal represents the quantisation error.
Observation (deduced from the sheet's formulas, not stated by the sheet): with Delta_q = V_FS/(2^Nbit) and levels from to , the largest representable value is about , so the step formula and the stated input range are not consistent with each other as written; if in doubt about the convention, ask the instructor.
1.5 Estimation of the signal parameters: RMS value
The samples are used to determine parameters of the continuous signal, whose analytic expression is known. The number of samples is predefined (example on the sheet: N_sample = 256), which corresponds to a finite-size memory recording the acquired samples.
Analytic RMS value of a sine of known amplitude V_0:
from the general formula
with the period of the sine.
With only samples the RMS is estimated as
The vector is obtained by squaring each element of ; then the functions sum() (sum of the elements of a vector) and sqrt() (square root) complete the computation.
The estimate does not generally coincide with the theoretical value, because samples do not cover an exact integer number of periods of the sinusoid. Once F_0 and V_0 are chosen, vary the phase Phi_0 and/or the sampling frequency F_s to approach the theoretical RMS value.
Question on the sheet: compare the RMS value computed from the samples with the theoretical one. Are there variations of the RMS value when the signal frequency and phase vary?
1.6 Additive noise and SNR
Any experimental dataset acquired by a data acquisition system (see Data Acquisition SystemsA DAQ module multiplexes several analog inputs through a programmable gain amplifier into one ADC, stores the samples in a buffer and hands them to a PC, with sampling timing, trigger modes (digital, analog level, window, pre-trigger) and input configuration (differential or referred to ground) that the user must know.Data Acquisition Systems →) is affected by noise: random fluctuations of the signal or spurious components. It is reproduced by creating a vector of noise samples of the same size as the signal vector and summing the two.
MATLAB functions:
rand(n1, n2): random numbers uniformly distributed between 0 and 1, in a matrix ofn1rows andn2columns;randn(n1, n2): random numbers with Gaussian distribution of zero mean and unit variance. Since noise is usually Gaussian,randnis used.
Signal-to-Noise Ratio (SNR): ratio between the signal power and the noise power. In this simulation the signal power is the square of the RMS value () and the noise power is the variance (dimension amplitude squared):
Example from the sheet: if the signal power is ten times the noise power, hence . To obtain noise samples with that power, the output of randn() is multiplied by the standard deviation :
noise = sqrt(P_noise) * randn(1, N_sample);Noisy signal:
V_noise = noise + V_sample;Tasks on the sheet
- Generate a figure with both signals (with and without noise), with axis labels and legend, using
hold on,xlabel,ylabel,legend. - Use different colours for the two plots, passed as additional parameters to
plot():'r'red,'k'black,'g'green. - Compare the theoretical SNR with that of the simulated sampled signal, obtained with
x = snr(y), whereyis the vector of samples of the noisy signal andsnr()is a MATLAB function.
Summary of the steps (as listed on the sheet)
- define the parameters of the sinusoidal signal;
- define the observation interval ;
- define the time axis ;
- generate the sinusoidal continuous signal;
- define the sampling frequency;
- compute the discrete time axis;
- compare the two sinusoidal signals;
- build the quantised signal;
- estimate the RMS value;
- observe the variations of the RMS value depending on the sampling frequency;
- add noise to the signal;
- compare the signals with and without noise;
- compute the SNR.
Versione ripasso
- Aim: a MATLAB script that takes a sinusoid through sampling, uniform quantisation, RMS estimation and noise addition with SNR evaluation. Theory: Sampling and the Sampling TheoremSampling multiplies a continuous-time signal by a pulse train, which replicates its spectrum every omega_s; if the signal is band-limited with maximum angular frequency omega_M and omega_s exceeds 2 omega_M, an ideal low-pass filter recovers it exactly (Shannon theorem and sinc interpolation formula).Sampling and the Sampling Theorem →, Aliasing and Anti-Aliasing FiltersAliasing is the overlap of spectral replicas that occurs when the band-limited or Nyquist assumptions of the sampling theorem fail; an anti-aliasing low-pass filter with cut-off omega_s/2 applied before sampling removes it at the price of losing the high frequencies; two worked exercises.Aliasing and Anti-Aliasing Filters →; quantisation concepts in Non-Idealities in a Control Loopmodels and control consequences of the main non-idealities of a feedback loop, namely sensor bias, noise, quantization and limited bandwidth, actuator saturation and limited bandwidth, time delays with Pade approximations, disturbances and parameter or model uncertainties.Non-Idealities in a Control Loop →.
- Script start:
clc,clear all,close all. Comments after%note the units (MATLAB knows none). End every instruction with;. Group the parameters in one block. - Signal: , parameters
V_0,F_0,Phi_0, observation windowT_W(choose it so only a few periods are shown). - Continuous-time approximation: many points on a time axis.
t = linspace(0, T_W, N); % N equidistant points in [0, T_W]
V = V_0 * sin(2*pi*F_0*t + Phi_0); Check the spacing : linspace does not show the sampling period.
- Sampling: , then
N_sample = round(T_W / T_s);,t_sample = [0:1:(N_sample - 1)] * T_s;andV_sampleevaluated att_sample. Overlay withhold onand'*r'. A plainplotof the samples joins them by linear interpolation. Check against the Nyquist-Shannon condition by trying several values. - Uniform quantiser: full scale
V_FS,Nbitbits, levels with values in .
Delta_q = V_FS/(2^Nbit); % quantisation step
q(i) = round(V_sample(i)/Delta_q);
% saturation: q(i) limited to [-2^(Nbit-1), 2^(Nbit-1)-1]
V_q(i) = q(i) * Delta_q;
e_q(i) = V_q(i) - V_sample(i); % quantisation error- Saturation is part of the quantiser: values outside the range are clipped.
- More bits reduce the error, at a higher cost.
- Test: a ramp
linspacefrom to with samples; the quantised plot shows the characteristic and the difference is the error. - Observation from the formulas (not on the sheet): with the largest level is about , not , so the convention is inconsistent as written; ask the instructor.
- RMS value:
- analytic: , from with ;
- from samples: , computed with
sum()andsqrt(). - The estimate differs from the theory when the samples do not cover an integer number of periods. Vary
Phi_0andF_sto see the effect.
- Noise and SNR:
randn(n1,n2): Gaussian, zero mean, unit variance (the usual choice for noise);rand(n1,n2): uniform between 0 and 1;- ; for , ;
noise = sqrt(P_noise) * randn(1, N_sample);
V_noise = noise + V_sample;
x = snr(V_noise); % simulated SNR- Plots: both signals with
hold on,xlabel,ylabel,legend, colours'r','k','g'. - Summary of the steps: parameters, , time axis, continuous signal, , discrete axis, comparison, quantised signal, RMS, RMS versus , noise, comparison with and without noise, SNR.
- Typical errors:
- missing semicolons (flooding the command window);
- too many periods in (unreadable plot);
- forgetting the saturation of
q(i); - comparing an RMS from a non-integer number of periods with the theoretical value;
- plots without labels and legend.