0% found this document useful (0 votes)
29 views95 pages

DC & SS LAB AR23 Student Manual

The document is a laboratory manual for the Digital Circuits and Signal Simulation Lab for III Semester students in Electronics and Communication Engineering, prepared by Mr. S. Balarama Murthy. It outlines the vision and mission of the department, code of conduct for laboratory sessions, course outcomes, program educational objectives, and specific outcomes related to the course. Additionally, it includes a detailed list of experiments and guidelines for using Xilinx tools for digital circuit design.

Uploaded by

akhil.ece
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views95 pages

DC & SS LAB AR23 Student Manual

The document is a laboratory manual for the Digital Circuits and Signal Simulation Lab for III Semester students in Electronics and Communication Engineering, prepared by Mr. S. Balarama Murthy. It outlines the vision and mission of the department, code of conduct for laboratory sessions, course outcomes, program educational objectives, and specific outcomes related to the course. Additionally, it includes a detailed list of experiments and guidelines for using Xilinx tools for digital circuit design.

Uploaded by

akhil.ece
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 95

SONTYAM, ANANDAPURAM, VISAKHAPATNAM, AP.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING

DIGITAL CIRCUITS AND SIGNAL SIMULATION


LABORATORY MANUAL
For
III SEMESTER (II B.TECH, I SEMESTER)
(Regulations: AR23)

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

Mr. S. Balarama Murty, Dr. B. Siva Prasad


Associate Professor Head of Department
VISION

 To promote societal empowerment and become an Institute of Excellence in the field of


engineering education, research

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

 To become recognized forerunner in Electronics and Communication Engineering by producing competent


and responsible graduates.

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.

B. Sandals or open-toed shoes are NOT allowed.

C. Foods, drinks and smoking are NOT allowed.

D. All bags must be left at the indicated place.

E. The lab timetable must be strictly followed.

F. Be PUNCTUAL for your laboratory session.

G. Program must be executed within the given time.

H. Noise must be kept to a minimum.

I. Workspace must be kept clean and tidy at all times.

J. Handle the systems and interfacing kits with care.

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

before leaving the lab

Place the chairs properly.

Turn off the kits properly.

Please check the laboratory notice board regularly for updates.


NSRIT | Academic Regulation 2023 | ECE | 23EC307 Digital Circuits and Signal Simulation Lab, Approved
in 2nd ACM

PC 23EC307 Digital Circuits and Signal Simulation Lab 0 0 3 1.5

COURSE OUTCOMES (CO’s):

After successful completion of this course, the students should be able to


CO1: Apply the principles of combinational and sequential circuit design to implement and verify
simple digital circuits using hardware description languages (HDL) like Verilog or VHDL.
CO2: Implement basic signal processing operations on discrete-time signals and analyze energy and average
power computation using signal processing software.
CO3: Examine and verify the properties of linearity and time invariance in continuous – time
systems through simulation and coding.
CO4: Analyze the effects of aliasing in signal reconstruction by performing sampling at various
rates and comparing the outcomes with the Nyquist criterion.
CO5: Evaluate the performance of digital circuits such as counters and registers in different modes
of operation, including synchronous and asynchronous modes.

PROGRAMME EDUCATIONAL OBJECTIVES (PEO’s):

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.

PROGRAMME OUTCOMES (PO’s):

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.

PROGRAMME SPECIFIC OUTCOMES (PSO’s):

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.

CO’S – PO’S MAPPING


COURSE PROGRAM OUTCOMES (PO’S)
OUTCOMES PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO
(CO’S) 1 2 3 4 5 6 7 8 9 10 11 12 1 2
CO1 3 3 - - - - - - 1 - 1 - 2 2
CO2 3 2 1 1 1 - - - 1 - 1 - 2 2
CO3 3 2 1 1 1 - - - 1 - 1 - 2 2
CO4 3 2 1 1 1 - - - 1 - 1 - 2 2
CO5 1 2 - - 3 - - - 1 - 1 2 2 2
AVERAGE 2.6 2.2 1 1 1.5 - - - 1 - 1 2 2 2

Strength of Correlation: 1 – Weak, Medium – 2 & Strong – 3

S. No. NAME OF THE EXPERIMENT


1 INTRODUCTION TO VERILOG
DESIGN A SIMPLE COMBINATIONAL CIRCUIT WITH FOUR VARIABLES AND OBTAIN
2
MINIMAL SOP EXPRESSION AND VERIFY THE TRUTH TABLE

3 VERIFY THE OF FUNCTIONALITY OF 3 TO 8 – LINE DECODER.

4 4 VARIABLE LOGIC FUNCTION VERIFICATION USING 8 TO1 MULTIPLEXER.


DESIGN AND VERIFY THE FUNCTIONALITY OF FULL ADDER CIRCUIT, FULL
5
SUBTRACTOR.
DRAW THE CIRCUIT DIAGRAM OF A SINGLE BIT COMPARATOR AND VERIFY THE
6
OUTPUT.
7 DESIGN AND VERIFY THE FUNCTIONALITY OF DIFFERENT FLIPFLOPS.
DESIGN AND VERIFY THE OPERATION OF 4-BIT UNIVERSAL SHIFT REGISTER FOR
8
DIFFERENT MODES OF OPERATION.
9 DESIGN UP COUNTER AND DOWN COUNTERS
10 DESIGN MOD – 8 SYNCHRONOUS COUNTER /ASYNCHRONOUS COUNTERS.

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:

