## MATLAB Code for Pulse Code Modulation

clc;

close all;

clear all;

fm=input('Enter the message frequency (in Hz): ');

fs=input('Enter the sampling frequency (in Hz): ');

L=input('Enter the number of the quantization levels: ');

n = log2(L);

t=0:1/fs:1; % fs nuber of samples have tobe selected

s=8*sin(2*pi*fm*t);

subplot(3,1,1);

t=0:1/(length(s)-1):1;

plot(t,s);

title('Analog Signal');

ylabel('Amplitude--->');

xlabel('Time--->');

subplot(3,1,2);

stem(t,s);grid on; title('Sampled Sinal'); ylabel('Amplitude--->'); xlabel('Time--->');

% Quantization Process

vmax=8;

vmin=-vmax; %to quantize a signal s into L levels between vmin and vmax

del=(vmax-vmin)/L;

part=vmin:del:vmax; % level are between vmin and vmax with difference of del

code=vmin-(del/2):del:vmax+(del/2); % Contaion Quantized valuses

[ind,q]=quantiz(s,part,code); % Quantization process

% ind contain index number and q contain quantized values

l1=length(ind);

l2=length(q);

for i=1:l1

if(ind(i)~=0) % To make index as binary decimal so started from 0 to N

ind(i)=ind(i)-1;

end

i=i+1;

end

for i=1:l2

if(q(i)==vmin-(del/2)) % To make quantize value inbetween the levels

q(i)=vmin+(del/2);

end

end

subplot(3,1,3);

stem(t,q);grid on; % Display the Quantize values

title('Quantized Signal');

ylabel('Amplitude--->');

xlabel('Time--->');

% Encoding Process

figure

code=de2bi(ind,'left-msb'); % Cnvert the decimal to binary

k=1;

for i=1:l1

for j=1:n

coded(k)=code(i,j); % convert code matrix to a coded row vector

j=j+1;

k=k+1;

end

i=i+1;

end

subplot(2,1,1); grid on;

stairs(coded); % Display the encoded signal

axis([0 100 -2 3]); title('Encoded Signal');

ylabel('Amplitude--->');

% Demodulation Of PCM signal

qunt=reshape(coded,n,length(coded)/n);

index=bi2de(qunt','left-msb'); % Getback the index in decimal form

q=del*index+vmin+(del/2); % getback Quantized values

subplot(2,1,2); grid on;

plot(t,q);

title('demodulated signal without low-pass filter');

% % % Demodulation after applying low-pass filter

figure()

% Low-pass Filter Design

fc = fm; % Cutoff frequency for the low-pass filter

order = 1; % Filter order (first-order Butterworth filter)

% Design the low-pass Butterworth filter

[b, a] = butter(order, fc/(fs/2), 'low');

% Apply the low-pass filter to the signal

filtered_signal = filtfilt(b, a, q);

plot(t,s);

title('demodulated signal after applying low-pass filter')

## Output

Enter the sampling frequency (in Hz): 10000

Enter the number of the quantization levels: 8

>>