Salta al contenuto
Note per Studenti Lab 5 - ADC with Matlab Report

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 .m extension.
  • Scripts execute instructions sequentially; usual programming statements (for cycles, conditionals if...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

v(t)=V0sin⁡(2πF0t+ϕ0)v(t) = V_0 \sin(2\pi F_0 t + \phi_0)

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, that F_0 = 20; is a frequency of 20 Hz.
  • Group all assignments in a dedicated part of the code. Example on the sheet:
matlab
% *********************
% 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 a figure with one or more plot commands; choose T_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_W the samples are close enough to approximate the continuous trend.

Time axis of the "continuous" signal:

matlab
t = linspace(0, T_W, N);

This imposes NN equidistant points in the interval from 0 to TWT_W; each point is TW/(N−1)T_W/(N-1) from the closest.

Continuous sinusoidal signal:

matlab
V = V_0 * sin(2*pi*F_0*t + Phi_0);

Display:

matlab
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 TW/NT_W/N 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 TWT_W is

matlab
N_sample = round(T_W / T_s);

(round() rounds to the closest integer). The vector of sampling time instants:

matlab
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:

matlab
V_sample = V_0 * sin(2*pi*F_0*t_sample + Phi_0);

Comparison of the continuous and sampled signal in the same chart:

matlab
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:

matlab
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 ±VFS\pm V_{FS};
  • Nbit, the number of bits bb. There are 2b2^b quantisation levels, whose numerical values belong to the set

{−2Nbit−1,…,0,…,2Nbit−1−1}\{-2^{Nbit-1}, \ldots, 0, \ldots, 2^{Nbit-1} - 1\}

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):

matlab
Delta_q = V_FS/(2^Nbit);

Quantisation level of each sample:

matlab
q(i) = round(V_sample(i)/Delta_q);

The integer values must be limited to the allowed range (saturation effect of the quantiser):

  • if q(i)>2Nbit−1−1q(i) > 2^{Nbit-1} - 1 then q(i)=2Nbit−1−1q(i) = 2^{Nbit-1} - 1;
  • if q(i)<−2Nbit−1q(i) < -2^{Nbit-1} then q(i)=−2Nbit−1q(i) = -2^{Nbit-1}.

Quantised value of the samples:

matlab
V_q(i) = q(i) * Delta_q;

Quantisation error: difference between the quantised signal and the real (sampled) one:

matlab
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 −VFS-V_{FS} to +VFS+V_{FS} (generate it with linspace()), with a number of samples KK much larger than the number of levels (K≫2bK \gg 2^b). 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 −2Nbit−1-2^{Nbit-1} to 2Nbit−1−12^{Nbit-1}-1, the largest representable value is about VFS/2V_{FS}/2, so the step formula and the stated input range ±VFS\pm V_{FS} 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:

VRMS=V02V_{RMS} = \frac{V_0}{\sqrt{2}}

from the general formula

VRMS=1T0∫t0t0+T0v2(t) dtV_{RMS} = \sqrt{\frac{1}{T_0}\int_{t_0}^{t_0+T_0} v^2(t)\,dt}

with T0=1/F0T_0 = 1/F_0 the period of the sine.

With only NN samples the RMS is estimated as

VRMS=1N∑n=0N−1v2(nTs)V_{RMS} = \sqrt{\frac{1}{N}\sum_{n=0}^{N-1} v^2(nT_s)}

The vector v2(nTs)v^2(nT_s) is obtained by squaring each element of v(nTs)v(nT_s); 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 NN 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 of n1 rows and n2 columns;
  • randn(n1, n2): random numbers with Gaussian distribution of zero mean and unit variance. Since noise is usually Gaussian, randn is 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 (VRMS2V_{RMS}^2) and the noise power PnoiseP_{noise} is the variance (dimension amplitude squared):

SNR=VRMS2PnoiseSNR = \frac{V_{RMS}^2}{P_{noise}}

Example from the sheet: if SNR=10SNR = 10 the signal power is ten times the noise power, hence Pnoise=VRMS2/10P_{noise} = V_{RMS}^2/10. To obtain noise samples with that power, the output of randn() is multiplied by the standard deviation Pnoise\sqrt{P_{noise}}:

matlab
noise = sqrt(P_noise) * randn(1, N_sample);

Noisy signal:

matlab
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), where y is the vector of samples of the noisy signal and snr() is a MATLAB function.

Summary of the steps (as listed on the sheet)

  1. define the parameters of the sinusoidal signal;
  2. define the observation interval TWT_W;
  3. define the time axis tt;
  4. generate the sinusoidal continuous signal;
  5. define the sampling frequency;
  6. compute the discrete time axis;
  7. compare the two sinusoidal signals;
  8. build the quantised signal;
  9. estimate the RMS value;
  10. observe the variations of the RMS value depending on the sampling frequency;
  11. add noise to the signal;
  12. compare the signals with and without noise;
  13. compute the SNR.

Versione ripasso

matlab
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 TW/(N−1)T_W/(N-1): linspace does not show the sampling period.

  • Sampling: Ts=1/FsT_s=1/F_s, then N_sample = round(T_W / T_s);, t_sample = [0:1:(N_sample - 1)] * T_s; and V_sample evaluated at t_sample. Overlay with hold on and '*r'. A plain plot of the samples joins them by linear interpolation. Check FsF_s against the Nyquist-Shannon condition by trying several values.
  • Uniform quantiser: full scale V_FS, Nbit bits, 2b2^{b} levels with values in {−2Nbit−1,…,2Nbit−1−1}\{-2^{Nbit-1},\dots,2^{Nbit-1}-1\}.
matlab
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 linspace from −VFS-V_{FS} to +VFS+V_{FS} with K≫2bK\gg 2^b samples; the quantised plot shows the characteristic and the difference is the error.
  • Observation from the formulas (not on the sheet): with Δq=VFS/2Nbit\Delta_q=V_{FS}/2^{Nbit} the largest level is about VFS/2V_{FS}/2, not VFSV_{FS}, so the convention is inconsistent as written; ask the instructor.
  • RMS value:
    • analytic: VRMS=V02V_{RMS}=\dfrac{V_0}{\sqrt{2}}, from VRMS=1T0∫t0t0+T0v2(t) dtV_{RMS}=\sqrt{\dfrac{1}{T_0}\displaystyle\int_{t_0}^{t_0+T_0}v^2(t)\,dt} with T0=1/F0T_0=1/F_0;
    • from NN samples: VRMS=1N∑n=0N−1v2(nTs)V_{RMS}=\sqrt{\dfrac{1}{N}\displaystyle\sum_{n=0}^{N-1}v^2(nT_s)}, computed with sum() and sqrt().
    • The estimate differs from the theory when the NN samples do not cover an integer number of periods. Vary Phi_0 and F_s to 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;
    • SNR=VRMS2PnoiseSNR=\dfrac{V_{RMS}^2}{P_{noise}}; for SNR=10SNR=10, Pnoise=VRMS2/10P_{noise}=V_{RMS}^2/10;
matlab
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, TWT_W, time axis, continuous signal, FsF_s, discrete axis, comparison, quantised signal, RMS, RMS versus FsF_s, noise, comparison with and without noise, SNR.
  • Typical errors:
    • missing semicolons (flooding the command window);
    • too many periods in TWT_W (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.

Teoria collegata