1. Create Verilog design in put file(s) using template driven editor.


2. Compile and implement the Verilog design file(s).
3. Create the test-vectors and simulate the design (functional simulation) without using a PLD (FPGA or
CPLD).
4. Assign input/output pins to implement the design on a target device.

A Verilog input file in the Xilinx software environment consists of the following segments:

1. Header: module name, list of input and output ports.


2. Declarations : input and output ports, registers and wires.
3. LogicDescriptions: equations, state machines and logic functions.
4. End: end module

CREATING A NEW PROJECT

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:

Project Name: Write the name of your new project


Project Location: The directory where you want to store the new project (Note: DONOT specify the project
location as a folder on Desktop or a folder in the Xilinx\bin directory. Your H: drive is the best place to put it.
The project location path is NOT to have any spaces in it eg: C:\Nivash\TA\new lab\sample exercises\o_gate is
NOT to be used) Leave the top level module type as HDL.

Example: If the project name were “o_gate”, enter “o_gate” as the project name and then click “Next”.

Fig 2: NEW PROJECT INITIATION WINDOW

Clicking on NEXT should bring up the following window:


Fig 3: DEVICE AND DESIGN FLOW OF PROJECT (SNAPSHOT FROM XILINX ISE SOFTWARE)
For each of the properties given below, click on the ‘value’ area and select from the list of values that appear.

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.

Then click on NEXT to save the entries.

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:

Fig 4: CREATE NEW SOURCE WINDOW

If creating a new source file, Click on the NEW SOURCE.


Creating a Verilog HDL input file for a combinational logic design
In this lab we will enter a design using a structural or RTL description using the Verilog HDL. You can create a
Verilog HDL input file (.v file) using the HDL Editor available in the Xilinx ISE Tools (or any text editor).
In the previous window, click on the NEW SOURCE
A window pops up as shown in Figure 4. (Note:“Add to project” option is selected by default. If you do not
select it then you will have to add the new source file to the project manually.)

Fig 5: CREATING VERILOG-HDL SOURCE FILE(SNAPSHOT FROM XILINX ISE SOFTWARE)

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.

Fig 6: DEFINE VERILOG SOURCE WINDOW


Fig 7: NEW PROJECT INFORMATION WINDOW

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”.

Fig 8: VERILOG SOURCE CODE EDITOR WINDOW IN THE PROJECT NAVIGATOR

Functional Simulation of Combinational Designs

Adding the test vectors


To check the functionality of a design, we have to apply test vectors and simulate the circuit. In order to apply
test vectors, a test bench file is written. Essentially it will supply all the inputs to the module designed and will
check the outputs of the module. Example: For the 2 input OR Gate, the steps to generate the test bench are as
follows:
In the Sources window (top left corner) right click on the file that you want to generate the test bench for and
select ‘New 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.

Fig 9: ADDING TEST VECTORS TO THE DESIGN

Click on ‘Next’ to proceed. In the next windows elect the source file with which you want to associate the test

Fig 10: ASSOCIATING A MODULE TO A TESTBENCH

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.

Simulating and Viewing the Output Waveforms


Now under the Processes window (making sure that the test bench file in the Sources window is selected)
expand the ModelSim simulator Tab by clicking on the add sign next to it. Double Click on Simulate
Behavioral Model. You will probably receive a complier error. This is nothing to worry about –answer “No”
when asked if you wish to abort simulation. This should cause ModelSim to open. Wait for it to complete
execution. If you wish to not receive the compiler error, right click on Simulate Behavioral Model
And select process properties. Mark the check box next to“ Ignore Pre-Complied Library Warning Check”.

Fig 11: SIMULATING THE DESIGN

Saving the simulation results

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

Fig 12: BEHAVIORAL SIMULATION OUTPUT WAVEFORM

For taking printouts for the lab reports, convert the black background to white in Tools ->Edit Preferences.
Then click Wave Windows -> Wave Background attribute.

Fig 13: CHANGING WAVEFORM BACKGROUND


Synthesis and Implementation of the Design

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.

Fig 14: IMPLEMENTING THE DESIGN

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

From the table, F = 1 for the minterms: 1, 2, 4, 7, 8, 11, 13, 14


MINTERMS:

F(A,B,C,D) = Σ m (1,2,4,7,8,11,13,14)

Use Karnaugh map (K-map) minimization

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

assign 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);

endmodule

TEST BENCH

module combinational_circuit_tb;

reg A, B, C , D;

wire F;

