2nd order delta sigma modulator in matlab

Here's an example MATLAB code for simulating a second-order delta-sigma modulator:

main.m
%% Parameters
Fs = 1e6;       % Sampling frequency
OSR = 64;       % Oversampling ratio
f0 = Fs/4;      % Signal frequency
f1 = Fs/3;      % Desired output cutoff frequency
K = OSR/2;      % Second-order loop filter gain
OSR_eff = OSR/2;% Effective OSR after decimation by 2

%% Generate input signal
N = 1e5;        % Number of samples
t = (0:N-1)/Fs; % Time vector
x = sin(2*pi*f0*t); % Input signal

%% Second-order delta-sigma modulator
acc = 0;        % Integrator accumulator
y = zeros(1,N); % Output signal
for n = 1:N
    % Quantizer
    d = x(n) - acc;
    s = sign(d);
    v = min(abs(d), 1); % Symmetric (mid-tread) quantizer
    q = s*v;

    % Feedback DAC
    e = q/K;
    
    % Integrators
    z1 = e - y(n);
    acc = acc + K*z1;
    z2 = acc - y(n);
    y(n+1) = z1 + z2;
end
y = y(1:N); % Remove last sample

%% Decimate output signal
M = OSR_eff;    % Decimation factor
y = decimate(y, M);

%% Plot spectra
X = fft(x);
Y = fft(y);
f = (0:N-1)*Fs/N;
f_dec = (0:length(y)-1)*Fs/(M*N);

figure;
subplot(2,1,1);
plot(f/1e3, mag2db(abs(X)));
xlabel('Frequency (kHz)');
ylabel('Magnitude (dBFS)');
title('Input Signal Spectrum');
subplot(2,1,2);
plot(f_dec/1e3, mag2db(abs(Y)));
xlabel('Frequency (kHz)');
ylabel('Magnitude (dBFS)');
title('Output Spectrum');
1274 chars
56 lines

This code generates a sinusoidal input signal, applies a second-order delta-sigma modulator, and then decimates the output signal by a factor of two. The power spectrum of the input and output signals are plotted for comparison.

Note that the loop filter gain K and cutoff frequency f1 should be chosen carefully to avoid instability and achieve the desired noise shaping performance. Additionally, this example code uses a symmetric (mid-tread) quantizer for simplicity, but other quantization schemes can be used depending on the application.

gistlibby LogSnag