DC & SS LAB AR23 Student Manual
DC & SS LAB AR23 Student Manual
Prepared by
Mr. S. BALA RAMA MURTHY, M. E. (PhD),
Associate Professor,
Dept. of ECE
DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING
This is to certify that Mr. S. Balarama Murty, Associate Professor, has prepared the
DIGITAL CIRCUITS AND SIGNAL SIMULATION LAB laboratory manual as per
Autonomous Syllabus REGULATIONS: AR23 with utmost care, and I thoroughly verified
the manual and approved it.
Prepared by Approved by
MISSION
To develop the students into outstanding professionals through innovative Teaching Learning process.
To uphold research through long term Academia – Industry interaction
To inculcate ethical standards and moral values.
ECE DEPARTMENT
VISION
MISSION
M1: To prepare technically competent graduates by establishing a conducive learner centric, academic
environment that uses innovative teaching learning processes.
M2: To create research interests in the graduates by bringing in real time engineering challenges through
industry collaborations.
M3: To make the graduates socially responsible citizens who provide sustainable solutions maintaining
ethical and professional standards
CODE OF CONDUCT FOR THE LABORATORIES
A. All students must observe the Dress Code while in the laboratory.
K. All students are liable for any damage to the accessories due to their own negligence.
L. All interfacing kits connecting cables must be RETURNED if taken from the lab
supervisor.
M. Students are strictly PROHIBITED from taking out any items from the laboratory.
N. Students are NOT allowed to work alone in the laboratory without the Lab Supervisor.
O. USB Ports have been disabled if you want to use USB drive consult lab supervisor.
P. Report immediately to the Lab Supervisor if any malfunction of the accessories, is there
PEO1: Our graduates will solve real – world problems of the 21 st Century in Electronics and
Communication Engineering with satisfactory professional growth and required skills.
PEO2: Our graduates will be able to pursue higher studies and engage in lifelong learning to adapt to
evolving technologies and career demands.
PEO3: Our graduates will demonstrate ethical behavior and social responsibility in their professional work.
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
PO2: Problem analysis: Identify, formulate, research literature, and analyze complex engineering problems
reaching substantiated conclusions using the first principles of mathematics, natural sciences, and engineering
sciences.
PO3: Design/development of solutions: Design solutions for complex engineering problems and system
components or processes that meet the specified needs with appropriate consideration for the public health and
safety, and the cultural, societal, and environmental considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multi-disciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multi-disciplinary environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
PSO1: Apply the fundamental concept of Electronics and Communication Engineering to design a variety of
components and systems for applications including image and signal processing. Communication,
networking, embedded systems, VLSI and control system.
PSO2: Select and apply cutting-edge engineering hardware and software tools to solve complex electronics
and communication engineering problems.
11 INTRODUCTION TO MATLAB
GENERATE VARIOUS SIGNALS AND SEQUENCES: PERIODIC AND APERIODIC, UNIT
12 IMPULSE, UNIT STEP, SQUARE, SAW TOOTH, TRIANGULAR, SINUSOIDAL, RAMP, SINC
FUNCTION
OPERATIONS ON SIGNALS AND SEQUENCES: ADDITION, MULTIPLICATION,
13
SCALING, SHIFTING, FOLDING, COMPUTATION OF ENERGY AND AVERAGE POWER
WRITE A PROGRAM TO FIND THE TRIGONOMETRIC & EXPONENTIAL FOURIER
SERIES COEFFICIENTS OF A RECTANGULAR PERIODIC SIGNAL. RECONSTRUCT THE
14
SIGNAL BY COMBINING THE FOURIER SERIES COEFFICIENTS WITH APPROPRIATE
WEIGHTINGS- PLOT THE DISCRETE SPECTRUM OF THE SIGNAL.
WRITE A PROGRAM TO FIND FOURIER TRANSFORM OF A GIVEN SIGNAL. PLOT ITS
15
AMPLITUDE AND PHASE SPECTRUM.
WRITE A PROGRAM TO CONVOLVE TWO DISCRETE TIME SEQUENCES. PLOT ALL
16
THE SEQUENCES.
WRITE A PROGRAM TO FIND AUTOCORRELATION AND CROSS CORRELATION OF
17
GIVEN SEQUENCES.
WRITE A PROGRAM TO VERIFY LINEARITY AND TIME INVARIANCE PROPERTIES OF
18
A GIVEN CONTINUOUS SYSTEM.
WRITE A PROGRAM TO GENERATE DISCRETE TIME SEQUENCE BY SAMPLING A
19 CONTINUOUS TIME SIGNAL. SHOW THAT WITH SAMPLING RATES LESS THAN
NYQUIST RATE, ALIASING OCCURS WHILE RECONSTRUCTING THE SIGNAL.
WRITE A PROGRAM TO GENERATE COMPLEX GAUSSIAN NOISE AND FIND ITS MEAN,
20 VARIANCE, PROBABILITY DENSITY FUNCTION (PDF) AND POWER SPECTRAL
DENSITY (PSD).
PART A: DIGITAL CIRCUITS LAB USING VERILOG
INTRODUCTION TO XILINX
INTRODUCTION
Xilinx Tools is a suite of software tools used for the design of digital circuits implemented using Xilinx Field
Programmable Gate Array (FPGA) or Complex Programmable Logic Device(CPLD). The design procedure
consists of (a) design entry, (b) synthesis and implementation of the design, (c) functional simulation and d)
testing and verification. Digital designs can be entered in various ways using the above CAD tools: using a
schematic entry tool, using a hardware description language (HDL) – Verilog or VHDL or a combination of
both. In this lab we will only use the design flow that involves the use of Verilog HDL.
The CAD tools enable you to design combinational and sequential circuits starting with Verilog HDL design
specifications. The steps of this design procedure are listed below:
A Verilog input file in the Xilinx software environment consists of the following segments:
Xilinx Tools can be started by clicking on the Project Navigator Icon on the Windows desktop. This should
open up the Project Navigator window on your screen. This window shows (see Figure 1) the last accessed
project.
Fig 1: XILINX PROJECT NAVIGATOR WINDOW
OPENING A PROJECT
Select File->New Project to create a new project. This will bring up a new project window (Figure 2) on the
desktop. Fill up the necessary entries as follows:
Example: If the project name were “o_gate”, enter “o_gate” as the project name and then click “Next”.
Device Family: Family of the FPGA/CPLD used. In this laboratory we will be using the Spartan3EFPGA’s.
Device: The number of the actual device.
Package: The type of package with the number of pins. The Spartan FPGA used in this lab is packaged in
CP132package.
Speed Grade: The Speed grade is “-4”.
Synthesis Tool: XST [VHDL/Verilog]
Simulator: The tool used to simulate and verify the functionality of the design. Modelsim simulator is
integrated in the Xilinx ISE. Hence choose “Modelsim-XE Verilog” as the simulator or even Xilinx ISE
Simulator can be used.
All project files such as schematics, netlists, Verilog files, VHDL files, etc., will be stored in a subdirectory
with the project name. A project can only have one top level HDL source file (or schematic). Modules can be
added to the project to create a modular, hierarchical design.
In order to open an existing project in Xilinx Tools, select File->Open Project to show the list of projects on the
machine. Choose the project you want and click OK.
Clicking on NEXT on the above window brings up the following window:
Select Verilog Module and in the “File Name:” area, enter the name of the Verilog source file you are going to
create. Also make sure that the option Add to project is selected so that the source need not be added to the
project again. Then click on Next to accept the entries. This pops up the following window (Figure 5).
In the Port Name column, enter the names of all input and output pins and specify the Direction accordingly. A
Vector/Bus can be defined by entering appropriate bit numbers in the MSB/LSB columns. Then click on
Next>to get a window showing all the new source information (Figure 6). If any changes are to be made, just
click on <Back to go back and make changes. If everything is acceptable, click on Finish
>Next >Next >Finish to continue.
Once you click on Finish, the source file will be displayed in the sources window in the Project Navigator
(Figure 1).
If a source has to be removed, just right click on the source file in the Sources in Project window in the Project
Navigator and select Remove in that. Then select Project ->Delete Implementation Data from the Project
Navigator menu bar to remove any related files.
Editing the Verilog source file
The source file will now be displayed in the Project Navigator window (Figure 8).The source. File window can
be used as a text editor to make any necessary changes to the source file. All the input/output pins will be
displayed. Save your Verilog program periodically by selecting the File->Save from the menu. You can also
edit Verilog programs in any text editor and add them to the project directory using “Add Copy Source”.
Provide a name for the test bench in the file name textbox and select ‘Verilog test fixture’ among the file types
in the list on the right side as shown in figure 9.
Click on ‘Next’ to proceed. In the next windows elect the source file with which you want to associate the test
Click on Next to proceed. In the next window click on Finish. You will now be provided with a template for
your test bench. If it does not open automatically click the radio button next to Simulation.
You should now be able to view your test bench template.
To save the simulation results, Go to the waveform window of the Modelsim simulator, Click on File -> Print
to Postscript -> give desired filename and location.
Note that by default, the waveform is“ zoomed in” to the nano second level. Use the zoom control Is to display
the entire waveform.
Else a normal print screen option can be used on the waveform window and subsequently stored in P
For taking printouts for the lab reports, convert the black background to white in Tools ->Edit Preferences.
Then click Wave Windows -> Wave Background attribute.
The design has to be synthesized and implemented before it can be checked for correctness, by running
functional simulation or downloaded onto the prototyping board. With the top- level Verilog file opened (can
be done by double-clicking that file) in the HDL editor window in the right half of the Project Navigator, and
the view of the project being in the Module view , the implement design option can be seen in the process view.
Design entry utilities and Generate Programming File options can also be seen in the process view. The former
can be used to include user constraints, if any and the latter will be discussed later.
To synthesize the design, double click on the Synthesize Design option in the
Processes window.
To implement the design, double click the Implement design option in the Processes window.It will gothrough
steps like Translate, Map and Place & Route. If any of these steps could not be done or done with errors, it will
place a X mark in front of that, otherwise a tick mark will be placed after each of them to indicate the
successful completion. If every thing is done successfully, a tick mark will be placed before the Implement
Design option. If there are warnings, one can see mark in front of the option indicating that there are some
warnings. One can look at the warnings or errors in the Console window present at the bottom of the Navigator
window. Every time the design file is saved; all these marks disappear asking for a fresh compilation.
By double clicking it opens the top level module showing only input(s) and output(s) as shown below.
Fig 15: TOP LEVEL HIERARCHY OF THE DESIGN
By double clicking the rectangle, it opens the realized internal logic as shown below.
Fig 16: REALIZED LOGIC BY THE XILINX ISE FOR THE VERILOG CODE
EXPERIMENT – 1
DESIGN A SIMPLE COMBINATIONAL CIRCUIT WITH FOUR
VARIABLES AND OBTAIN MINIMAL SOP EXPRESSION AND VERIFY
THE TRUTH TABLE
AIM
To design a simple combinational circuit with four variables and obtain minimal SOP expression and verify the
truth table
APPARATUS REQUIRED
1. PC with windows (95/98/XP/NT/2000).
2. Xilinx Software
THEORY
We can minimize Boolean expressions of 3, 4 variables very easily using K-map without using any Boolean
algebra theorems. K-map can take two forms Sum of Product (SOP) and Product of Sum (POS) according to
the need of problem. K-map is table like representation but it gives more information than TRUTH TABLE.
We fill grid of K-map with 0’s and 1’s then solves it by making groups.
We’ll design a combinational circuit with four inputs: A, B, C, D and a single output F. Let’s define the output
F using a truth table
Decimal Notation Input Output
A B C D F
0 0 0 0 0 0
1 0 0 0 1 1
2 0 0 1 0 1
3 0 0 1 1 0
4 0 1 0 0 1
5 0 1 0 1 0
6 0 1 1 0 0
7 0 1 1 1 1
8 1 0 0 0 1
9 1 0 0 1 0
10 1 0 1 0 0
11 1 0 1 1 1
12 1 1 0 0 0
13 1 1 0 1 1
14 1 1 1 0 1
15 1 1 1 1 0
F(A,B,C,D) = Σ m (1,2,4,7,8,11,13,14)
F = A'B'C D + A'B C' D' + A B' C D + A B C' D + A B' C' D' + A'B C D
PROGRAM
VERILOG DESIGN CODE
module combinational_circuit (
input A, B, C, D,
output F);
endmodule
TEST BENCH
module combinational_circuit_tb;
reg A, B, C , D;
wire F;
integer i;
initial begin
$dumpfile(“combinational_circuit.vcd”);
$dumpvars(0,combinational_circuit_tb);
$display("A B C D | F");
$display("--------|--");
for (i = 0; i < 16; i = i + 1) begin
{A, B, C, D} = i;
end
$finish;
end
endmodule
OUTPUT
RESULT
Hence, we are able to design a combinational circuit using a given Boolean expression and subsequently verify
the truth table through the program code.
EXPERIMENT – 2
VERIFY THE OF FUNCTIONALITY OF 3 TO 8-LINE DECODER
AIM
APPARATUS REQUIRED
THEORY
A 3-to-8 line decoder is a combinational logic circuit that takes 3 input lines and decodes them into one of 8
output lines. Each output line corresponds to one of the 8 combinations of the 3 input bits. Only one output is
active (typically high, 1) at any time, corresponding to the binary value of the input.
Functionality of 3-to-8 Line Decoder
Inputs: A, B, C (3 bits)
Outputs: Y0 to Y7 (8 outputs)
Enable signal (optional): Usually used to control whether the decoder is active.
When enable = 1:
PROGRAM
module decoder3to8 (
input wire [2:0] in, // 3-bit input
input wire en, // enable signal
output reg [7:0] out // 8-bit output);
endmodule
TEST BENCH:
module tb_decoder3to8;
reg [2:0] in;
reg en;
wire [7:0] out;
decoder3to8 uut (
.in(in),
.en(en),
.out(out)
);
initial begin
$dumpfile("top_module.vcd");
$dumpvars (0, tb_top_module);
$display("Time\t en in\t out");
$monitor("%0t\t %b %b\t %b", $time, en, in, out);
en = 0; in = 3'b000; #10;
en = 1; in = 3'b000; #10;
in = 3'b001; #10;
in = 3'b010; #10;
in = 3'b011; #10;
in = 3'b100; #10;
in = 3'b101; #10;
in = 3'b110; #10;
in = 3'b111; #10;
en = 0; in = 3'b011; #10;
$finish;
end
endmodule
OUTPUT
RESULT
AIM
To design 4 variable logic function verification using 8 to1 multiplexer and verify the truth table
APPARATUS REQUIRED
THEORY
A 4 – variable logic function using an 8-to-1 multiplexer (MUX) in Verilog involves using three of the
variables as select lines and the fourth variable to control the data inputs, implementing the function through
data input values.
D=1 ⇒ D
S0 (A) S1 (B) S2 (C)
0 0 0 I0 = D
D=0 ⇒ ~D
0 0 1 — I1 = 0
D=0,1 ⇒ 1
0 1 0 I2 = ~D
D=0,1 ⇒ 1
0 1 1 I3 = 1
1 0 0 I4 = 1
1 0 1 — I5 = 0
D=1 ⇒ D
1 1 0 — I6 = 0
1 1 1 I7 = D
PROGRAM
module mux8to1 (
input wire [2:0] sel,
input wire D,
output wire F
);
endmodule
TESTBENCH:
module tb_mux_function;
reg A, B, C, D;
wire F;
wire [3:0] inputs;
wire expected;
initial begin
$dumpfile("top_module.vcd");
$dumpvars (0, tb_top_module);
$display(" A B C D | F (MUX) | Expected | Match");
for (int i = 0; i < 16; i = i + 1) begin
{A, B, C, D} = i;
#5;
$display(" %b %b %b %b | %b | %b | %s",
A, B, C, D, F, expected, (F === expected) ? "Yes" : "No");
end
$finish;
end
endmodule
OUTPUT
Fig 3.2: OUTPUT OF A 4 VARIABLE BOOLEAN EXPRESSION CONDENSED INTO AN 8 X 1 MULTIPLEXER
RESULT
Hence we design 4 variable logic function verification using 8 to1 multiplexer and verified the truth table.
EXPERIMENT – 5
DESIGN AND VERIFY THE CIRCUIT DIAGRAM OF A SINGLE BIT
COMPARATOR AND VERIFY THE OUTPUT IN VERILOG
AIM
To design and verify the circuit diagram of a single bit comparator and verify the output in Verilog.
APPARATUS REQUIRED
THEORY
A single-bit comparator is a combinational logic circuit that compares two 1-bit binary inputs, typically labeled
A and B, and determines their relations
A 1-bit comparator compares two single-bit binary values, A and B.
A_eq_B → 1 when A == B
A_gt_B → 1 when A > B
A_lt_B → 1 when A < B
TRUTH TABLE:
Inputs Output
A B A>B A=B A<B
0 0 0 1 0
0 1 0 0 1
1 0 1 0 0
1 1 0 1 0
1 0 1 0 0
1 1 0 1 0
PROGRAM
VERILOG DESIGN CODE:
module comparator_1bit (
input wire A,
input wire B,
output wire A_eq_B,
output wire A_gt_B,
output wire A_lt_B);
endmodule
TESTBENCH:
module tb_comparator_1bit;
reg A, B;
wire A_eq_B, A_gt_B, A_lt_B;
// Instantiate comparator
comparator_1bit uut (
.A(A),
.B(B),
.A_eq_B(A_eq_B),
.A_gt_B(A_gt_B),
.A_lt_B(A_lt_B)
);
initial begin
$dumpfile("comparator_1bit.vcd");
$dumpvars (0,tb_comparator_1bit );
$display("A B | A_eq_B A_gt_B A_lt_B");
$display("--------------------------");
endmodule
OUTPUT
RESULT
Hence we have designed and verified the functionality of 1 – bit comparator in Verilog.
EXPERIMENT – 6
DESIGN AND VERIFY THE FUNCTIONALITY OF DIFFERENT FLIP –
FLOPS IN VERILOG
AIM
APPARATUS REQUIRED
THEORY
A flip flop is an electronic device or to be precise a kind of memory component that can hold one bit of data. A
flip flop has two states, which are "SET" and "RESET". Those states are represented with the binary values 0
and 1. The flip flop remains in its current state until it receives a signal that switches it to opposite state. A
clock or pulse signal may "trigger" the flip flop to change state.
1. SR FLIP-FLOP:
In the flip flop, with the help of preset and clear when the power is switched ON, the states of the circuit keeps
on changing, that is it is uncertain. It may come to set (Q=1) or reset (Q’=0) state. In many applications, it is
desired to initially set or reset the flip flop that is the initial state of the flip flop that needs to be assigned. This
thing is accomplished by the preset (PR) and the clear (CLR)
The Operations of S-R Flip Flop:
Case 1(PR=CLR=1): The asynchronous inputs are inactive and the flip flop responds freely to the S, R and the
CLK inputs in the normal way.
Case 2(PR=0 and CLR=1): This is used when the Q is set to 1.
Case 3(PR=1 and CLR=0): This is used when the Q’ is set to 1.
Case 4(PR=CLR=0): This is an invalid state.
Fig 6.1: LOGIC DIAGRAM AND TRUTH TABLE FOR SR – FLIP FLOP
2. T- FLIP-FLOP:
The T Flip Flop consists of data input (T), a clock input (CLK), and two outputs: Q and Q' (the complement of
Q).
A T flip-flop (Toggle flip-flop) is a type of sequential logic circuit that changes (toggles) its output on each
clock cycle if the T input is high (T = 1). If T = 0, the output remains unchanged. It's commonly used for binary
counters and frequency division.
Operation of T Flip-Flop
Case 1 (T=0):In this condition the flip-flop remains in its current state regardless of clock input, also the Output
Q will remain unchanged unit the value of T will not change.
Case 2 (T=1):In this condition the flip flop will change when T input is 1,At each rising or falling edge of the
clock signal the output Q will be in complementary state
Fig 6.2: LOGIC DIAGRAM AND TRUTH TABLE FOR T – FLIP FLOP
3. D FLIP-FLOP:
The D Flip Flop Consists a single data input(D), a clock input(CLK),and two outputs: Q and Q' (the
complement of Q).
A D flip-flop (or Data or Delay flip-flop) is a fundamental building block in digital electronics used to store one
bit of data. It's a type of sequential logic circuit that captures the value of the D input at a particular portion of
the clock cycle (typically the rising or falling edge of a clock signal) and outputs that value until the next clock
edge.
The operation of D Flip-Flip
Case 1 (PR=CLR=0): This conditions is represents as invalid state where both PR(present) and CLR(clear)
inputs are inactive.
Case 2 (PR=0 and CLR=1): This state is set state in which PR is inactive (0) and CLR is active(1) and the
output Q is set to 1.
Case 3 (PR=1 and CLR=0): This state is reset state in which PR is active (1) and CLR is inactive (0) and the
complementary output Q' is set to 1.
Case 4 (PR=CLR=1): In This state the flip flop behaves as normal, both PR and CLR inputs are active(1).
Fig 6.3: LOGIC DIAGRAM AND TRUTH TABLE FOR D – FLIP FLOP
4. J – K FLIP-FLOP:
In JK flip flops, the basic structure of the flip flop which consists of Clock (CLK), Clear (CLR), and Preset
(PR).
the Operations of J-K Flip Flop
Case 1 (PR=CLR=0): This condition is in its invalid state.
Case 2 (PR=0 and CLR=1): The PR is activated which means the output in the Q is set to 1. Therefore, the flip
flop is in the set state.
Case 3 (PR=1 and CLR=0): The CLR is activated which means the output in the Q’ is set to 1. Therefore, the
flip flop is in the reset state.
Case 4 (PR=CLR=1): In this condition the flip flop works in its normal way whereas the PR and CLR gets
deactivated
Fig 6.4: LOGIC DIAGRAM AND TRUTH TABLE FOR JK – FLIP FLOP
PROGRAM
// S – R Flip Flop
module sr_flip_flop (
input wire S, // Set input
input wire R, // Reset input
output reg Q, // Output
output wire Q_bar // Complement of output
);
always @ (S or R) begin
if (S == 1 && R == 0)
Q <= 1; // Set
else if (S == 0 && R == 1)
Q <= 0; // Reset
else if (S == 0 && R == 0)
Q <= Q; // Hold state
else
Q <= 1'bx; // Invalid state (S=1, R=1)
end
endmodule
TESTBENCH:
module tb_sr_flip_flop;
reg S, R;
wire Q, Q_bar;
sr_flip_flop uut (
.S(S),
.R(R),
.Q(Q),
.Q_bar(Q_bar)
);
initial begin
$dumpfile("sr_flip_flop.vcd");
$dumpvars (0,tb_ sr_flip_flop);
// Test cases
S = 0; R = 0; #10; // Hold state
S = 1; R = 0; #10; // Set
S = 0; R = 1; #10; // Reset
S = 0; R = 0; #10; // Hold
S = 1; R = 1; #10; // Invalid
$finish;
end
endmodule
// T – Flip Flop
VERILOG DESIGN CODE:
module t_flip_flop (
input wire clk, // Clock input
input wire rst, // Asynchronous reset
input wire T, // Toggle input
output reg Q // Output
);
endmodule
TESTBENCH:
module tb_t_flip_flop;
reg clk, rst, T;
wire Q;
t_flip_flop uut (
.clk(clk),
.rst(rst),
.T(T),
.Q(Q)
);
// Clock generation
initial begin
$dumpfile("t_flip_flop.vcd");
$dumpvars (0,tb_ t_flip_flop);
clk = 0;
forever #5 clk = ~clk; // 10 time units period
end
initial begin
$monitor("Time=%0t T=%b Q=%b", $time, T, Q);
// Initial state
rst = 1; T = 0; #10;
rst = 0;
// Toggle on T = 1
T = 1; #40;
// Hold on T = 0
T = 0; #20;
// Toggle again
T = 1; #20;
$finish;
end
endmodule
// D – Flip Flop
VERILOG DESIGN CODE:
module d_flip_flop (
input wire clk, // Clock input
input wire reset, // Asynchronous reset
input wire d, // Data input
output reg q // Output
);
endmodule
TESTBENCH:
module tb_d_flip_flop;
// Testbench signals
reg clk;
reg d;
wire q;
// Stimulus
initial begin
$dumpfile("d_flip_flop.vcd");
$dumpvars (0,tb_ d_flip_flop);
// Initialize signals
clk = 0;
d = 0;
// Display format
$display("Time\tclk\td\tq");
$monitor("%g\t%b\t%b\t%b", $time, clk, d, q);
endmodule
// J – K Flip Flop
module jk_flip_flop (
input wire clk, // Clock input
input wire j, // J input
input wire k, // K input
output reg q // Output
);
endmodule
TEST BENCH:
// Testbench signals
reg clk;
reg j, k;
wire q;
// Stimulus
initial begin
// Initialize
clk = 0;
j = 0;
k = 0;
// Display headers
$dumpfile("jk_flip_flop.vcd");
$dumpvars (0,tb_ jk_flip_flop);
$display("Time\tclk\tj\tk\tq");
$monitor("%g\t%b\t%b\t%b\t%b", $time, clk, j, k, q);
// Test sequence
#7 j = 0; k = 1; // Reset
#10 j = 1; k = 0; // Set
#10 j = 1; k = 1; // Toggle
#10 j = 0; k = 0; // Hold
#10 j = 1; k = 1; // Toggle
#10 j = 0; k = 1; // Reset
#10 j = 1; k = 0; // Set
#10 $finish;
end
endmodule
OUTPUT
\
Fig 6.6: OUTPUT WAVEFORM OF T – FLIP FLOP
RESULT
Hence, we can design various type of flip – flops and verify them using test bench in Verilog.
EXPERIMENT – 7
DESIGN AND VERIFY THE OPERATION OF 4-BIT UNIVERSAL SHIFT
REGISTER FOR DIFFERENT MODES OF OPERATION
AIM
To Design and verify the operation of 4 – bit Universal Shift Register for different Modes of operation.
APPARATUS REQUIRED
THEORY
A Universal shift register is a register which has both the right shift and left shift with parallel load capabilities.
Universal shift registers are used as memory elements in computers. A Unidirectional shift register is capable of
shifting in only one direction. A bidirectional shift register is capable of shifting in both the directions. The
Universal shift register is a combination design of bidirectional shift register and a unidirectional shift register
with parallel load provision.
A universal shift register operates in any of three modes: according to the control signals. If the "Shift Left"
control signal is active, there is a shift in data one position to the left, while the leftmost bit is lost and the
rightmost bit is replaced from the serial input. In "Shift Right," the data moves right with the loss of the
rightmost bit and loading of the leftmost from the serial input. "Parallel Load" allows the simultaneous loading
of data from all input lines. For this, the register retains its current data if none of the control signals have been
activated. Internally, their obvious external interface is implemented by using multiplexers and flip-flops: the
bits are held by a flip-flop, while a multiplexer acts for the input source at each operation.
The first input (zeroth pin of multiplexer) is connected to the output pin of the corresponding flip-flop.
The second input (first pin of multiplexer) is connected to the output of the very-previous flip flop which
facilitates the right shift.
The third input (second pin of multiplexer) is connected to the output of the very-next flip-flop which facilitates
the left shift.
The fourth input (third pin of multiplexer) is connected to the individual bits of the input data which facilitates
parallel loading.
Fig 7.1: LOGIC DIAGRAM OF A UNIVERSAL 4 – BIT SHIFT REGISTER
PROGRAM
VERILOG DESIGN CODE:
module universal_shift_register (
input wire clk,
input wire reset,
input wire [1:0] sel, // Mode select
input wire [3:0] d, // Parallel input
input wire sin_left, // Serial input for shift left
input wire sin_right, // Serial input for shift right
output reg [3:0] q // Register output
);
endmodule
TESTBENCH:
module universal_shift_register_tb;
universal_shift_register uut (
.clk(clk),
.reset(reset),
.sel(sel),
.d(d),
.sin_left(sin_left),
.sin_right(sin_right),
.q(q)
);
// Clock generation
always #5 clk = ~clk;
initial begin
$dumpfile("universal_shift_register.vcd");
$dumpvars(0,tb_universal_shift_register);
// Monitor signals
$monitor("Time=%0t clk=%b reset=%b sel=%b d=%b sin_l=%b sin_r=%b q=%b",
$time, clk, reset, sel, d, sin_left, sin_right, q);
clk = 0;
reset = 1;
sel = 2'b00; d = 4'b0000;
sin_left = 0; sin_right = 0;
#10 reset = 0;
// Hold
#10 sel = 2'b00;
// Shift Right
#10 sel = 2'b01; sin_right = 1;
// Shift Left
#10 sel = 2'b10; sin_left = 0;
// Finish
#10 $finish;
end
endmodule
OUTPUT
Fig 7.3: OUTPUT WAVEFORM OF A 4 – BIT SHIFT REGISTER
RESULT
Hence, we have designed and verified the operation of 4-bit Universal Shift Register for different Modes of
operation.
EXPERIMENT – 8
DESIGN UP COUNTER AND DOWN COUNTERS IN VERILOG
AIM
APPARATUS REQUIRED
THEORY
A Counter is a device which stores (and sometimes displays) the number of times a particular event or process
has occurred, often in relationship to a clock signal. Counters are used in digital electronics for counting
purpose, they can count specific event happening in the circuit. For example, in UP counter a counter increases
count for every rising edge of clock. Not only counting, a counter can follow the certain sequence based on our
design like any random sequence 0, 1, 3, 2….They can also be designed with the help of flip flops. They are
used as frequency dividers where the frequency of given pulse waveform is divided. Counters are sequential
circuit that count the number of pulses can be either in binary code or BCD form. The main properties of a
counter are timing, sequencing, and counting.
Counter works in two modes: Up counter, down counter
4 – BIT UP COUNTER:
A 4-bit counter requires four JK flip-flops (FF0 to FF3), connected in a way that ensures synchronous
operation.
The clock input is applied to all flip-flops simultaneously.
The output of each flip-flop represents a binary digit, with FF0 as the least significant bit (LSB) and FF3 as the
most significant bit (MSB).
Toggling of flip-flops occurs based on the previous state.
Each flip-flop’s J and K inputs are set to HIGH (1) for toggling.
The first flip-flop (FF0) toggles with every clock pulse.
Each subsequent flip-flop toggles when all the previous flip-flop outputs are HIGH
Fig 8.1: LOGIC DIAGRAM OF A 4 – BIT SYNCHRONOUS UP COUNTER
It can be seen above, that the external clock pulses (pulses to be counted) are fed directly to each of the J-K
flip-flops in the counter chain and that both the J and K inputs are all tied together in toggle mode, but only in
the first flip-flop, flip-flop FFA (LSB) are they connected HIGH, logic “1” allowing the flip-flop to toggle on
every clock pulse. Then the synchronous counter follows a predetermined sequence of states in response to the
common clock signal, advancing one state for each pulse.
The J and K inputs of flip-flop FFB are connected directly to the output QA of flip-flop FFA, but
the J and K inputs of flip-flops FFC and FFD are driven from separate AND gates which are also supplied with
signals from the input and output of the previous stage. These additional AND gates generate the required logic
for the JK inputs of the next stage.
If we enable each JK flip-flop to toggle based on whether or not all preceding flip-flop outputs (Q) are “HIGH”
we can obtain the same counting sequence as with the asynchronous circuit but without the ripple effect, since
each flip-flop in this circuit will be clocked at exactly the same time.
Then as there is no inherent propagation delay in synchronous counters, because all the counter stages are
triggered in parallel at the same time, the maximum operating frequency of this type of frequency counter is
much higher than that for a similar asynchronous counter circuit.
Wrap-around: Since it's 4-bit, after reaching 0000, the next decrement wraps around to 1111.
The design is similar to the up counter but modified to count in reverse order (1111 to 0000).
Instead of toggling on all HIGH states, each flip-flop toggles when all lower significant bits are LOW.
PROGRAM
//UP COUNTER
module up_counter_4bit (
input wire clk, // Clock input
input wire reset, // Synchronous reset
output reg [3:0] count // 4-bit counter output
);
endmodule
TESTBENCH:
module tb_up_counter_4bit;
reg clk;
reg reset;
wire [3:0] count;
// Instantiate the counter
up_counter_4bit uut (
.clk(clk),
.reset(reset),
.count(count)
);
// Clock generation
initial begin
clk = 0;
forever #5 clk = ~clk; // 10 time unit period
end
// Test stimulus
initial begin
$dumpfile("up_counter_4bit.vcd");
$dumpvars(0,tb_up_counter_4bit);
reset = 1; #10;
reset = 0; #150;
reset = 1; #10;
reset = 0; #50;
$finish;
end
initial begin
$monitor("Time = %0t | Reset = %b | Count = %b", $time, reset, count);
end
endmodule
// DOWN COUNTER
module down_counter_4bit (
input wire clk, // Clock input
input wire reset, // Synchronous reset
output reg [3:0] count // 4-bit counter output
);
endmodule
TESTBENCH:
module tb_down_counter_4bit;
reg clk;
reg reset;
wire [3:0] count;
// Clock generation
initial begin
clk = 0;
forever #5 clk = ~clk; // Clock period = 10 units
end
// Stimulus
initial begin
reset = 1; #10;
reset = 0; #100;
reset = 1; #10;
reset = 0; #50;
$finish;
end
initial begin
$dumpfile(“down_counter_4bit.vcd”);
$dumpvars(0,tb_ down_counter_4bit);
$monitor("Time = %0t | Reset = %b | Count = %b", $time, reset, count);
end
endmodule
OUTPUT
Fig 8.3: OUTPUT WAVEFORM OF A 4 – BIT SYNCHRONOUS UP COUNTER
RESULT
Hence we have designed a 4 – bit synchronous up – down counter using Verilog and verified it successfully.
EXPERIMENT – 9
DESIGN MOD – 8 SYNCHRONOUS COUNTER /ASYNCHRONOUS
COUNTERS IN VERILOG
AIM
APPARATUS REQUIRED
THEORY
A mod-8 counter is a modulo – 8 counter, which means it cycles through 8 distinct states before repeating. It's
commonly used in digital systems for counting, timing, and sequencing tasks.
Modulus 8 (counts from 0 to 7)
Bits
3 bits (since 2³ = 8)
Required
Can be up, down, synchronous, or
Types
asynchronous
Wrap- After reaching 7 (binary 111), it wraps back
around to 0
Modulus Counters, or simply MOD counters, are defined based on the number of states that the counter will
sequence through before returning back to its original value. For example, a 2-bit counter that counts from
002 to 112 in binary, that is 0 to 3 in decimal, has a modulus value of 4 ( 00 → 01 → 10 → 11, and return back
to 00 ) so would therefore be called a modulo-4, or mod-4, counter. Note also that it has taken four clock pulses
to get from 00 to 11.
Therefore, a “Mod-N” counter will require “N” number of flip-flops connected together to count a single data
bit while providing 2n different output states, (n is the number of bits). Note that N is always a whole integer
value.
The we can see that MOD counters have a modulus value that is an integral power of 2, that is, 2, 4, 8, 16 and
so on to produce an n-bit counter depending on the number of flip-flops used, and how they are connected,
determining the type and modulus of the counter
We need eight different states for our counter, one for each value from 0 to 7. We can describe the operation by
drawing a state machine. The nodes represent states and the edges represent transitions and are labeled with the
input (clock in this case) that causes the transition to occur.
PROGRAM
module mod8_counter (
input wire clk, // Clock input
input wire reset, // Synchronous reset
output reg [2:0] count // 3-bit output (0 to 7)
);
endmodule
TESTBENCH:
module tb_mod8_counter;
reg clk;
reg reset;
wire [2:0] count;
mod8_counter uut (
.clk(clk),
.reset(reset),
.count(count)
);
// Clock generation
initial begin
clk = 0;
forever #5 clk = ~clk;
end
// Stimulus
initial begin
reset = 1; #10;
reset = 0; #100;
$finish;
end
initial begin
$dumpfile(“mod8_counter.vcd”);
$dumpvars(0, tb_mod8_counter);
$monitor("Time = %0t | Reset = %b | Count = %b", $time, reset, count);
end
endmodule
OUTPUT
Fig 9.3: OUTPUT WAVEFORM OF A MOD – 8 SYNCHRONOUS/ASYNCHRONOUS COUNTER
RESULT
Hence, we have designed a MOD – 8 synchronous/ asynchronous counter and verified the same using Verilog.
INTRODUCTION TO MATLAB
MATLAB is a software package for high-performance language for technical computing. It integrates
computation, visualization, and Programming in an easy-to-use environment where problems and solutions are
expressed in familiar mathematical notation. Typical uses include the following:
It also allows you to put a list of your processing requests together in a file and save that combined list with a
name so that you can run all of those commands in the same order at some later time. Furthermore, it allows
you to run such lists of commands such that you passing data and/or get data back out (i.e. the list of commands
is like a function in most programming languages). Once you save a function, it becomes part of your toolbox
(i.e. it now looks to you as if it were part of the basic toolbox that you started with). For those with computer
programming backgrounds: Note that MATLAB runs as an interpretive language (like the old BASIC). That is,
it does not need to be compiled. It simply reads through each line of the function, executes it, and then goes on
to the next line. (In practice, a form of compilation occurs when you first run a function, so that it can run faster
the next time you run it.)
The name MATLAB stands for matrix laboratory. MATLAB was originally written to provide easy access to
matrix software developed by the LINPACK and EISPACK projects. Today, MATLAB engines incorporate the
LAPACK and BLAS libraries, embedding the state of the art in software for matrix computation. MATLAB
has evolved over a period of years with input from many users. In university environments, it is the standard
instructional tool for introductory and advanced courses in mathematics, engineering, and science. In industry,
MATLAB is the tool of choice for high-productivity research, development, and analysis.
MATLAB features a family of add-on application-specific solutions called toolboxes. Very important to most
users of MATLAB, toolboxes allow learning and applying specialized technology. Toolboxes are
comprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment to solve
particular classes of problems. Areas in which toolboxes are available include Image processing, signal
processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and many others.
1. Advanced algorithms for high-performance numerical computation, especially in the field of matrix
algebra.
2. A large collection of predefined mathematical functions, with the ability to define one’s own
functions.
3. Two- and three-dimensional graphics for plotting and displaying data.
4. A complete online help system.
5. A powerful, matrix- or vector-oriented, high-level programming language for individual
applications.
6. Toolboxes available for solving advanced problems in several application areas.
1. COMMAND WINDOW : This is the main window .It is characterized by MATLAB command prompt
>>when you launch the application PROGRAM MATLAB puts you in this window all commands including
those for user-written PROGRAMs ,are typed in this window at the MATLAB prompt .
2. GRAPHICS WINDOW: the OUTPUT of all graphics commands typed in the command window are
flushed to the graphics or figure window, a separate gray window with white background color the user can
create as many windows as the system memory will allow.
3. EDIT WINDOW: This is where you write, edit, create and save your own PROGRAMs in files called
M files.
Write OUTPUT files. Input-OUTPUT: MATLAB supports interactive computation taking the input from the
screen and flushing, the OUTPUT to the screen. In addition it can read input files and
DATA TYPE: The fundamental data–type in MATLAB is the array. It encompasses several distinct data
objects- integers, real numbers, matrices, character strings, structures and cells. There is no need to declare
variables as real or complex, MATLAB automatically sets the variable to be real.
DIMENSIONING: Dimensioning is automatic in MATLAB. No dimension statements are required for vectors
or arrays .we can find the dimensions of an existing matrix or a vector with the size and length commands.
5. The MATLAB language is case-sensitive. It is customary to use lower-case letters for ordinary
variable names. The most common types of MATLAB variables are double and char.
6. MATLAB is a weakly typed language. Variables are not declared in a program before they are used.
7. MATLAB variables are created automatically when they are initialized.
8. Common ways to initialize variables in MATLAB:
i. Assign data to the variable in an assignment system.
ii. Input data into the variable from the keyboard
iii. Read data from a file
9. The semicolon at the end of an assignment statement suppresses the automatic echoing of values that
normally occurs whenever an expression is evaluated in an assignment statement.
4. If you want to delete a directory, type rmdir mydir in the command window.
5. How to open a file in MATLAB?
6. Go to File_ New_M–File and click
7. Then type the PROGRAM in the file and save the file with an extension of .m. While giving filename we
should make sure that given file name should not be a command. It is better to give the filename as my
convolution.
8. How to run a MATLAB file?
9. Go to Debug->run and click
All PROGRAMs and commands can be entered either in the a) Command window b) As an Mfile using
MATLAB editor
Note: Save all M files in the folder 'work' in the current directory. Otherwise you have to locate the file during
compiling. Typing quit in the command prompt >> quit, will close MATLAB Development Environment. For
any clarification regarding plot etc, which are built in functions type help topic
2. Subplot: This function divides the figure window into rows and columns. Subplot (221) divides the figure
window into 2 rows and 2 columns 1 represent number of the figure.
Subplot (312) divides the figure window into 3 rows and 1 column 2 represent the figure number
4. Disp Syntax: disp(X) Description: disp(X) displays an array, without printing the array name. If X contains
a text string, the string is displayed. Another way to display an array on the screen is to type its name, but
this prints a leading "X=," which is not always desirable.
Note: disp does not display empty arrays.
9. FFT Discrete Fourier Transform. FFT(X) is the discrete Fourier transform (DFT) of vector X. For
matrices, the FFT operation is applied to each column. For N-D arrays, the FFT operation operates on the
first non-singleton dimension. FFT(X,N) is the N-point FFT, padded with zeros if X has less than N points
and truncated if it has more.
10. ABS Absolute value. ABS(X) is the absolute value of the elements of X. When X is complex, ABS(X) is
the complex modulus (magnitude) of the elements of X.
11. ANGLE Phase angle. ANGLE (H) returns the phase angles, in radians, of a matrix with complex elements.
12. INTERP Resample data at a higher rate using low pass interpolation. Y = INTERP(X,L) re samples the
sequence in vector X at L times the original sample rate. The resulting re sampled vector Y is L times
longer, LENGTH(Y) = L*LENGTH(X).
13. DECIMATE Resample data at a lower rate after low pass filtering.
Y = DECIMATE(X, M) resample the sequence in vector X at 1/M times the original sample rate. The
resulting resample vector Y is M times shorter, i.e., LENGTH(Y) = CEIL (LENGTH(X)/M). By default,
DECIMATE filters the data with an 8th order Chebyshev Type I low pass filter with cutoff
frequency .8*(Fs/2)/R, before resampling.
QUITTING MATLAB:
To end your MATLAB session, type quit in the Command Window, or select File Exit MATLAB in the
desktop main menu.
OVERWRITING VARIABLE:
Once a variable has been created, it can be reassigned. In addition, if you do not wish to see the intermediate
results, you can suppress the numerical output by putting a semicolon (;) at the end of the line. Then the
sequence of commands looks like this:
>> t = 5;
>> t = t+1
t=6
Error messages: If we enter an expression incorrectly, MATLAB will return an error message. For example, in
the following, we left out the multiplication sign, *, in the following expression
>> x = 10;
MISCELLANEOUS COMMANDS:
Here are few additional useful commands:
AIM
APPARATUS REQUIRED
THEORY
There are several elementary signals which play vital role in the study of signals and systems. These elementary
signals serve as basic building blocks for the construction of more complex signals. In fact, these elementary
signals may be used to model a large number of physical signals which occur in nature. These elementary
signals are also called standard signals.
The unit sample function, often referred to as the unit impulse or delta function, is the function that defines the
idea of a unit impulse in discrete time. There are not nearly as many intricacies involved in its definition as
there are in the definition of the Dirac delta function, the continuous time impulse function. The unit sample
function simply takes a value of one at n=0 and a value of zero elsewhere. The impulse function is often written
as δ[n].
δ[n] = {01otherwise
,if n=0
{
r [ n ] = n , for n≥ 0
0 , for n< 0
The sine wave or sinusoid is a mathematical function that describes a smooth repetitive Oscillation. It occurs
often in pure mathematics, as well as physics, signal processing, electrical engineering and many other fields.
It’s most basic form as a function of time y(t) is:
Y(t) = A Sin ωt
where:
A, the amplitude, is the peak deviation of the function from its centre position.
ω, the angular frequency, specifies how many oscillations occur in a unit time interval, in radians per second
υ, the phase, specifies where in its cycle the oscillation begins at t = 0. A sampled sinusoid may be written as:
Where f is the signal frequency, fs is the sampling frequency, θ is the phase and A is the amplitude of the signal.
The PROGRAM and its OUTPUT is shown below: Note that there are 64 samples with sampling frequency of
8000Hz or sampling time of 0.125 ms (i.e. 1/8000). Hence the record length of the signal is 64x0.125=8mS.
There are exactly 8 cycles of sine wave, indicating that the period of one cycle is 1mS which means that the
signal frequency is 1 KHz.
PROCEDURE
1. Open MATLAB
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. For the output see command window\ Figure window.
PROGRAM
% Time vector
t = -2:0.01:2; % Time range from -2 to 2 with step size 0.01
subplot(3,3,5);
plot(t, x_triangular, 'LineWidth', 2);
title('Triangular Wave');
xlabel('Time');
ylabel('Amplitude');
axis([-2 2 -1.5 1.5]);
subplot(3,3,7);
plot(t, x_ramp, 'LineWidth', 2);
title('Ramp Function');
xlabel('Time');
ylabel('Amplitude');
axis([-2 2 -0.1 2]);
subplot(3,3,8);
plot(t, x_sinc, 'LineWidth', 2);
title('Sinc Function');
xlabel('Time');
ylabel('Amplitude');
axis([-2 2 -0.5 1]);
OUTPUT
Fig 1.5: OUTPUTS OF RESPECTIVE WAVEFORMS
RESULT
Hence, we have generated different types of standard signals such as Unit Impulse function, Unit Step function,
Sinusoidal functions, etc. using MATLAB Software.
EXPERIMENT – 2
OPERATIONS ON SIGNALS AND SEQUENCES: ADDITION,
MULTIPLICATION, SCALING, SHIFTING, FOLDING, COMPUTATION
OF ENERGY AND AVERAGE POWER
AIM
Write a MATLAB program to perform Operations on Signals and Sequences: Addition, Multiplication, Scaling,
Shifting, Folding, Computation of Energy and Average Power.
APPARATUS REQUIRED
THEORY
1. ADDITION:
Any two signals can be added to form a third signal, z (t) = x (t) + y (t)
2. MULTIPLICATION:
Multiplication of two signals can be obtained by multiplying their values at every instant. z(t) = x (t) * y (t)
3. TIME REVERSAL/FOLDING:
Time reversal of a signal x(t) can be obtained by folding the signal about t=0. Y(t) = y(-t)
Signal amplification/scaling:
y(n) = ax(n), if a < 1 attenuation
a >1 amplification
4. TIME SHIFTING:
The time shifting of x(n) obtained by delay or advance the signal in time by using y(n) = x(n+k)
If k is a positive number, y(n) shifted to the right i.e., the shifting delays the signal
If k is a negative number, y(n) it gets shifted left. Signal Shifting advances the signal
5. ENERGY
N ∞
∑ |x [ n ]| = ∑ |x [ n ]|
2 2
E [ n ] = lim
N → ∞ n=− N n=−∞
6. AVERAGE POWER
N
1
∑
2
P [ n ] = lim |x [ n ]|
N →∞ 2 N +1 n=−N
PROGRAM
% Time vector
t = -10:0.01:10; % Time range from -10 to 10 with step size 0.01
% Plot Operations
% Addition
x_add = x1 + x2;
subplot(3,3,3);
plot(t, x_add, 'k', 'LineWidth', 1.5);
title('Addition: x1 + x2');
xlabel('Time');
ylabel('Amplitude');
% Multiplication
x_mul = x1 .* x2;
subplot(3,3,4);
plot(t, x_mul, 'm', 'LineWidth', 1.5);
title('Multiplication: x1 .* x2');
xlabel('Time');
ylabel('Amplitude');
% Scaling
scaling_factor = 2;
x_scaled = scaling_factor * x1;
subplot(3,3,5);
plot(t, x_scaled, 'g', 'LineWidth', 1.5);
title('Scaling: 2 * x1');
xlabel('Time');
ylabel('Amplitude');
% Shifting
% Folding
x_folded = fliplr(x1); % Flipped (or folded) signal
subplot(3,3,7);
plot(t, x_folded, 'k', 'LineWidth', 1.5);
title('Folding: flipped x1');
xlabel('Time');
ylabel('Amplitude');
% Energy Computation
OUTPUT
Fig 2.1: OPERATIONS AND SEQUENCES ON A GIVEN SIGNAL
RESULT
Hence, we have done various operations on signals such as addition and multiplication of signals, time shifting,
time scaling and sequences are performed.
EXPERIMENT – 3
WRITE A PROGRAM TO FIND THE TRIGONOMETRIC FOURIER
SERIES COEFFICIENTS OF A RECTANGULAR PERIODIC SIGNAL.
RECONSTRUCT THE SIGNAL BY COMBINING THE FOURIER SERIES
COEFFICIENTS WITH APPROPRIATE WEIGHTINGS
AIM
To write a program to find the trigonometric Fourier series coefficients of a rectangular periodic signal.
Reconstruct the signal by combining the Fourier series coefficients with appropriate weightings
APPARATUS REQUIRED
THEORY
FOURIER SERIES
The Fourier series represents periodic, continuous-time signals as a weighted sum of continuous-time sinusoids.
It is widely used to analyze and synthesize periodic signals. It also introduces you to the conditions that must be
met for a signal to have a convergent representation. You will learn both the general and trigonometric forms.
The general form expresses the signal as a weighted sum of harmonically related complex sinusoids. The
trigonometric form expresses real -valued signals as weighted sums of harmonically related sines and cosines.
The Fourier series is an essential tool and will enable you to work effectively with periodic signals in the
frequency domain.
The trigonometric Fourier series representation of a periodic signal x (t) with fundamental period T, is given by
∞
2π
x (t )=a0 + ∑ ( ak cos kω 0 t +b k sink ω 0 t ) , ω 0=
k=1 T0
2 2
a k= ∫
T0 T
x ( t ) cosk ω0 tdt ,b k = ∫ x ( t ) sink ω0 tdt
T0 T
0 0
PROCEDURE
1. Open MATLAB
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. For the output see command window\ Figure window
PROGRAM:
% MATLAB Program to Compute and Plot Fourier Series Coefficients and Reconstruct a Rectangular Signal
for n = 1:n_terms
a_n(n) = 2/T * integral(@(t) rectangular_signal(t) .* cos(2 * pi * n * t / T), -T/2, T/2);
b_n(n) = 2/T * integral(@(t) rectangular_signal(t) .* sin(2 * pi * n * t / T), -T/2, T/2);
end
for n = 1:n_terms
reconstructed_signal = reconstructed_signal + a_n(n) * cos(2 * pi * n * t_rec / T) + b_n(n) * sin(2 * pi * n * t_rec / T);
end
subplot(3, 2, 4);
stem(1:n_terms, b_n, 'filled');
title('Sine Coefficients (b_n)');
xlabel('n');
ylabel('Magnitude');
axis([0 n_terms 0 max(b_n) + 1]);
% Adjust layout
sgtitle('Fourier Series Analysis of a Rectangular Signal');
OUTPUT
RESULT
Hence, we have obtained the trigonometric Fourier series coefficients of a rectangular periodic signal, and
reconstructed the signal by combining the Fourier series coefficients with appropriate weightings
EXPERIMENT – 4
WRITE A PROGRAM TO FIND FOURIER TRANSFORM OF A GIVEN
SIGNAL. PLOT ITS AMPLITUDE AND PHASE SPECTRUM
AIM
Write a program to find Fourier transform of a given signal. Plot its amplitude and phase spectrum.
APPARATUS REQUIRED
THEORY
FOURIER TRANSFORM:
The Fourier Transform is a mathematical technique that transforms a function of time, x (t), to a function of frequency, X
(ω). It is closely related to the Fourier series.
The Fourier series is used to represent a periodic function by a discrete sum of complex exponentials, while the Fourier
transform is then used to represent a general, non periodic function by a continuous superposition or integral of complex
exponentials.
The Fourier transform can be viewed as the limit of the Fourier series of a function with the period approaches to infinity,
so the limits of integration change from one period to (−∞, ∞). Fourier transform of ƒ is given by definition:
∞
F ( ω )= ∫ f ( x ) e
−iωx
dx
−∞
X [k ]= ∑ x [ n ] e N
k=0
PROCEDURE
1. Open MATLAB
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. For the output see command window\ Figure window
PROGRAM
% Define the signal (example: a composite signal with sine and cosine components)
f1 = 50; % Frequency of the first component (Hz)
f2 = 120; % Frequency of the second component (Hz)
signal = 0.7 * sin(2 * pi * f1 * t) + 1.0 * cos(2 * pi * f2 * t);
OUTPUT
Fig 4.1: FOURIER TRANSFORM OF A GIVEN RECTANGULAR PULSE SIGNAL IN TIME DOMAIN TO FRQUENCY
DOMAIN
RESULT
Hence, we can generate a given time signal to frequency domain while we plot the frequency spectrum and
amplitude spectrum.
EXPERIMENT – 5
WRITE A PROGRAM TO CONVOLVE TWO DISCRETE TIME
SEQUENCES. PLOT ALL THE SEQUENCES. VERIFY THE RESULT BY
ANALYTICAL CALCULATION
AIM
To find the output with linear convolution operation Using MATLAB Software.
APPARATUS REQUIRED
THEORY
y [ n]= ∑ x [ k ] h[n−k ]
k=−∞
The process of computing the convolution between x (k) and h (k) involves the following four steps
1. Folding - fold h (k) about k=0 to obtain (-k)
2. Shifting. Shift h (k) by n0 to the right (left) if n0 is positive (negative), to obtain h (n0-k)
3. Multiplication. Multiply x (k) by h(n0-k) to obtain the product sequence
v (k) = x (k) h(n0-k)
4. Summation. Sum all the values of the product sequence v (k) to obtain the value of the output at time n=n 0.
PROCEDURE
1. Open MATLAB
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. For the output see command window\ Figure window
PROGRAM
OUTPUT
RESULT
Hence, we can find the convolution between two given signals and we have obtained the appropriate response.
EXPERIMENT – 6
WRITE A PROGRAM TO FIND THE AUTOCORRELATION AND CROSS
CORRELATION OF SEQUENCES.
AIM
APPARATUS REQUIRED
THEORY
CORRELATION:
In general, correlation describes the mutual relationship which exists between two or more things. The same
definition holds good even in the case of signals. That is, correlation between signals indicates the measure up
to which the given signal resembles another signal. In other words, if we want to know how much similarity
exists between the signals 1 and 2, then we need to find out the correlation of Signal 1 with respect to Signal 2
or vice versa.
TYPES OF CORRELATION:
Depending on whether the signals considered for correlation are same or different, we have two kinds of
correlation: autocorrelation and cross-correlation.
a. AUTOCORRELATION:
This is a type of correlation in which the given signal is correlated with itself, usually the time-shifted version
of itself. Mathematical expression for the autocorrelation of continuous time signal x (t) is given by
∞
R xx = ∫ x (t)x ( t−τ ) dt
¿
−∞
∞
R xx [m]= ∑ x [ n ] x¿ [n−m]
n=−∞
Next, the autocorrelation of any given signal can also be computed by resorting to graphical technique. The
procedure involves sliding the time-shifted version of the given signal upon itself while computing the samples
at every interval. That is, if the given signal is digital, then we shift the given signal by one sample every time
and overlap it with the original signal. While doing so, for every shift and overlap, we perform multiply and
add.
b. CROSS – CORRELATION:
This is a kind of correlation, in which the signal in-hand is correlated with another signal so as to know how
much resemblance exists between them. Mathematical expression for the cross-correlation of continuous time
signals x (t) and y (t) is given by
∞
R xy ( τ )= ∫ x ( t ) y ( t−τ ) dt
¿
−∞
Similarly, the cross-correlation of the discrete time signals x [n] and y [n] is expressed as
∞
R xy [ m ] = ∑ x [ n ] y ¿ [n−m]
n=−∞
PROCEDURE
1. Open MATLAB
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. For the output see command window\ Figure window
PROGRAM
clc;
close all;
OUTPUT
Fig 6.1: AUTO CORRELATION AND CROSS CORRELATION OF GIVEN INPUT SEQUENCE
RESULT
Hence, we have obtained the autocorrelation and cross correlation sequences for a given input.
EXPERIMENT – 7
WRITE A PROGRAM TO VERIFY LINEARITY AND TIME
INVARIANCE PROPERTIES OF A GIVEN CONTINUOUS SYSTEM.
AIM
Write a program to verify Linearity and Time Invariance properties of a given Continuous System.
APPARATUS REQUIRED
THEORY
LINEARITY PROPERTY:
Any system is said to be linear if it satisfies the superposition principal. Superposition principal states that
response to a weighted sum of input signal equal to the corresponding weighted sum of the outputs of the
system to each of the individual input signals.
PROCEDURE
1. Open MATLAB
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. For the output see command window\ Figure window
PROGRAM
% Linearity Verification
% Superposition principle: T{a*x1 + b*x2} = a*T{x1} + b*T{x2}
superposition_input = a * x1 + b * x2; % Combined input
superposition_response = system_response(superposition_input); % System response to combined input
linear_combination_response = a * y1 + b * y2; % Linear combination of individual responses
% Plotting
figure;
% Adjust layout
sgtitle('Verification of Linearity and Time Invariance')
OUTPUT
RESULT
Hence, The Linearity and the time invariance of a given system are verified.
EXPERIMENT – 8
GENERATE A DISCRETE TIME SEQUENCE BY SAMPLING A
CONTINUOUS TIME SIGNAL. SHOW THAT WITH SAMPLING RATES
LESS THAN NYQUIST RATE, ALIASING OCCURS WHILE
RECONSTRUCTING THE SIGNAL.
AIM
To generate a discrete time sequence by sampling a continuous time signal. Show that with sampling rates less
than Nyquist rate, aliasing occurs while reconstructing the signal.
APPARATUS REQUIRED
THEORY
A continuous time signal can be represented in its samples and can be recovered back when sampling frequency
fs is greater than or equal to the twice the highest frequency component of message signal i.e.,
fs ≥ 2fm
Proof: Consider a continuous time signal x(t). The spectrum of x(t) is a band limited to f m Hz i.e. the spectrum
of x(t) is zero for |ω| > ωm. Sampling of input signal x(t) can be obtained by multiplying x(t) with an impulse
train δ(t) of period Ts. The output of multiplier is a discrete signal called sampled signal which is represented
with y(t) in the following diagrams:
Aliasing fs < 2fm
PROCEDURE
1. Open MATLAB
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. For the output see command window\ Figure window
PROGRAM
clc;
clear;
tmin=-1;
tmax=1;
t=tmin:0.001:tmax;
xa=sin(2*pi*10*t);
%//xa=exp(-10*abs(t));
Fs=30;
Ts=1/Fs;
n=tmin/Ts:tmax/Ts;
%//x=exp(-10*abs(n*Ts));
x=sin(2*pi*10*n*Ts);
figure(1);
subplot(211);
plot(t,xa);
title('analogsignal');
subplot(212);
stem(n,x);
title('discretetimesignalforFS=30Hz');
figure(2);
subplot(211);
%//holdon;
plot(n*Ts,x);
for i=1:size(x,2)
xsinc(i,:)=x(i)*sinc(Fs*(t-(i+min(n)-1)*Ts));
plot(t,xsinc(i,:));
end
title('signalreconstruction');
sum1=zeros(1,size(xsinc,1));
for i=1:size(xsinc,1)
for j=1:size(xsinc,2)
sum1(i)=sum1(i)+xsinc(i,j);
end
end
%//holdoff;
%//xar=sum(xsinc);
subplot(212);
stem(n*Ts,sum1);
title('ReconstructedsignalwhenFs<2fmi.eFs=30');
legend('reconstructedsignalxa(t)');
OUTPUT
Fig 8.2: SAMPLED SIGNAL WHEN FS > 2FM AND FS < 2FM.
RESULT
The discrete time sequence by sampling a continuous time signal Generated sampling rates less than Nyquist
rate, aliasing occurs while reconstructing the signal was verified.
EXPERIMENT – 9
WRITE A PROGRAM TO GENERATE COMPLEX GAUSSIAN NOISE
AND FIND ITS MEAN, VARIANCE, PROBABILITY DENSITY
FUNCTION (PDF) AND POWER SPECTRAL DENSITY (PSD).
AIM
Write a program to generate Complex Gaussian noise and find its mean, variance, Probability Density
Function (PDF) and Power Spectral Density (PSD).
APPARATUS REQUIRED
THEORY
Random signals are those which are not precisely predictable; that is, given the past history of a signal and the
amplitude values it has taken on, it is not possible to precisely predict what particular value itwill take on at
certain instants in the future. Random noise signals may be represented mathematically using statistical
methods. It is important to understand the nature of “random” systems, and that “random” does not necessarily
mean “totally unpredictable.” From a signal processing perspective, if we understand the nature of random
fluctuations in a signal, we are in a better position to remove, or at least to minimize, their negative effects.
The term random signal is used primarily to denote signals, which have a random in its nature source. ... An
example is a periodic sinusoidal signal with a random phase or amplitude. Random variables: In the study of
probability, any process of observation is referred to as an experiment. The results of an observation are called
outcomes of the experiment. If the outcomes of an experiment cannot be predicted, then it is called random
experiment.
PROCEDURE
1. Open MATLAB
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. For the output see command window\ Figure window
PROGRAM
% Parameters
N = 10000; % Number of samples
mean_value = 0; % Mean of the complex Gaussian noise
variance_value = 1; % Variance of the complex Gaussian noise
% Plot PSD
figure;
freq = linspace(0, 1, L/2+1)*2*pi; % Frequency axis
plot(freq,10*log10(psd_complex));
title('Power Spectral Density (PSD) of Complex Gaussian Noise');
xlabel('Frequency (rad/sample)');
ylabel('Power/Frequency (dB/rad/sample)');
OUTPUT
RESULT
Hence, we can generate complex Gaussian noise and find its mean, variance, Probability Density Function
(PDF) and Power Spectral Density (PSD).