combinational_circuit uut (.A(A), .B(B), .C(C), .D(D), .F(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;

#1; // small delay to simulate propagation

$display("%b %b %b %b | %b", A, B, C, D, F);

end

$finish;

end

endmodule

OUTPUT

Fig 1.1: OUTPUT FOR COMBINATIONAL CIRCUIT OF A GIVEN BOOLEAN EXPRESSION

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

To design a 3 to 8 – line Decoder and verify the truth table

APPARATUS REQUIRED

1. PC with windows (95/98/XP/NT/2000).


2. Xilinx Software

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:

Enable (EN) Input Output


A B C Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7
0 X X X X X X X X X X X
1 0 0 0 1 0 0 0 0 0 0 0
1 0 0 1 0 1 0 0 0 0 0 0
1 0 1 0 0 0 1 0 0 0 0 0
1 0 1 1 0 0 0 1 0 0 0 0
1 1 0 0 0 0 0 0 1 0 0 0
1 1 0 1 0 0 0 0 0 1 0 0
1 1 1 0 0 0 0 0 0 0 1 0
1 1 1 1 0 0 0 0 0 0 0 1
Fig 2.1: A 3 X 8 DECODER

PROGRAM

VERILOG DESIGN CODE:

module decoder3to8 (
input wire [2:0] in, // 3-bit input
input wire en, // enable signal
output reg [7:0] out // 8-bit output);

always @(*) begin


if (en) begin
out = 8'b00000000; // Clear all outputs
out[in] = 1'b1; // Set only the selected output
end else begin
out = 8'b00000000; // All outputs off if not enabled
end
end

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

Fig 2.2: OUTPUT WAVEFORM OF A 3X8 DECODERWITH ENABLE HIGH SIGNAL

RESULT

Hence we have verified the functionality of a 3 to 8 – line Decoder.


EXPERIMENT – 3
4 VARIABLE LOGIC FUNCTION VERIFICATION USING 8 TO 1
MULTIPLEXER IN VERILOG

AIM

To design 4 variable logic function verification using 8 to1 multiplexer and verify the truth table

APPARATUS REQUIRED

1. PC with windows (95/98/XP/NT/2000).


2. Xilinx Software

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.

An 8-to-1 multiplexer has:


3 select lines → we'll use A, B, and C
8 data inputs (D0 to D7) → values will depend on the function
The fourth variable D is used within the data inputs (either as D, ~D, or constants 1, 0), depending on the logic
function.
So, for a function F (A, B, C, D), we write it as a MUX with:
A, B, C as select lines (to select which input is routed to output)
MUX data inputs (I0 to I7) implemented using expressions in terms of D

Implement and Verify F = Σ m (1, 3, 4, 6, 7, 8, 9, 15)


But this function has minterms from 0 to 15 (4-variable function), while 8-to-1 MUX can only directly select
from 8 inputs. So we map 4-variable function into 3-variable select lines.
Let’s assign:
A, B, C as select inputs to MUX (3 bits)
Use D as data bit
We'll break the function into terms of the 3 select bits and decide what value (0, 1, D, or ~D) each MUX input
should be.
Step-by-step:
Let’s say F (A,B,C
Decimal Minterms: 1, 3, 4, 6, 7, 8, 9, 15
Binary:
0001 → A=0 B=0 C=0 D=1
0011 → A=0 B=0 C=1 D=1
0100 → A=0 B=1 C=0 D=0
0110 → A=0 B=1 C=1 D=0
0111 → A=0 B=1 C=1 D=1
1000 → A=1 B=0 C=0 D=0
1001 → A=1 B=0 C=0 D=1
1111 → A=1 B=1 C=1 D=1
We now group these by A, B, C (3-bit select) and decide values of D_i (data inputs):

SELECT LINES (INPUT) D Values Needed MUX Input

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

Fig 3.1: AN 8 X 1 MULTIPLEXER

PROGRAM

VERILOG DESIGN CODE:

module mux8to1 (
input wire [2:0] sel,
input wire D,
output wire F
);

wire [7:0] mux_in;


assign mux_in[0] = D; // I0
assign mux_in[1] = 1'b0; // I1
assign mux_in[2] = ~D; // I2
assign mux_in[3] = 1'b1; // I3
assign mux_in[4] = 1'b1; // I4
assign mux_in[5] = 1'b0; // I5
assign mux_in[6] = 1'b0; // I6
assign mux_in[7] = D; // I7

assign F = mux_in[sel]; // MUX operation

endmodule

TESTBENCH:

module tb_mux_function;
reg A, B, C, D;
wire F;
wire [3:0] inputs;
wire expected;

// Instantiate the mux module


mux8to1 uut (
.sel({A, B, C}),
.D(D),
.F(F)
);

assign inputs = {A,B,C,D};

// Expected output using 4-variable logic function: F = Σm(1,3,4,6,7,8,9,15)


assign expected =
(inputs == 4'b0001) || (inputs == 4'b0011) ||
(inputs == 4'b0100) || (inputs == 4'b0110) ||
(inputs == 4'b0111) || (inputs == 4'b1000) ||
(inputs == 4'b1001) || (inputs == 4'b1111);

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

1. PC with windows (95/98/XP/NT/2000).


2. Xilinx Software

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

Fig 5.1: LOGIC DIAGRAM OF A SINGLE BIT COMAPRATOR

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

// Implement the logic


assign A_eq_B = ~(A ^ B); // A equals B
assign A_gt_B = A & ~B; // A greater than B
assign A_lt_B = ~A & B; // A less than 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("--------------------------");

// Test all combinations


for (int i = 0; i < 4; i = i + 1) begin
{A, B} = i;
#5;
$display("%b %b | %b %b %b", A, B, A_eq_B, A_gt_B, A_lt_B);
end
$finish;
end

endmodule

OUTPUT

Fig 5.2: OUTPUT WAVEFORM OF 1 – BIT COMPARATOR

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

To Design and verify the functionality of different flip-flops in Verilog.

APPARATUS REQUIRED

1. PC with windows (95/98/XP/NT/2000).


2. Xilinx Software

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

VERILOG DESIGN CODE:

// 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
);

assign Q_bar = ~Q;

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

$monitor("S=%b R=%b -> Q=%b Q_bar=%b", S, R, Q, Q_bar);

// 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
);

always @(posedge clk or posedge rst) begin


if (rst)
Q <= 0; // Reset output
else if (T)
Q <= ~Q; // Toggle
// else Q stays the same
end

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

always @(posedge clk or posedge reset) begin


if (reset)
q <= 1'b0; // Reset output to 0
else
q <= d; // On rising edge, store D input
end

endmodule

TESTBENCH:

`timescale 1ns / 1ps

module tb_d_flip_flop;

// Testbench signals
reg clk;
reg d;
wire q;

// Instantiate the D flip-flop


d_flip_flop uut (
.clk(clk),
.d(d),
.q(q)
);

// Clock generation: 10 ns period


always #5 clk = ~clk;

// 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);

// Apply test values


#7 d = 1;
#10 d = 0;
#10 d = 1;
#10 d = 1;
#10 d = 0;
#10 $finish;
end

endmodule

// J – K Flip Flop

VERILOG DESIGN CODE:

module jk_flip_flop (
input wire clk, // Clock input
input wire j, // J input
input wire k, // K input
output reg q // Output
);

always @(posedge clk) begin


case ({j, k})
2'b00: q <= q; // No change
2'b01: q <= 0; // Reset
2'b10: q <= 1; // Set
2'b11: q <= ~q; // Toggle
endcase
end

endmodule

TEST BENCH:

`timescale 1ns / 1ps


module jk_flip_flop_tb;

// Testbench signals
reg clk;
reg j, k;
wire q;

// Instantiate the JK flip-flop


jk_flip_flop uut (
.clk(clk),
.j(j),
.k(k),
.q(q)
);

// Clock generation: 10 ns period


always #5 clk = ~clk;

// 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.5: OUTPUT WAVEFORM OF SR – FLIP FLOP

\
Fig 6.6: OUTPUT WAVEFORM OF T – FLIP FLOP

Fig 6.7: OUTPUT WAVEFORM OF D – FLIP FLOP


Fig 6.8: OUTPUT WAVEFORM OF JK – 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

1. PC with windows (95/98/XP/NT/2000).


2. Xilinx Software

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

Fig 7.2: TRUTH TABLE OF THE 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
);

always @(posedge clk or posedge reset) begin


if (reset)
q <= 4'b0000;
else begin
case (sel)
2'b00: q <= q; // Hold
2'b01: q <= {sin_right, q[3:1]}; // Shift Right
2'b10: q <= {q[2:0], sin_left}; // Shift Left
2'b11: q <= d; // Parallel Load
endcase
end
end

endmodule

TESTBENCH:

`timescale 1ns / 1ps

module universal_shift_register_tb;

reg clk, reset;


reg [1:0] sel;
reg [3:0] d;
reg sin_left, sin_right;
wire [3:0] q;

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;

// Load parallel data


#10 sel = 2'b11; d = 4'b1010;

// Hold
#10 sel = 2'b00;

// Shift Right
#10 sel = 2'b01; sin_right = 1;

// Shift Left
#10 sel = 2'b10; sin_left = 0;

// Another parallel load


#10 sel = 2'b11; d = 4'b1100;

// Shift Left with sin_left = 1


#10 sel = 2'b10; sin_left = 1;

// 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

To Design up counter and down counters in Verilog.

APPARATUS REQUIRED

1. PC with windows (95/98/XP/NT/2000).


2. Xilinx Software

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.

4 – BIT DOWN COUNTER:

Clock-driven: The counter updates on the rising edge of the clock.


Synchronous Reset: When reset is 1, the counter is set to 4'b1111 (decimal 15).
Counting Down: Each clock tick decrements the counter value by 1.

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.

The J and K inputs of first flip-flops are set to HIGH.


FF0 toggles at every clock pulse.
FF1 toggles when FF0 is LOW, and so on.
As synchronous counters are formed by connecting flip-flops together and any number of flip-flops can be
connected or “cascaded” together to form a “divide-by-n” binary counter, the module’s or “MOD” number still
applies as it does for asynchronous counters so a Decade counter or BCD counter with counts from 0 to 2n-
1 can be built along with truncated sequences. All we need to increase the MOD count of an up or down
synchronous counter is an additional flip-flop and AND gate across it.

Fig 8.2: LOGIC DIAGRAM OF A 4 – BIT SYNCHRONOUS DOWN COUNTER

PROGRAM

VERILOG DESIGN CODE:

//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
);

always @(posedge clk) begin


if (reset)
count <= 4'b0000; // Reset counter to 0
else
count <= count + 1; // Increment counter
end

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

VERILOG DESIGN CODE:

// 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
);

always @(posedge clk) begin


if (reset)
count <= 4'b1111; // Reset to maximum value (15)
else
count <= count - 1; // Decrement counter
end

endmodule

TESTBENCH:

module tb_down_counter_4bit;

reg clk;
reg reset;
wire [3:0] count;

// Instantiate the counter


down_counter_4bit uut (
.clk(clk),
.reset(reset),
.count(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

Fig 8.4: OUTPUT WAVEFORM OF A 4 – BIT SYNCHRONOUS DOWN 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

To Design MOD – 8 synchronous counter /asynchronous counters in Verilog.

APPARATUS REQUIRED

1. PC with windows (95/98/XP/NT/2000).


2. Xilinx Software

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.

We will derive an equation for each of the next state functions:


Current State Input Next State
C2 C1 C0 N2 N1 N0 ------------------------------------ 0 0 0 1 0 0 1
0011010
0101011
0111100
1001101
1011110
1101111
1 1 1 1 000

Fig 9.1: LOGIC DIAGRAM OF A MOD – 8 SYNCHRONOUS/ASYNCHRONOUS COUNTER

Fig 9.2: COUNTER MECHANISM

PROGRAM

VERILOG DESIGN CODE:

module mod8_counter (
input wire clk, // Clock input
input wire reset, // Synchronous reset
output reg [2:0] count // 3-bit output (0 to 7)
);

always @(posedge clk) begin


if (reset)
count <= 3'b000; // Reset to 0
else if (count == 3'b111)
count <= 3'b000; // Wrap around after 7
else
count <= count + 1; // Increment
end

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 (MATRIX LABORATORY):

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:

1. Math and computation


2. Algorithm development
3. Data acquisition
4. Modeling, simulation, and prototyping
5. Data analysis, exploration, and visualization
6. Scientific and engineering graphics
7. Application development, including graphical user interface building

At its core, MATLAB is essentially a set(a―toolbox) of routines(called―mfiles or ―mexfiles) that’s it on


your computer and a window that allows you to create new variables with names (e.g. voltage and time) and
process those variables with any of those routines (e.g. plot voltage against time, find the largest voltage, etc).

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.

THE MAIN FEATURES OF MATLAB

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.

MATLAB WINDOWS: MATLAB works through three basic windows

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.

1. The functional unit of data in any MATLAB program is the array.


An array is a collection of data values organized into rows and columns, and known by a single name.
2. MATLAB variable is a region of memory containing an array, which is known by a user specified name.
MATLAB variable names must begin with a letter, followed by any combination of letters, numbers, and
the underscore (_) character. Only the first 31 characters are significant; if more than 31 are used, the
remaining characters will be ignored. If two variables are declared with names that only differ in the 32 nd
character, MATLAB will treat them as same variable.
3. Spaces cannot be used in MATLAB variable names, underscore letters can be substituted to create
meaningful names.
4. It is important to include a data dictionary in the header of any program you write. A data
dictionary lists the definition of each variable used in a program. The definition should include both a
description of the contents of the variable and the units in which it is measured.

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.

HOW TO INVOKE MATLAB?

1. Double Click on the MATLAB icon on the desktop.


2. You will find a Command window where in which you can type the commands and see the OUTPUT. For
example if you type PWD in the command window, it will print current working directory.
3. If you want to create a directory, type mkdir mydir in the command window.
This will create a directory called pes.

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

WHERE TO WORK IN MATLAB?

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

I.e. help plot

BASIC INSTRUCTIONS IN MATLAB:

1. stem (t,x):- This instruction will display a figure window as shown.

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

3. Conv Syntax: w = conv(u,v) Description: w = conv(u,v) convolves vectors u and v. Algebraically,


convolution is the same operation as multiplying the polynomials whose coefficients are the elements of u
and v.

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.

5. xlabel Syntax: xlabel ('string')


Description: xlabel ('string') labels the x-axis of the current axes.

6. ylabel Syntax: ylabe l ('string')


Description: ylabel ('string') labels the y-axis of the current axes.

7. Title Syntax: title('string')


Description: title('string') OUTPUTs the string at the top and in the center of the current axes.

8. gridon Syntax: gridon


Description: grid on adds major grid lines to the current axes.

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.

CREATING MATLAB VARIABLES:


MATLAB variables are created with an assignment statement. The syntax of variable assignment is variable
name = a value (or an expression).
For example,
>> x = expression
Where expression is a combination of numerical values, mathematical operators, variables, and function calls.
In other words, expression can involve:
1. manual entry
2. built-in functions
3. user-defined functions

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:

1. To clear the Command Window, type clc


2. To abort a MATLAB computation, type ctrl-c
3. To continue a line, type..
EXPERIMENT – 1
WRITE A PROGRAM TO GENERATE VARIOUS SIGNALS AND
SEQUENCES: PERIODIC AND APERIODIC, UNIT IMPULSE, UNIT
STEP, SQUARE, SAW TOOTH, TRIANGULAR, SINUSOIDAL, RAMP,
SINC FUNCTION

AIM

To generate different types of standard signals Using MATLAB Software.

APPARATUS REQUIRED

1. PC with windows (95/98/XP/NT/2000).


2. MATLAB Software

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.

UNIT IMPULSE FUNCTION:

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

Fig 1.1: DISCRETE UNIT IMPULSE FUNCTION


UNIT STEP SIGNAL:

Discrete time unit step signal is defined as


u[n] = {1,0 ,nn<0≥ 0

Fig 1.2: DISCRETE UNIT STEP FUNCTION


\
UNIT RAMP FUNCTION:

A discrete unit ramp function can be defined as

{
r [ n ] = n , for n≥ 0
0 , for n< 0

Fig 1.3: DISCRETE RAMP FUNCTION

SINUSOIDAL SIGNAL GENERATION:

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.

Fig 1.4: SINUSOIDAL FUNCTION

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 Generate Various Signals and Sequences

% Time vector
t = -2:0.01:2; % Time range from -2 to 2 with step size 0.01

% Plot Unit Impulse Function


% Unit Impulse Function
delta_t = (t == 0); % Impulse function: 1 at t=0, 0 elsewhere
subplot(3,3,1);
stem(t, delta_t, 'filled');
title('Unit Impulse Function');
xlabel('Time');
ylabel('Amplitude');
axis([-2 2 -0.1 1.1]);
% Plot Unit Step Function
% Unit Step Function
u_t = (t >= 0); % Step function: 0 for t<0, 1 for t>=0
subplot(3,3,2);
plot(t, u_t, 'LineWidth', 2);
title('Unit Step Function');
xlabel('Time');
ylabel('Amplitude');
axis([-2 2 -0.1 1.1]);

% Plot Square Wave


% Square Wave
T_square = 1; % Period of the square wave
x_square = square(2 * pi * t / T_square);
subplot(3,3,3);
plot(t, x_square, 'LineWidth', 2);
title('Square Wave');
xlabel('Time');
ylabel('Amplitude');
axis([-2 2 -1.5 1.5]);

% Plot Sawtooth Wave


% Sawtooth Wave
T_sawtooth = 1; % Period of the sawtooth wave
x_sawtooth = sawtooth(2 * pi * t / T_sawtooth);
subplot(3,3,4);
plot(t, x_sawtooth, 'LineWidth', 2);
title('Sawtooth Wave');
xlabel('Time');
ylabel('Amplitude');
axis([-2 2 -1.5 1.5]);

% Plot Triangular Wave


% Triangular Wave
T_triangular = 1; % Period of the triangular wave
x_triangular = sawtooth(2 * pi * t / T_triangular, 0.5); % 0.5 specifies triangular waveform

subplot(3,3,5);
plot(t, x_triangular, 'LineWidth', 2);
title('Triangular Wave');
xlabel('Time');
ylabel('Amplitude');
axis([-2 2 -1.5 1.5]);

% Plot Sinusoidal Wave


% Sinusoidal Wave
A = 1; % Amplitude
f = 1; % Frequency in Hz
phi = 0; % Phase shift
x_sin = A * sin(2 * pi * f * t + phi);
subplot(3,3,6);
plot(t, x_sin, 'LineWidth', 2);
title('Sinusoidal Wave');
xlabel('Time');
ylabel('Amplitude');
axis([-2 2 -1.5 1.5]);

% Plot Ramp Function


% Ramp Function
x_ramp = t .* (t >= 0); % Ramp function: linear increase for t>=0

subplot(3,3,7);
plot(t, x_ramp, 'LineWidth', 2);
title('Ramp Function');
xlabel('Time');
ylabel('Amplitude');
axis([-2 2 -0.1 2]);

% Plot Sinc Function


% Sinc Function
x_sinc = sinc(t); % Sinc function: normalized sinc

subplot(3,3,8);
plot(t, x_sinc, 'LineWidth', 2);
title('Sinc Function');
xlabel('Time');
ylabel('Amplitude');
axis([-2 2 -0.5 1]);

% Adjust the layout


sgtitle('Various Signals and Sequences');

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

1. PC with windows (95/98/XP/NT/2000).


2. MATLAB Software

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

% MATLAB Program to Demonstrate Operations on Signals and Sequences

% Time vector
t = -10:0.01:10; % Time range from -10 to 10 with step size 0.01

% Define two example signals


x1 = sin(t); % Signal 1: Sinusoidal wave
x2 = cos(t); % Signal 2: Cosine wave

% Plot Original Signals


subplot(3,3,1);
plot(t, x1, 'b', 'LineWidth', 1.5);
title('Signal x1 (sin(t))');
xlabel('Time');
ylabel('Amplitude');
subplot(3,3,2);
plot(t, x2, 'r', 'LineWidth', 1.5);
title('Signal x2 (cos(t))');
xlabel('Time');
ylabel('Amplitude');

% 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

shift_amount = 5; % Shift by 5 units


t_shifted = t - shift_amount; % New time vector
x_shifted = interp1(t, x1, t_shifted, 'linear', 0); % Shifted signal (linear interpolation)
subplot(3,3,6);
plot(t, x_shifted, 'c', 'LineWidth', 1.5);
title('Shifting: x1 shifted');
xlabel('Time');
ylabel('Amplitude');

% 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

energy_x1 = sum(x1.^2) * 0.01; % Energy of x1 (using step size 0.01)


energy_x2 = sum(x2.^2) * 0.01; % Energy of x2 (using step size 0.01)

% Average Power Computation


average_power_x1 = mean(x1.^2);
average_power_x2 = mean(x2.^2);

% Display computed values


subplot(3,3,8);
text(0.1, 0.8, ['Energy of x1: ', num2str(energy_x1)], 'FontSize', 12);
text(0.1, 0.6, ['Energy of x2: ', num2str(energy_x2)], 'FontSize', 12);
text(0.1, 0.4, ['Average Power of x1: ', num2str(average_power_x1)], 'FontSize', 12);
text(0.1, 0.2, ['Average Power of x2: ', num2str(average_power_x2)], 'FontSize', 12);
axis off;

% Adjust the layout


sgtitle('Operations on Signals and Sequences');

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

1. PC with windows (95/98/XP/NT/2000).


2. MATLAB Software

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.

TRIGONOMETRIC FOURIER SERIES:

The trigonometric Fourier series representation of a periodic signal x (t) with fundamental period T, is given by



x (t )=a0 + ∑ ( ak cos kω 0 t +b k sink ω 0 t ) , ω 0=
k=1 T0

where ak and bk are Fourier coefficients given by

2 2
a k= ∫
T0 T
x ( t ) cosk ω0 tdt ,b k = ∫ x ( t ) sink ω0 tdt
T0 T
0 0

a0 is the dc component of the signal and is given by


1
a 0= ∫ x ( t ) dt
T0 T 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

% Define the parameters


T = 2; % Period of the rectangular wave
T0 = 1; % Width of the rectangular pulse
n_terms = 10; % Number of Fourier series terms for reconstruction

% Time vector for the signal and reconstruction


t = linspace(-T, T, 1000); % Time vector for plotting
t_rec = linspace(-T, T, 1000); % Time vector for reconstruction

% Define the rectangular signal


rectangular_signal = @(t) (mod(t, T) < T0) - 0.5;

% Compute the Fourier series coefficients


a0 = 1/T * integral(@(t) rectangular_signal(t), -T/2, T/2); % DC component

% Trigonometric coefficients (cosine terms)


a_n = zeros(1, n_terms);
b_n = zeros(1, n_terms);

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

% Compute the exponential Fourier coefficients


c_n = zeros(1, 2*n_terms+1);
c_n(n_terms+1) = a0; % a0 is the constant term
for n = 1:n_terms
c_n(n_terms + n + 1) = (a_n(n) - 1i * b_n(n)) / 2; % Positive frequencies
c_n(n_terms - n + 1) = (a_n(n) + 1i * b_n(n)) / 2; % Negative frequencies
end
% Reconstruct the signal using Fourier coefficients
reconstructed_signal = a0 / 2; % Start with a0/2

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

% Plotting the results


figure;

% Plot the rectangular signal


subplot(3, 2, 1);
plot(t, rectangular_signal(t), 'k', 'LineWidth', 1.5);
title('Rectangular Signal');
xlabel('Time');
ylabel('Amplitude');
axis([-T T -0.6 0.6]);

% Plot the DC component


subplot(3, 2, 2);
stem(0, a0, 'filled');
title('DC Component (a0)');
xlabel('Frequency');
ylabel('Magnitude');
axis([-0.5 0.5 0 1]);

% Plot the trigonometric Fourier series coefficients


subplot(3, 2, 3);
stem(1:n_terms, a_n, 'filled');
title('Cosine Coefficients (a_n)');
xlabel('n');
ylabel('Magnitude');
axis([0 n_terms 0 max(a_n) + 1]);

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]);

% Plot the reconstructed signal


subplot(3, 2, 5);
plot(t_rec, reconstructed_signal, 'b', 'LineWidth', 1.5);
title('Reconstructed Signal');
xlabel('Time');
ylabel('Amplitude');
axis([-T T -0.6 0.6]);

% Plot the exponential Fourier series coefficients


subplot(3, 2, 6);
stem(linspace(-n_terms, n_terms, 2*n_terms+1), abs(c_n), 'filled');
title('Exponential Fourier Coefficients (|c_n|)');
xlabel('Frequency Index');
ylabel('Magnitude');
axis([-n_termsn_terms 0 max(abs(c_n)) + 1]);

% Adjust layout
sgtitle('Fourier Series Analysis of a Rectangular Signal');

OUTPUT

Fig 3.1: FOURIER ANALYSIS OF A RECTANGULAR SIGNAL

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

1. PC with windows (95/98/XP/NT/2000).


2. MATLAB Software

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
−∞

DFT of a sequence is:


N−1 − j2 π k n

X [k ]= ∑ x [ n ] e N

k=0

where N = Length of sequence.


K = Frequency Coefficient.
n = Samples in time domain.
FFT: -Fast Fourier transform, there are two methods.
1. Decimation in time (DIT FFT).
2. Decimation in Frequency (DIF FFT).

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 the Fourier Transform of a Signal

% Define the signal parameters


Fs = 1000; % Sampling frequency (Hz)
T = 1/Fs; % Sampling period (seconds)
L = 1000; % Length of the signal
t = (0:L-1) * T; % Time vector

% 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);

% Compute the Fourier Transform using Fast Fourier Transform (FFT)


Y = fft(signal);
P2 = abs(Y / L); % Two-sided spectrum
P1 = P2(1:L/2+1); % Single-sided spectrum
P1(2:end-1) = 2 * P1(2:end-1);

% Compute the frequency vector


f = Fs * (0:(L/2)) / L;

% Compute the phase spectrum


phase_spectrum = angle(Y(1:L/2+1));

% Plot the signal


figure;
subplot(3, 1, 1);
plot(t, signal, 'b');
title('Time-Domain Signal');
xlabel('Time (seconds)');
ylabel('Amplitude');

% Plot the amplitude spectrum


subplot(3, 1, 2);
plot(f, P1, 'r');
title('Amplitude Spectrum');
xlabel('Frequency (Hz)');
ylabel('Magnitude');

% Plot the phase spectrum


subplot(3, 1, 3);
plot(f, phase_spectrum, 'g');
title('Phase Spectrum');
xlabel('Frequency (Hz)');
ylabel('Phase (radians)');

% Adjust the layout


sgtitle('Fourier Transform Analysis');

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

1. PC with windows (95/98/XP/NT/2000).


2. MATLAB Software

THEORY

Linear Convolution involves the following operations.


Folding
Multiplication
Addition
Shifting
These operations can be represented by a Mathematical Expression as follows:

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

%program for convolution of two sequences


clc;
close all;
clear all;

%program for convolution of two sequences


x=input('enter input sequence');
h=input('enter impulse response');
y=conv(x,h);
subplot(3,1,1);
stem(x);
xlabel('n');
ylabel('x(n)');
title('input signal')
subplot(3,1,2);
stem(h);
xlabel('n');
ylabel('h(n)');
title('impulse response')
subplot(3,1,3);
stem(y);
xlabel('n');
ylabel('y(n)');
title('linear convolution')
disp('The resultant signal is');
disp(y)

OUTPUT

Fig 5.1: CONVOLUTION OF TWO SIGNALS

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

To write a program to find the autocorrelation and cross correlation of sequences.

APPARATUS REQUIRED

1. PC with windows (95/98/XP/NT/2000).


2. MATLAB Software

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
¿

−∞

where ⋆ denotes the complex conjugate.

Similarly the autocorrelation of the discrete time signal x[n] is expressed as


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;

% two input sequences


x=input('enter input sequence');
h=input('enter the impulse sequence');
subplot(2,2,1);
stem(x);
xlabel('n');
ylabel('x(n)');
title('input sequence');
subplot(2,2,2);
stem(h);
xlabel('n');
ylabel('h(n)');
title('impulse signal');

% cross correlation between two sequences


y=xcorr(x,h);
subplot(2,2,3);
stem(y);
xlabel('n');
ylabel('y(n)');
title(' cross correlation between two sequences ');

% auto correlation of input sequence


z=xcorr(x,x);
subplot(2,2,4);
stem(z);
xlabel('n');
ylabel('z(n)');
title('auto correlation of input sequence');

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

1. PC with windows (95/98/XP/NT/2000).


2. MATLAB Software

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.

If x(n) is a input signal and y(n) is a output signal then y(n)=T[x(n)]


y1(n) =T[x1(n)] and y2(n) =T[x2(n)]
x3(n) =[a*x1(n) +b*x2(n) ]
y3(n) = T [x3(n)]

T [a*x1(n)+b*x2(n) ] = a y1(n)+ b y2(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

% MATLAB Program to Verify Linearity and Time Invariance of a Continuous System

% Define the continuous-time system


% Example system: T{x(t)} = x(t) * cos(t)
% Define the time vector
t = linspace(-10, 10, 1000); % Time vector from -10 to 10

% Define input signals


x1 = sin(t); % First input signal
x2 = cos(t); % Second input signal

% Define scaling factors


a = 2;
b = 3;

% Define time shift


t_shift = 2;

% Define the system response


system_response = @(x) x .* cos(t); % System: y(t) = x(t) * cos(t)

% Compute the responses


y1 = system_response(x1); % Response to x1
y2 = system_response(x2); % Response to x2

% 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

% Time Invariance Verification


% Time shifted input: x1(t - t_shift) and x2(t - t_shift)
x1_shifted = sin(t - t_shift);
x2_shifted = cos(t - t_shift);

% System response to shifted inputs


y1_shifted = system_response(x1_shifted);
y2_shifted = system_response(x2_shifted);

% Expected time-shifted response


expected_response_shifted = a * y1_shifted + b * y2_shifted;

% Plotting
figure;

% Plot original signals and their responses


subplot(3, 2, 1);
plot(t, x1, 'b', t, x2, 'r--');
title('Input Signals');
xlabel('Time');
ylabel('Amplitude');
legend('x1(t)', 'x2(t)');
subplot(3, 2, 2);
plot(t, y1, 'b', t, y2, 'r--');
title('System Responses to x1 and x2');
xlabel('Time');
ylabel('Amplitude');
legend('T{x1}', 'T{x2}');

% Plot the linearity verification


subplot(3, 2, 3);
plot(t, superposition_input, 'k', t, linear_combination_response, 'g--');
title('Linearity Verification');
xlabel('Time');
ylabel('Amplitude');
legend('Superposition Input', 'a*T{x1} + b*T{x2}');

% Plot the time invariance verification


subplot(3, 2, 4);
plot(t, superposition_response, 'k', t, expected_response_shifted, 'g--');
title('Time Invariance Verification');
xlabel('Time');
ylabel('Amplitude');
legend('T{a*x1 + b*x2}', 'Expected Response after Time Shift');

% Adjust layout
sgtitle('Verification of Linearity and Time Invariance')

OUTPUT

Fig 7.1: LINEARITY AND TIME INVARIANCE VERIFICATION

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

1. PC with windows (95/98/XP/NT/2000).


2. MATLAB Software

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

Fig 8.1: ALIASING DUE TO INADEQUATE SAMPLING

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

1. PC with windows (95/98/XP/NT/2000).


2. MATLAB Software

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

% Generate Complex Gaussian noise


real_part = sqrt(variance_value/2) * randn(1, N) + mean_value;
imaginary_part = sqrt(variance_value/2) * randn(1, N) + mean_value;
complex_noise = real_part + 1i * imaginary_part;

% Compute mean and variance


mean_complex = mean(complex_noise);
variance_complex = var(complex_noise);

% PDF (Probability Density Function)


figure;
histogram(abs(complex_noise), 'Normalization', 'pdf');
title('Probability Density Function (PDF) of Complex Gaussian Noise');
xlabel('Magnitude');
ylabel('Probability Density');

% Power Spectral Density (PSD)


L = 1024; % Length of FFT
psd_complex = pwelch(complex_noise,[], [],L);

% 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

Fig 9.1: PROBABILITY OF POWER DENSITY FUNCTION

RESULT

Hence, we can generate complex Gaussian noise and find its mean, variance, Probability Density Function
(PDF) and Power Spectral Density (PSD).

You might also like