0% found this document useful (0 votes)
27 views

Control System Lab Manual

Uploaded by

vikasstanli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Control System Lab Manual

Uploaded by

vikasstanli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

SCHOOL OF MECHANICAL ENGINEERING

MICROCONTROLLERS & INTERFACING LAB

LABORATORY MANUAL

B.Tech. Mechanical Engineering


B.Tech. Mechanical Engineering (Automotive Engineering)
B.Tech. Mechanical Engineering (Manufacturing Engineering)

June 2024
CONTENTS

Page No.

1. Introduction to 8051 Microcontroller 04

2. Programming with KEIL software 09

3. Assembly language programming 24

4. Interfacing push button and LED with microcontroller 35

5. Interfacing Keypad and LCD Interface with microcontroller 38

6. Interfacing ultrasonic sensor with microcontroller 44

7. Speed and direction control of DC motor using microcontroller 48

8. Speed control of Servo motor using microcontroller 50

9. Interfacing stepper motor with microcontroller 53

10. Traffic light Control with Microcontroller 55

11. Blue Tooth Wireless data transmission microcontroller 58

12. Creating linear control system models using transfer function and 65
state-space representations

13. Visualization of system behavior in time domain and frequency 71


domain

2
COURSE OBJECTIVES

1. To expose the students to fundamentals of microcontrollers.


2. To understand the functions of microcontroller, programming and interfacing.
3. To enable the students to design appropriate microcontroller based systems.

COURSE OUTCOMES
At the end of the course, the student will be able to,
1. Demonstrate and interface microcontroller with sensors and actuators.
2. Develop speed control techniques using microcontroller.
3. Construct the simulation model in MATLAB.

3
1. INTRODUCTION TO 8051 MICROCONTROLLER

1.1 Introduction

Microcontroller consists of all features that are found in microprocessors with additional
built-in ROM, RAM, I/O ports, Serial ports, Timers, Interrupts, and Clock circuits. It is an
entire computer on a single chip that is embedded within applications. Microcontrollers
are widely used in many domestic (washing machines, VCD players, microwave oven,
robotics, etc.) as well as industrial and automobile areas.

The 8051 is the first microcontroller of the MCS-51 family developed by Intel Corporation
in 1980. It was developed using N-type Metal-Oxide-Semiconductor (NMOS) technology
and later it came to be identified by a letter C in their names e.g. 80C51 which was
developed with Complementary Metal-Oxide-Semiconductor (CMOS) technology which
consumes less power than NMOS and made it better compatible for battery-powered
applications. Microcontrollers can be classified on the basis of their bit processing
capability e.g.8-bit microcontroller means it can read, write, and process 8-bit data.
Basically, it specifies the size of the data bus. Today microcontrollers are designed with
much more compact, cheap, and powerful specifications like AVR and PIC.

The Key features of the 8051 Microcontroller


 4 KB on-chip ROM (Program memory)
 128 bytes on-chip RAM (Data memory)
 The 8-bit data bus (bidirectional)
 16-bit address bus (unidirectional)
 Two 16-bit timers
 Instruction cycle of 1 microsecond with 12
MHz crystal Fig.1.1 8051 Microcontroller
 Four 8-bit input/output ports (Image Courtesy: https://www.cpu-
world.com/ CPUs/8051/Intel-
 128 user-defined flags P8051AH.html)

 Four register banks of 8 bit each


 16-byte bit-addressable RAM
 General purpose registers are 32 each is 8-bit
 Two external and three internal interrupts
 8051 microcontroller specifies some special function features like UARTs, ADC, Op-
amp, etc.
 16-bit program counter and data pointer

4
1.2 Block-Structure Diagram of 8051 Microcontroller

Fig. 1.2 Block Diagram of 8051 Microcontroller

8051 is one of the first and most popular microcontrollers also known as MCS-51. Intel
introduced it in the year 1981. Initially, it came out as an N-type metal-oxide-
semiconductor (NMOS) based microcontroller, but later versions were based on
complementary metal-oxide-semiconductor (CMOS) technology. It is an 8-bit
microcontroller which means the data bus is 8-bit. Therefore, it can process 8 bits at a
time. It is used in a wide variety of embedded systems like robotics, remote controls, the
automotive industry, telecom applications, power tools, etc. It is referred to as a System
on a Chip (SoC) microcontroller because it is a chip circuit/integrated circuit that holds
many components of a computer together on a single chip. These components include a
CPU, memory, input-output ports (I/O ports), timers, and secondary storage. 8051μc have
family members 8052 microcontroller & 8031 microcontroller. 8052μc has 8K bytes of
on-chip program ROM instead of 4K bytes, and 128 bytes of RAM. and 8031μc has 0K
bytes of on-chip program ROM, and 128 bytes of RAM.

1.3 Pin Description of 8051

The 8051 microcontroller is a popular 8-bit microcontroller widely used in embedded


systems. It is a single-chip microcontroller with a Harvard architecture that includes a
CPU, RAM, ROM, and several peripherals. The 8051 microcontroller has a 40-pin dual in-
line package (DIP) that provides various inputs and outputs for communication with
external devices. The 40 pins serve different functions like read, write, I/O operations,
interrupts etc. 8051 has four I/O ports wherein each port has 8 pins which can be
configured as input or output depending upon the logic state of the pins. Therefore, 32

5
out of these 40 pins are dedicated to I/O ports. The rest of the pins are dedicated to VCC,
GND, XTAL1, XTAL2, RST, ALE, EA’ and PSEN’.

Fig. 1.3 Pin Diagram of 8051 Microcontroller

1.4 Application of Microcontrollers

 Automation: The 8051 microcontroller is widely used in automation applications.


They are widely used automation of machine operations, product tracking in
assembly and inspection systems with appropriate sensors.

 Industrial Control Systems: The 8051 microcontroller is used in industrial control


systems, such as process control systems and manufacturing equipment, to control
and monitor various processes and operations.

 Energy management: Competent measurement systems support energy


consumption calculations in home and industrial environments. These measuring
systems are prepared by integrating a microcontroller.

 Embedded Systems: The 8051 microcontroller is commonly used in embedded


systems, such as home automation systems, security systems, and industrial control

6
systems. Its low cost, small size, and ease of programming make it an ideal choice
for these applications.

 Automotive Systems: The 8051 microcontroller is used in automotive systems,


such as engine control units, anti-lock braking systems, and airbag systems, to
control various functions and ensure safe and efficient operation.

 Robotics: The 8051 microcontroller is used in robotics applications to control the


movement and operation of robots. It is commonly used to control the motors,
sensors, and other peripherals of the robot.

 Environmental monitoring: Convenient environmental devices such as humidity,


temperature and pollution monitors contain microcontrollers to display
measurements in real-time.

 Consumer Electronics: The 8051 microcontroller is used in a variety of consumer


electronics products, such as digital cameras, gaming systems, and audio players. It
is commonly used to control the user interface, display, and other peripherals of
these devices.

 Communication Systems: The 8051 microcontroller is used in communication


systems, such as modems, routers, and switches, to control the data transfer and
communication protocols.

 Medical Devices: The 8051 microcontroller is used in medical devices, such as


insulin pumps, heart monitors, and blood glucose meters, to control various
functions and provide accurate and reliable results.

1.5 Functional Blocks of 8051 Development Board

A microcontroller development board is a printed circuit board (PCB) with circuitry and
hardware designed to facilitate experimentation with a microcontroller. Development
boards are printed circuit boards with either a microcontroller or a microprocessor
mounted on them and with various metal pins that an experienced developer can use to
develop, prototype, and iterate different versions of various smart products. Development
boards provide a pre-designed, integrated environment that allows developers to
concentrate on the functionality of their concept rather than the hardware specifics. This
substantially speeds up prototyping and increases productivity.

7
SERVO MOTOR 4 x 4 KEYPAD TEMPERATURE SENSOR
DRIVE

ULN2B03
BUZZER

MICROCONTROLLER
ZIGBEE

MEMORY
USB

POWER LED

8051
DC MOTOR
RTC
RELAY
PUSHBUTTONS

7 SEGMENT LED
ISP

2 X 16 LCD

DC MOTOR DRIVER ON / OFF SWITCH 12V AC/DC INPUT

Fig. 1.4 Block diagram of 8051 Microcontroller Development Board

Fig. 1.5 8051 Microcontroller Development Board

8
2. PROGRAMMING WITH KEIL SOFTWARE

Embedded system means some combination of computer hardware and programmable


software which is specially designed for a particular task like displaying message on LCD. One of
the important parts in making an embedded system is loading the software/program we develop
into the microcontroller. Usually it is called “burning software” into the controller. Before “burning
a program” into a controller, we must do certain prerequisite operations with the program. This
includes writing the program in assembly language or C language, compiling the program in a
compiler and finally generating the hex code and bin code from the compiled program. Keil
MicroVision is free software which solves many of the pain points for an embedded program
developer. This software is an integrated development environment (IDE), which integrated a text
editor to write programs, a compiler and it will convert your source code to hex files too. Here is
simple guide to start working with Keil uVision which can be used for writing programs in C/C++
or Assembly language, compiling and assembling programs, debugging program, creating Hex and
Bin file, and testing program without real hardware (Simulator Mode)

2.1 Working with KEIL MICRO VISION software


STEP 1: Create new folder in the name of FLASHING LED, and copy lcd.c and lcd.h from From CD
Embedded lab experiment code FLA SHING LED code Main files: FLASHING LED.c Sub files: lcd.c,
lcd.h
STEP 2: Click for KEIL µVISION4 Icon .Which appearing after Installing KEIL µVISION4

After opening Keil uV4, go to Project tab and Create new uVision project

9
Create the project in FLASHING LED folder created in Step1 and give save.

STEP 3: Select Target Device Vendor (i.e.).NUVOTON& click ok

10
STEP 4: Then select specific chip W78E052 in NUVOTON.

Then click ok, you will see following window click yes

Note: Code wills not run without Startup.s

STEP 5: Then you will see following window

11
STEP 6: Now Startups is already added which is necessary for running code for Keil. Startup.s is
available in C:\Keil\ARM\Startup\Philips. The startup-code executes immediately upon reset of
the target system and performs thefollowing operations:

Adding C - file can be done in two ways.


Method 1: Creating a new c file for FLASHING LED.C
STEP 7: Now Click on File Menu and Click on New.

Write Code for FLASHING LED in C and save it as FileName.c here FLASHING LED.c
Write Code for flashing led in C and SAVE as FLASHING LED.c

12
STEP 8: Once the code is written it has to be added to the project to do that right click on source
group and select “ADD FILES TO SOURCE GROUP” option AND add FILES FLASHINGLED.c, lcd.c.
Main files: FLASHING LED.c
Sub files: lcd.c, lcd.h

OR

METHOD 2: Using existing file from copied folder


Copy FLASHING LED.c file from
CD Embedded lab experiment code FLASHING LED code
copy to FLASHINGLED folder

Now add FLASHING LED.c , lcd.c, to source group from FLASHING LED FOLDER

13
Copy flashing led .c and lcd.c from Embedded lab experiment code

Now the folder contains flashing led.c and lcd.c.


Add files to Source Group

14
Now add lcd file to the source

Hex file and bin files are not created unless we follow particular steps. Steps to be followed for
creating hex file and bin files are mentioned below

2.2 Creating Hex file


The Intel hex (ihex) generally known as hex file, is a format used to store machine language
code in hexadecimal form. It is widely used format to store programs to be transferred to
microcontrollers, ROM and EEPROM. The compilers convert the programs written in assembly, C

15
etc into corresponding hex files, which are dumped into the controllers using
burners/programmers.

STEP 1: Go to Options for Target 1‟.

STEP 2: Go to output Tab

16
STEP 3: Click on Check Box “Create HEX File”.

STEP 5: Then Click on Rebuild All Target Files

Once the project is build result can be seen at the bottom. If any errors are present list of errors
will be displayed or if project has no errors build is said to be successful.

STEP 6: Now look for 0 Error(s), 0 Warning (s). Then Hex File will create in Specific Folder.
Now todownload it for you target hardware

17
2.3 Burning Hexfile In to the Chip
STEP 1: Connect USB CABLE in the 8051 kit to the system via serial cable.
STEP 2: Click the windows buton and search for NUVOTON ISP-ICP UTILITY and click on it.

STEP 3: NUVOTON ISP-ICP UTILITY WINDOW WILL OPEN

18
STEP 4: CLICK as shown below

STEP 5: Note the port connected, here its connected to COM2.

19
STEP 6: Select the COM port which is connected in the system.

STEP 7: Select the IC Number “W78E052D”

20
STEP 8: Click the ‘LOAD FILE’ button

STEP 9: Select the hex file created in step6 in hex file creation and click the open button.

21
STEP 10: Click the “UPDATE CHIP” button

STEP 11: While uploading the data you should be click the reset button.

The reset button is located in 8051 kit.

22
STEP 12: Just Click OK

STEP 13: when the upload was completed the popup window will be shown as updated.

23
3. ASSEMBLY LANGUAGE PROGRAMMING

Objective
To program a microcontroller with assembly language.

Hardware and Software


1. Computer
2. KEIL Software

Features of MC-8051
 MC-8051 is an 8-bit Microcontroller.
 It is a 40 pin IC Chip.
 It has RAM(On Chip) of 128 bytes.
 It has ROM(On Chip) of 4K bytes.
 8051-MC Works with 12 MHz clock and a single +5V supply.
 It has 111 instructions: 49 single byte, 45 two byte and 17 three byte

Program for 8-bit Addition


;program for 8-bit addition in assembly language programming
ORG 0000
MOV A,#5
MOV B,#5
ADD A,B
MOV 50H,A
MOV R0,50H
END

Program Description
 ORG 0000H means it set the statement at memory address 0000H.
 MOV A,#5 using immediate Addressing mode we are transferring hexadecimal ‘5’
to accumulator.
 MOV B,#5 Same as above we are transferring hexadecimal 5 to b.
 ADD A,B here add opcode will adds the data of a and b
 MOV 50H,A this line uses to store the output to the memory address 50h from
accumulator.
 MOV R0,50H this line uses to store the output to the register from memory 50h.

24
 END This ‘end’ opcode to stops the program
 To Write comments in Assembly language we use a “;“.

Flowchart of program

To write a 8-bit addition program using assembly language programming, we need a


IDE to write and run it. In this case we are using Keil uVision software.

Steps to use Keil uVision Software


After Installing the Keil software follow the steps to perform the 8-bit Addition
1. Open the software and click on the Project option which is settled at the top of the
window, Then it will shows a popup like this below:

25
Keil uVision Software

And then click on the “New uVision Project” option then it will opens and explorer to
save it like below:

Saving the Project

26
Give a name to your Project and save it in a desired location. Then a popup will display
to select the device of microcontroller, in this case select the ‘AT89C51’ Microcontroller
to run the program. In the popup there will be a search bar, type the name then select
the device:

Select the MC AT89C51

After selecting the MC click on “OK” Option ‘AT89C51’ is a Microcontroller that designed
by ‘ATML’ it is 8051-MC. Then you will get a dialog box with yes or no like below:

Click on NO

Click on ‘NO’ if we don’t have need of that file. If you have any use cases with that file we
can click on YES. Then it successfully created a project file like below:

27
Then right click on Source Group 1 and click on the option called “add new item to
Group ‘Source Group 1′” and select the file type and enter the file name also like below:

Then click on Add that create an .asm file in your project. Now the ‘asm’ file will be open
in the editor to type the program so that Enter the above Program of 8-bit Addition. You
can paste the above Program in your code editor after completing the code click on “F7”
key to Build the target file or right click on the .asm file and select Build target option
from there.

28
The Build output box will be displayed as:
Build started: Project: addition
Build target 'Target 1'
assembling add.asm...
linking...
Program Size: data=8.0 xdata=0 code=11
".\Objects\addition" - 0 Error(s), 0 Warning(s).
Build Time Elapsed: 00:00:01

So when we are getting the output as 0 Errors we can proceed to run the Program by
debugging. To debug the program we can simply click ‘ctrl + F5’ or there will be a option
to do that at the top of the window.

To debug the program by step wise or complete program at a time by clicking on keys,
By clicking on F11 Key we can achieve step wise debugging, at start the register values
are like below:

At starting all the registers are empty by pressing the F11 key we can check how the
values of the accumulator, b are changing.

29
We can in the above picture that the value #5 came into Accumulator and B also added,
the result was stored in Accumulator as per the program, as in the program we are
added that to store the value in r0 register and 50h address see the result in the below:

As you can see the result was stored in R0 Register and 50h address. so that we can
change the program to test your own values and make sure to rebuilt it again by clicking
on F7 key .

30
Applications of Assembly Language Programming

Assembly Language Programming have lot more applications. Few are,


1. Used to design Real-time Systems
2. Used to design Embedded Systems
3. Used in Writing OS
4. Used in Writing FirmWare
5. Used to develop compilers and interpreters, etc.

Advantages of using Assembly Language in 8051


1. It is faster than using a high-level language.
2. It works more efficiently in terms of memory usage.
3. It gives the programmer more control over the code.

Disadvantages of using Assembly Language in 8051


1. It is difficult to write and maintain.
2. It is not portable to other microcontrollers.

31
Additional Programs

1. TRANSFER OF BLOCK OF DATA BYTES FROM SOURCE MEMORY TO DESTINATION


MEMORY USING 8051

Program:

MOV R0,#50H // Initialize the source memory pointer


MOV R1,#60H // Initialize the destination memory pointer
MOV R2, #05H // Initialize Iteration counter
BACK: MOV A,@R0 // Get the data from source memory pointer
MOV @R1,A // Store the data into destination memory pointer
INC R0 // Increment the source memory pointer
INC R1 // Increment the destination memory pointer
DJNZ R2, BACK // Decrement iteration count and if it
// is not zero, go to relative Address and
// repeat the same process until count become
// zero.
END

Memory Window:

Before execution:
D:0x50H: 22 AB 3D 44 55 00
D:0X60H: 00 00 00 00 00 00

After execution:
D:0x50H: 22 AB 3D 44 55 00
D:0X60H: 22 AB 3D 44 55 00

32
2. 16 BIT ADDITION

Program:

MOV R0,#51H // Initialize input1 memory pointer


MOV R1,#61H /* Initialize input2 memory pointer and store output also same */
MOV R2,#02H // Initialize iteration count
CLR C
BACK: MOV A,@R0 /*Get lower bytes data in first iteration, upper bytes data in second
iteration, add them with carry and store in memory pointer2.*/
ADDC A,@R1
MOV @R1,A
DEC R0 // Increment memory pointer1 & 2 to get upper bytes
DEC R1
DJNZ R2,BACK /* Decrement iteration count and if it is not zero, go to relative address
and repeat the same process until count become zero.*/
JNC FINISH
MOV @R1,#01H
FINISH:SJMP $
END

Memory Window:

Before execution:
D:0x50H: FD 07 00 00 00 00
D:0X60H: FF 5F 00 00 00 00

After execution:
D:0x50H: FD 07 00 00 00 00
D:0X5FH: 01 FC 66 00 00 00

33
3. ARRANGEMENT OF 8-BIT NUMBERS IN ASCENDING ORDER

Program:

MOV R2, #05H // Initialize the iteration counter


DEC R2 // Decrement the iteration count
BACK1: MOV R0, #50H // Initialize memory pointer1
MOV R1, #51H // Initialize memory pointer2
MOV A, R2 // Store outer loop count
MOV R3, A // Store inner loop count
BACK: MOV A,@R0 // Get the data from memory pointer1
MOV B,@R1 // Get the data from memory pointer2
CJNE A, B, LOOP /* Compare if not equal go to relative address (LOOP)*/
LOOP: JC LOOP1 /* If carry generates, go to relative address (LOOP1)*/
MOV @R0,B // Exchange the data in memory pointer
MOV @R1, A
LOOP1: INC R0 // Increment the memory pointer1
INC R1 // Increment the memory pointer2
DJNZ R3, BACK // Decrement inner loop count if not zero go to
back
DJNZ R2, BACK1 // Decrement outer loop count if not zero go to
back1
END

Memory Window:

Before execution:
D:0x50H: 06 04 03 07 02 01

After execution:
D:0x50H: 01 02 03 04 06 07

34
4. PUSH BUTTON AND LED INTERFACE

The objective is to create the simplest experiment by using 4 pushbutton and led interface
with 8051 microcontroller. Basically, you connect a few things easily, write some code,
and upload it to the 8051 microcontroller. With that, the Push buttons or switches connect
two points in a circuit when you press them, LED gets ON and OFF.

Circuit Connection

From above the figure explained that how to make connections between 8051
microcontroller and 4 bush buttons and LED through wire connections as a
corresponding pin described in table.

8051 PINS LED AND SWITCH PINS


P1.0 SW1
P1.1 SW2
P1.2 SW3
P1.3 SW4
P3.4 LED1
P3.5 LED2
P3.6 LED3
P3.7 LED4

35
Procedure

• Set up the circuit as described in the “Circuit Connection” section.


• Connect the 8051 MICROCONTROLLER to your computer using a USB cable.
• Open the KEIL UVISION4 software on your computer.
• Write the code for 4 pushbutton and led interface in 8051 MICROCONTROLLER.
• Create a hex file as a instructions given.
• Open the NUVUTON ISP-ICP utility software on your computer.
• Click the upload button and upload the hex file which is created by the KEIL
software.
• Verify and upload the code to the 8051 MICROCONTROLLER.
• When the button is not pressed, the LED will turn off.
• When the button is press the LED will turn on.

PROGRAM

#include<reg51.h>
sbit sw1=P1^0;
sbit sw2=P1^1;
sbit sw3=P1^2;
sbit sw4=P1^3;
sbit led1=P3^4;
sbit led2=P3^5;
sbit led3=P3^6;
sbit led4=P3^7;

int main()
{
P1=0xFF;
while(1)
{
if(sw1==0)
{
led1=0;
}
else
{

36
led1=1;
}
if(sw2==0)
{
led2=0;
}
else
{
led2=1;
}
if(sw3==0)
{
led3=0;
}
else
{
led3=1;
}
if(sw4==0)
{
led4=0;
}
else
{
led4=1;
}
}
return 0;
}

The 8051 MICROCONTROLLER successfully blinks led on if pushbutton is high, led


off if pushbutton low, Here by following the instructions and uploading the provided code.
The fundamentals of utilizing an 8051 microcontroller to control hardware components
are clarified through this experiment.

37
5. KEYPAD AND LCD INTERFACE

The objective is to create the simplest experiment by using 4x4 keypad and lcd interface
8051 MICROCONTROLLER. Basically, you connect a few things easily, write some code,
and upload it to the 8051 MICROCONTROLLER. With that if you

CIRCUIT CONNECTION

GND GND
+5V VCC
CON CON
P2.7 RS
P2.6 R/W
P2.5 EN
P0.0 D0
P0.1 D1
P0.2 D2
P0.3 D3
P0.4 D4
P0.5 D5
P0.6 D6
P0.7 D7
L+ LCD(light +)
L- LCD(light-)
P1.0 R1 (KEYPAD R=ROW,C=COLUM)
P1.1 R2
P1.2 R3
P1.3 R4
P1.4 C1
P1.5 C2
P1.6 C3
P1.7 C4

38
PROCEDURE:

• Set up the circuit as described in the “Circuit Connection” section.


• Connect the 8051 microcontroller to computer using a USB cable.
• Open the KEIL UVISION4 software on your computer.
• Write the code for 4x4 keypad and LCD interface 8051 microcontroller.
• Create a hex file as a instructions given.
• Open the NUVUTON ISP-ICP utility software on your computer.
• Click the upload button and upload the hex file which is created by the KEIL
software.
• Verify and upload the code to the 8051 MICROCONTROLLER.
• When the input is given with the help of 4*4 keypad the LCD screen displays the
output.

PROGRAM
#include <stdio.h> //Define I/O Functions
#include <reg52.h> //Define 8051 Registers
#define DATA P0 //Define DATA to Port1
#define SCAN P1
void lcd_init(void); //LCD Initialization
void lcd_cmd(unsigned char); //LCD Command Function
void lcd_display(unsigned char); //LCD Display Function
void Key_Scan(void); //KeyScan Function

39
void DelayMs(int); //DelayMs Function
sbit RS = P2^7; //Register Select
sbit RW = P2^6; //LCD Read/Write
sbit lcd_e = P2^5; //LCD Enable
unsigned char R,C,ch;
unsigned int i=0;
unsigned char Key[4][4] = {'*','7','4','1',
'0','8','5','2',
'#','9','6','3',
'D','C','B','A',
};
code unsigned char msg[] = (" 4X4 KEYPAD TEST");//Display the Message
code unsigned char msg1[] = ("KEY PRESSED - _");

//-------------------------------
// Main Program
//-------------------------------
void main()
{
lcd_init();
while(1)
{
Key_Scan();
ch = Key[C][R]; //Assign Key value to ch;
//SBUF=ch; //[C][R] denotes Column
DelayMs(35); //and Row Value of Keypad
lcd_cmd(0xCE);
lcd_display(ch);
DelayMs(35);
}
}

//-------------------------------
// Key Scan Function
//-------------------------------
void Key_Scan(void)
{
unsigned int i = 0;

40
//Scanning for Row Value
SCAN = 0x0F; //Initialize Port2 to 0Fh
while(SCAN == 0x0F);
if(SCAN == 0x0E) //Checking for Row0
R = 0;
else if(SCAN == 0x0D) //Checking for Row1
R = 1;
else if(SCAN == 0x0B) //Checking for Row2
R = 2;
else if(SCAN == 0x07) //Checking for Row3
R = 3;
//Scanning for Column Value
SCAN = 0xF0; //Initialize Port2 to F0h
while(SCAN == 0xF0);
if(SCAN == 0xE0) //Checking for Column0
C = 0;
else if(SCAN == 0xD0) //Checking for Column1
C = 1;
else if(SCAN == 0xB0) //Checking for Column2
C = 2;
else if(SCAN == 0x70) //Checking for Column3
C = 3;
DelayMs(50);
}

//-------------------------------
// LCD command Function
//-------------------------------
void lcd_cmd(unsigned char cmnd)
{
DATA = cmnd;
RS = 0; //RS:Register Select
RW = 0; //RW:Read/Write
lcd_e = 1; //LCD Enable
DelayMs(35);
lcd_e = 0;
}

41
//-------------------------------
// LCD Data Function
//-------------------------------
void lcd_display(unsigned char dat)
{
DATA = dat;
RS = 1; //RS:Register Select
RW = 0; //RW:Read/Write
lcd_e = 1;
DelayMs(35);
lcd_e = 0;
}

//-------------------------------
// LCD Initialization
//-------------------------------

void lcd_init(void)
{
unsigned char i;
lcd_cmd(0x38); //2x16 Character 5x7 dot
DelayMs(15); //matrix LCD,8-bit format
lcd_cmd(0x0c); //Display On, cursor off
DelayMs(15);
lcd_cmd(0x06); //Shift Cursor to right
DelayMs(15);
lcd_cmd(0x01); //Clear display screen
DelayMs(15);

//------------------------------------
// First Line Message Display
//------------------------------------
lcd_cmd(0x80); //First Line Initialization
DelayMs(35);
i=0;
while(msg[i]!='\0')
{
lcd_display(msg[i]);

42
i++;
}
DelayMs(50);

//------------------------------------
// Second Line Message Display
//------------------------------------

lcd_cmd(0xc0); //Second Line Initialization


DelayMs(35);
i=0;
while(msg1[i]!='\0')
{
lcd_display(msg1[i]);
i++;
}
DelayMs(50);
}

//--------------------------
// DelayMs Function
//--------------------------

void DelayMs(int k)
{
unsigned int a;
for(a=0;a<=k;a++);
}

The 8051 Microcontroller displays the output that that entered using keypad, here
by following the instructions and uploading the provided code. The fundamentals of
utilizing an 8051 MICROCONTROLLER to control hardware components are clarified
through this experiment.

43
6. ULTRASONIC SENSOR INTERFACE WITH MICROCONTROLLER

The objective is to measure the distance of the object we used ultrasonic sensor. Basically,
you connect a few things easily, write some code, and upload it to the 8051
MICROCONTROLLER.

CIRCUIT CONNECTION

From above the figure explained that how to make connections among 8051
MICROCONTROLLER and ultrasonic sensor through wire connections as a corresponding
pin described in table.

8051 pins LCD pins and ultrasonic pins


GND GND
+5V VCC
CON CON
P2.0 RS
P2.1 R/W
P2.2 EN
P1.0 D0
P1.1 D1
P1.2 D2
P1.3 D3
P1.4 D4
P1.5 D5
P1.6 D6
P1.7 D7
L+ LCD(light +)
L- LCD(light-)
P2.7 echo
P2.6 trig
gnd gnd(ultrasonic)
+5v Vcc(ultrasonic)

44
PROCEDURE

• Set up the circuit as described in the “Circuit Connection” section.


• Connect the 8051 MICROCONTROLLER to your computer using a USB cable.
• Open the KEIL UVISION4 software on your computer.
• Write the code for measuring distance using ultrasonic sensor.
• Create a hex file as a instructions given.
• Open the NUVUTON ISP-ICP utility software on your computer.
• Click the upload button and upload the hex file which is created by the KEIL
software.
• Verify and upload the code to the .
• To measure the distance of the object with the help of ultrasonic sensor, move
the object from near too far from the sensor and check it in serial monitor.

PROGRAM

#include<reg52.h>
#include <stdio.h>
#include <LCD_8_bit.h>
#include <math.h>

45
#define sound_velocity 34300 /* sound velocity in cm per second */
#define period_in_us pow(10,-6)
#define Clock_period 1.085*period_in_us /* period for clock cycle of 8051*/

sbit Trigger_pin=P2^6; /* Trigger pin */


sbit Echo_pin=P2^7; /* Echo pin */

void Delay_us()
{
TL0=0xF5;
TH0=0xFF;
TR0=1;
while (TF0==0);
TR0=0;
TF0=0;
}

void init_timer(){
TMOD=0x01;
/*initialize Timer*/
TF0=0;
TR0 = 0;
}

void send_trigger_pulse(){
Trigger_pin= 1; /* pull trigger pin HIGH */
Delay_us(); /* provide 10uS Delay*/
Trigger_pin = 0; /* pull trigger pin LOW*/
}

void main()
{
float distance_measurement, value;
unsigned char distance_in_cm[10];
LCD_Init(); /*

46
Initialize 16x2 LCD */
LCD_String_xy(1,1,"Distance");
init_timer(); /*
Initialize Timer*/

while(1)
{
send_trigger_pulse(); /* send trigger pulse of 10us */
while(!Echo_pin); /* Waiting for Echo */
TR0 = 1; /* Timer Starts */
while(Echo_pin && !TF0); /* Waiting for Echo goes LOW */
TR0 = 0; /* Stop the timer */
/* calculate distance using timer */
value = Clock_period * sound_velocity;
distance_measurement = (TL0|(TH0<<8));
/* read timer register for time count */
distance_measurement = (distance_measurement*value)/2.0; /* find
distance(in cm) */
sprintf(distance_in_cm, "%.2f", distance_measurement);
LCD_String_xy(2,1,distance_in_cm);
/* show distance on 16x2 LCD */
LCD_String(" cm ");
delay(100);
}
}

The distance measured by sensor in inches and cm and also monitored using serial
monitor of Arduino IDE. Here by following the instructions and uploading the provided
code. The fundamentals of utilizing an 8051 microcontroller to control hardware
components are clarified through this experiment.

47
7. DC MOTOR INTERFACE WITH 8051 MICROCONTROLLER

The objective is to control the speed of the DC motor by simply controlling the input
voltage to the motor and the most common method of doing that is by using PWM signal.
Basically, you connect a few things easily, write some code, and upload it to the 8051
MICROCONTROLLER.

CIRCUIT CONNECTION

From above the figure explained that how to make connections among 8051
MICROCONTROLLER, and DC motor through wire connections as a corresponding pin
described in table.

8051 pin Motor pins


P2.0 SWITCH 1
P2.1 SWITCH 2
P3.0 CLOCK(MOTOR PIN)
P3.1 ANTICLOCK(MOTOR PIN)

PROCEDURE
• Set up the circuit as described in the “Circuit Connection” section.
• Connect the 8051 MICROCONTROLLER to your computer using a USB cable.
• Open the KEIL UVISION4 software on your computer.

48
• Write the code for Dc motor and motor driver interface with 8051
MICROCONTROLLER.
• Create a hex file as a instructions given.
• Open the NUVUTON ISP-ICP utility software on your computer.
• Click the upload button and upload the hex file which is created by the KEIL
software.
• Verify and upload the code to the 8051 MICROCONTROLLER.

PROGRAM

#include<reg51.h>
sbit switch1=P2^0;
sbit switch2=P2^1;
sbit clk=P3^0;
sbit anticlk=P3^1;

void main()

switch1=switch2=1; //making P2.0 and P2.1 as inputs


switch1=switch2=0;
clk=anticlk=0;
while(1)
{ if((switch1))
clk=1;
else if((switch2))
anticlk=1;
else
P3=0x00;
}
}

The 8051 MICROCONTROLLER successfully control the speed of the DC motor as


programed. Here by following the instructions and uploading the provided code. The
fundamentals of utilizing an 8051 microcontroller to control hardware components are
clarified through this experiment

49
8. SERVO MOTOR INTERFACE

The objective is to control the servo motor in two ways Knob (Controlling a servo
position using a potentiometer (variable resistor)) and Sweep (the shaft of a RC servo
motor back and forth across 180 degrees).is by using PWM signal. Basically, you connect
a few things easily, write some code, and upload it to the 8051 MICROCONTROLLER.

CIRCUIT CONNECTION

From above the figure explained that how to make connections among 8051
microcontroller and servo motor through wire connections as a corresponding pin
described in table.

8051 PINS SERVO PINS


2.0 PWM
+5V +5V
GND GND

PROCEDURE
• Set up the circuit as described in the “Circuit Connection” section.
• Connect the 8051 MICROCONTROLLER to your computer using a USB cable.
• Open the KEIL UVISION4 software on your computer.
• Write the code for Servo motor interface with 8051.
• Create a hex file as a instructions given.
• Open the NUVUTON ISP-ICP utility software on your computer.
• Click the upload button and upload the hex file which is created by the KEIL
software.
• Verify and upload the code to the 8051 MICROCONTROLLER.

50
PROGRAM
#include <reg52.h>
#include <intrins.h>
/* Define value to be loaded in timer for PWM period of 20 milli second */
#define PWM_Period 0xB7FE
sbit Servo_Motor_Pin = P2^0;
unsigned int ON_Period, OFF_Period, DutyCycle;
/* Function to provide delay of 1ms at 11.0592 MHz */
void delay(unsigned int count)
{
int i,j;
for(i=0; i<count; i++)
for(j=0; j<112; j++);
}

void Timer_init()
{
TMOD = 0x01; /* Timer0 mode1 */
TH0 = (PWM_Period >> 8); /* 20ms timer value */
TL0 = PWM_Period;
TR0 = 1; /* Start timer0 */
}

/* Timer0 interrupt service routine (ISR) */


void Timer0_ISR() interrupt 1
{
Servo_Motor_Pin = !Servo_Motor_Pin;
if(Servo_Motor_Pin)
{
TH0 = (ON_Period >> 8);
TL0 = ON_Period;
}
else
{
TH0 = (OFF_Period >> 8);
TL0 = OFF_Period;

51
}
}

/* Calculate ON & OFF period from duty cycle */


void Set_DutyCycle_To(float duty_cycle)
{
float period = 65535 - PWM_Period;
ON_Period = ((period/100.0) * duty_cycle);
OFF_Period = (period - ON_Period);
ON_Period = 65535 - ON_Period;
OFF_Period = 65535 - OFF_Period;
}

int main()
{
EA = 1; /* Enable global interrupt */
ET0 = 1; /* Enable timer0 interrupt */
Timer_init();
while(1)
{
Set_DutyCycle_To(2.7);/* 0.54ms(2.7%) of 20ms(100%) period */
delay(1000);
Set_DutyCycle_To(7); /* 1.4ms(7%) of 20ms(100%) period */
delay(1000);
Set_DutyCycle_To(12); /* 2.4ms(12%) of 20ms(100%) period */
delay(1000);
}
}

The servo motor is controlled successfully with the code written to 8051. Here by
following the instructions and uploading the provided code. The fundamentals of utilizing
an 8051 MICROCONTROLLER to control hardware components are clarified through this
experiment.

52
9. STEPPER MOTOR INTERFACE

The objective is to control the speed of the stepper motor by simply controlling the
input voltage to the motor and the most common method of doing that is by using PWM
signal. Basically, you connect a few things easily, write some code, and upload it to the
8051 MICROCONTROLLER.

CIRCUIT CONNECTION

From below the figure explained that how to make connections among 8051
microcontroller and stepper motor through wire connections as a corresponding pin
described in table.

8051 PINS ULN 2803 PINS


P2.0 IN5
P2.1 IN6
P2.2 IN7
P2.3 IN8
GND GND
+5V VDD

PROCEDURE
• Set up the circuit as described in the “Circuit Connection” section.
• Connect the 8051 MICROCONTROLLER to your computer using a USB cable.
• Open the KEIL UVISION4software on your computer.
• Write the code for Stepper motor interface with 8051.
• Create a hex file as a instructions given.

53
• Open the NUVUTON ISP-ICP utility software on your computer.
• Click the upload button and upload the hex file which is created by the KEIL
software.
• Verify and upload the code to the 8051 MICROCONTROLLER.

PROGRAM
#include<reg51.h>
void msdelay(unsigned int time)
{
unsigned i,j ;
for(i=0;i<time;i++)
for(j=0;j<1275;j++);
}

void main()
{
while(1)
{
P2 = 0x03; //0011 P2_0=1,P2_1=1,P2_2=0,P2_3=0
msdelay(1);
P2 = 0x06; //0110
msdelay(1);
P2 = 0x0C; //1100
msdelay(1);
P2 = 0x09; //1001
msdelay(1);
}
}

The 8051 MICROCONTROLLER successfully control the speed of the DC motor as


programed. Here by following the instructions and uploading the provided code. The
fundamentals of utilizing an 8051 MICROCONTROLLER to control hardware components
are clarified through this experiment

54
10. TRAFFIC LIGHT CONTROL WITH 8051MICROCONTROLLER

The objective is to control the traffic lights with the 8051 microcontroller. The
connections among 8051 microcontroller, Bluetooth module interface through wire
connections as a corresponding pin are described in table.

8051 PINS Connection Description 8051 PINS Connection Description


GND GND P2.2 LED 3
+5V VCC P2.3 LED 4
CON CON P2.4 LED 5
P1.2 RS P2.5 LED 6
GND R/W P3.0 LED 7
P1.1 ENABLE SWITCH P3.1 LED 8
P2.0 LED 1 P3.2 LED 9
P2.1 LED 2

PROCEDURE
• Set up the circuit as described in the “Circuit Connection” section.
• Connect the 8051 microcontroller to your computer using a USB cable.
• Open the KEIL UVISION4 software on your computer.
• Write the code for light controls with 8051 microcontroller.
• Create a hex file as per instructions.
• Open the NUVUTON ISP-ICP utility software on your computer.

55
• Click the upload button and upload the hex file which is created by the KEIL
software.
• Verify and upload the code to the 8051 microcontroller.

PROGRAM
include<reg51.h>
//signal 1
sbit tl1r = P2^0; // red
sbit tl1o = P2^1; // orange
sbit tl1g = P2^2; // green
//signal 2
sbit tl2r = P2^3; // red
sbit tl2o = P2^4; // orange
sbit tl2g = P2^5; // green
//signal 3
sbit tl3r = P3^0; // red
sbit tl3o = P3^1; // orange
sbit tl3g = P3^2; // green

void delay(int t);


void trafficlight(void);
void main() // main program
{ P2=0x00; // turned off the lights
P3=0x00; // turned off the lights
while(1)
{ trafficlight( ); }
}
void delay(unsigned long int t) // delay routine
{ while(t>0)
{ unsigned long int i;
for(i=1;i<10*1275;i++);
t--; }
}
void trafficlight(void) // traffic light system program
{
P2= 0x11; // traffic signal control data
P3= 0x04;
/*
tl1r=1; // signal 1
tl1o=0;
tl1g=0;
tl2r=0; // signal 2
tl2o=1;
tl2g=0;

56
tl3r=0; // signal 3
tl3o=0;
tl3g=1;
*/
delay(100); // delay
P2= 0x0c; // traffic signal control data
P3= 0x02;
/*
tl1r=0; // signal 1
tl1o=0;
tl1g=1;
tl2r=1; // signal 2
tl2o=0;
tl2g=0;
tl3r=0; // signal 3
tl3o=1;
tl3g=0;
*/
delay(100); // delay
P2= 0x22; // traffic signal control data
P3= 0x01;
/*
tl1r=0; // signal 1
tl1o=1;
tl1g=0;
tl2r=0; // signal 2
tl2o=0;
tl2g=1;
tl3r=1; // signal 3
tl3o=0;
tl3g=0;
*/
delay(100); // delay
}

Traffic light control successfully carried out with the 8051 microcontroller and by
uploading the assembly code. The fundamentals of utilizing an 8051 microcontroller to
control hardware components are clarified through this experiment.

57
11. BLUETOOTH MODULE INTERFACE WITH 8051

The objective is to connect Bluetooth module and control the components with
the help of 8051 microcontroller.

CIRCUIT CONNECTION

The connections among 8051 microcontroller, Bluetooth module interface


through wire connections as a corresponding pin are described in table.

8051 PINS LCD AND ADC PINS


GND GND
+5V VCC
CON CON
P1.2 RS
GND R/W
P1.1 EN
P0.0 D0
P0.1 D1
P0.2 D2
P0.3 D3
P0.4 D4
P0.5 D5
P0.6 D6
P0.7 D7
L+ LCD(light +)
L- LCD(light-)
P3.0 TX(BT)
P3.1 RX(BT)
P2.0 D0(ADC)
P2.1 D1(ADC)
P2.2 D2(ADC)
P2.3 D3(ADC)
P2.4 D4(ADC)
P2.5 D5(ADC)
P2.6 D6(ADC)
P2.7 D7(ADC)

58
PROCEDURE
• Set up the circuit as described in the “Circuit Connection” section.
• Connect the 8051 MICROCONTROLLER to your computer using a USB cable.
• Open the KEIL UVISION4 software on your computer.
• Write the code for Bluetooth module interface with 8051 MICROCONTROLLER.
• Create a hex file as a instructions given.
• Open the NUVUTON ISP-ICP utility software on your computer.
• Click the upload button and upload the hex file which is created by the KEIL
software.
• Verify and upload the code to the 8051 MICROCONTROLLER.

59
PROGRAM

#include <stdio.h> //Define I/O Functions


#include <reg51.h> //Define 8051 Registers
#include <math.h>
int convertBinaryToDecimal(long n);
#define DATA P0
char lcd_buf[30];//Define DATA to Port0
unsigned int adc_data;
void serial_send(unsigned char);
void tx_string(char *);
void lcd_init(void); //LCD Initialization
void lcd_cmd(unsigned char); //LCD Command Function
void lcd_display(unsigned char); //LCD Display Function
void LCD_DisplayNumber(unsigned int);
void DelayMs(int); //DelayMs Function
sbit RS = P1^2; //LCD Register Select
sbit lcd_e = P1^1;
unsigned int i;
code unsigned char msg[] = ("Bluetooth-Test "); //Display the Message
code unsigned char msg1[] = ("Raana Demo"); //in LCD
code unsigned char msg2[] = ("ADC:");
//-------------------------------
// Main Program
//-------------------------------
void main()
{
lcd_init();
DelayMs(20);
TMOD = 0x20; //Serial port enable
SCON = 0x50;
TH1 = 0xFD;
TR1 = 1;
lcd_cmd(0x01);
lcd_e=0;
lcd_cmd(0x80);

60
P2=0xff; // Declare P2 as input port.
while(1)
{
//------------------------------------
// First Line Message Display
//------------------------------------
lcd_cmd(0x80); //First Line Initialization
DelayMs(15);
i=0;
while(msg2[i]!='\0')
{
lcd_display(msg[i]);
i++;
}
DelayMs(20);
lcd_cmd(0xC0); //First Line Initialization
sprintf(lcd_buf,"Temp-%00004d ",adc_data);
LCD_DisplayNumber(P2);
tx_string(lcd_buf);
DelayMs(100);
}
}
void serial_send(unsigned char dat){
SBUF = dat;
while(TI==0);
TI = 0;
}
void tx_string(char *str)
{
while(*str)
serial_send(*str++);
for(i=0;i<1000;i++);
}
//-------------------------------
// LCD command Function
//-------------------------------

61
void lcd_cmd(unsigned char cmnd)
{
DATA = cmnd;
RS = 0; //RS:Register Select
//RW:Read/Write
lcd_e = 1; //LCD Enable
DelayMs(15);
lcd_e = 0;
}
//-------------------------------
// LCD Data Function
//-------------------------------
void lcd_display(unsigned char dat)
{
DATA = dat;
RS = 1; //RS:Register Select
//RW:Read/Write
lcd_e = 1;
DelayMs(15);
lcd_e = 0;
}
//-------------------------------
// LCD Initialization
//-------------------------------
void lcd_init(void)
{
unsigned char i;
lcd_cmd(0x38); //2x16 Character 5x7 dot
DelayMs(15); //matrix LCD,8-bit format
lcd_cmd(0x0c); //Display On, cursor off
DelayMs(15);
lcd_cmd(0x06); //Shift Cursor to right
DelayMs(15);
lcd_cmd(0x01); //Clear display screen
DelayMs(15);
//------------------------------------

62
// First Line Message Display
//------------------------------------
lcd_cmd(0x80); //First Line Initialization
DelayMs(15);
i=0;
while(msg[i]!='\0')
{
lcd_display(msg[i]);
i++;
}
DelayMs(20);
//------------------------------------
// Second Line Message Display
//------------------------------------
lcd_cmd(0xc0); //Second Line Initialization
DelayMs(15);
i=0;
while(msg1[i]!='\0')
{
lcd_display(msg1[i]);
i++;
}
DelayMs(30);
}
//lcd_DisplayNumber
//description :This function is used to display a 5-digit integer(0-65535).
// ex: if the number is 12345 then 12345 is displayed.
// if the number is 123 then 00123 is displayed.
void LCD_DisplayNumber(unsigned int num)
{
lcd_display((num/10000)+0x30);
num=num%10000;
lcd_display((num/1000)+0x30);
num=num%1000;
lcd_display((num/100)+0x30);
num=num%100;

63
lcd_display((num/10)+0x30);
lcd_display((num%10)+0x30);
adc_data=P2;
adc_data=(adc_data/4);
}
//--------------------------
// DelayMs Function
//--------------------------
void DelayMs(int k)
{
unsigned int a,b;
for(a=0;a<=k;a++)
for(b=0;b<1275;b++);
}

Bluetooth module gets successfully connected with the 8051, and also help to
control the components. Here by following the instructions and uploading the provided
code. The fundamentals of utilizing an 8051 microcontroller to control hardware
components are clarified through this experiment.

64
12. Creating Linear Control System Models using Transfer Function &
State-Space Representations

Objective:
To develop appropriate mathematical models of the system to be controlled in MATLAB
for analysis.

Software: MATLAB

Theory:
Dynamic systems are systems that change or evolve in time according to a fixed rule. For
many physical systems, this rule can be stated as a set of first-order differential equations

……………. (1)

In the equation (1), x(t) is the state vector, a set of variables representing the
configuration of the system at time t. For instance, in a simple mechanical mass-spring-
damper system, the two state variables could be the position and velocity of the mass. u(t)
is the vector of external inputs to the system at time t, and f is a (possibly nonlinear)
function producing the time derivative (rate of change) of the state vector, dx/dt, for a
particular instant of time.

For continuous linear time-invariant (LTI) systems, the standard state-space


representation is given as,
………….. (2)
………….. (3)
Where,
is the vector of state variables (nx1)
is time derivative of the state vector (nx1)
is input or control vector (px1)
is output vector (qx1)
A is system matrix (nxn)
B is input matrix (nxp)
C is output matrix (qxn)
D is feedforward matrix (qxp)

65
The output equation y is necessary because often there are state variables which are not
directly observed or are otherwise not of interest. The output matrix, C, is used to specify
which state variables (or combinations thereof) are available for use by the controller.
Also, it is often the case that the outputs do not directly depend on the inputs (only
through the state variables), in which case D is the zero matrix.

The state-space representation, also referred to as the time-domain representation, can


easily handle multi-input/multi-output (MIMO) systems, systems with non-zero initial
conditions, and nonlinear systems. Consequently, the state-space representation is used
extensively in "modern" control theory.

Methodology:
 The first step in the control design process is to develop appropriate
mathematical models of the system to be controlled.
 These models may be derived either from physical laws or experimental data.
 The state-space and transfer function representations of dynamic systems.
 Basic approaches to modeling mechanical and show how to generate these
models in MATLAB for further analysis.
 Key MATLAB commands: ss, tf

Mechanical Systems
Newton's laws of motion form the basis for analyzing mechanical systems. Newton’s
second law, states that the sum of the forces acting on a body equals the product of its
mass and acceleration. Newton's third law, for our purposes, states that if two bodies are
in contact, then they experience the same magnitude contact force, just acting in opposite
directions.

………………. (4).

When applying this equation 4, it is best to construct a free-body diagram (FBD) of the
system showing all of the applied forces.

Mass-Spring-Damper System

66
Fig. 12.1 Free Body Diagram

The free-body diagram for the system is shown in figure 1. The spring force is
proportional to the displacement of the mass, , and the viscous damping force is
proportional to the velocity of the mass, . Both forces oppose the motion of the mass
and are, therefore, shown in the negative -direction. Note also that corresponds to
the position of the mass when the spring is unstretched.

Now we proceed by summing the forces and applying Newton’s second law, Equation (4),
in each direction. In this case, there are no forces acting in the -direction; however, in
the -direction we have:

…….. (5)

This equation, known as the governing equation, completely characterizes the dynamic
state of the system. Later, we will see how to use this to calculate the response of the
system to any external input, , as well as to analyze system properties such as stability
and performance.
To determine the state-space representation of the mass-spring-damper system, we must
reduce the second-order governing equation to a set of two first-order differential
equations. To this end, we choose the position and velocity as our state variables.

………….. (6)
The position variable captures the potential energy stored in the spring, while the velocity
variable captures the kinetic energy stored by the mass. The damper only dissipates
energy, it doesn't store energy. Often when choosing state variables it is helpful to
consider what variables capture the energy stored in the system.

The state equation in this case is:

………….. (7)

67
If, for instance, we are interested in controlling the position of the mass, then the output
equation is:

………….. (8)

Entering State-Space Models into MATLAB

The equations derived are entered into an m-file for MATLAB and the following numerical
values are assigned to each of the variables.

m mass 1.0 kg
k spring constant 1.0 N/m
b damping constant 0.2 Ns/m
F input force 1.0 N

Create a new m-file and enter the following commands.

m = 1;
k = 1;
b = 0.2;
F = 1;
A = [0 1; -k/m -b/m];
B = [0 1/m]';
C = [1 0];
D = [0];
sys = ss(A,B,C,D)

sys =
A=
x1 x2
x1 0 1
x2 -1 -0.2

B=
u1
x1 0
x2 1

C=

68
x1 x2
y1 1 0

D=
u1
y1 0

Continuous-time state-space model.


The Laplace transform for the system assuming zero initial conditions is

………….. (9)

and, therefore, the transfer function from force input to displacement output is

………….. (10)

Entering Transfer Function Models into MATLAB

To create the transfer function model derived above within MATLAB enter the following
commands into the m-file in which the system parameters are defined.

s = tf('s');
sys = 1/(m*s^2+b*s+k)

sys =
1
---------------
s^2 + 0.2 s + 1

Continuous-time transfer function.

Note that the symbolic s variable used here to define the transfer function model. It is
recommended to use this method most of the time; however, in some circumstances, for
instance in older versions of MATLAB or when interfacing with SIMULINK, it may need to
define the transfer function model using the numerator and denominator polynomial
coefficients directly. In these cases, the following commands are used:

69
num = [1];
den = [m b k];
sys = tf(num,den)

sys =
1
---------------
s^2 + 0.2 s + 1

Continuous-time transfer function.

Results

The Transfer Function and State-Space models of spring-mass-damper dynamic control


system was modelled and analyzed in MATLAB software.

70
13. Visualization of System Behavior in Time Domain and Frequency
Domain

Objective:
To plot the time and frequency responses of SISO and MIMO linear systems.

Software:

Matlab

Simulink

1. Time Responses:

Create a linear system with third-order transfer function.

Get
sys = tf([8 18 32],[1 6 14 24])
sys =
8 s^2 + 18 s + 32
-----------------------
s^3 + 6 s^2 + 14 s + 24
Continuous-time transfer function.

To plot the step and impulse responses of this system using


the step and impulse commands.

Get
subplot(2,1,1)
step(sys)
subplot(2,1,2)
impulse(sys)

71
To simulate the response to an arbitrary signal, such as a sine wave, use
the lsim command. The input signal appears in gray and the system response in blue.

Get
clf
t = 0:0.01:4;
u = sin(10*t);
lsim(sys,u,t) % u, t define the input signal

The plotting commands can be used with continuous or discrete tf, ss, or zpk models. For
state-space models, also plot the unforced response from some given initial state:

Get

72
A = [-0.8 3.6 -2.1;-3 -1.2 4.8;3 -4.3 -1.1];
B = [0; -1.1; -0.2];
C = [1.2 0 0.6];
D = -0.6;
G = ss(A,B,C,D);
x0 = [-1;0;2]; % initial state
initial(G,x0)
grid

2. Frequency Responses

Frequency-domain analysis is key to understanding stability and performance properties


of control systems. Bode plots, Nyquist plots, and Nichols charts are three standard ways
to plot and analyze the frequency response of a linear system. The plots can be created
using the bode, nichols, and nyquist commands.

Creation of a linear system

Get
sys = tf([8 18 32],[1 6 14 24])
sys =
8 s^2 + 18 s + 32
-----------------------
s^3 + 6 s^2 + 14 s + 24
Continuous-time transfer function.

73
Create a Bode plot for this system:

Get
bode(sys)
grid

Create a Nyquist plot for this system.

Get
nyquist(sys)
grid

Create a Nichols chart for this system.

74
Get
nichols(sys)
grid

Pole/Zero Maps and Root Locus

The poles and zeros of a system contain valuable information about its dynamics,
stability, and limits of performance. For example, consider the feedback loop in the
following SISO control loop.

Here:

G= 2
−(2s+1)s +3s+2
For the gain value k = 0.7, you can plot the closed-loop poles and zeros using pzmap.

Get
s = tf('s');
G = -(2*s+1)/(s^2+3*s+2);
k = 0.7;
T = feedback(G*k,1);
pzmap(T)

75
grid, axis([-2 0 -1 1])

The closed-loop poles (marked by blue x's) lie in the left half-plane so the feedback loop
is stable for this choice of gain k. You can read the damping ratio of the closed-loop poles
from this chart (see labels on the radial lines). Here the damping ratio is about 0.7,
suggesting a well-damped closed-loop response as confirmed by:

Get
clf
step(T)

76
To further understand how the loop gain k affects closed-loop stability, you can plot the
locus of the closed-loop poles as a function of k.

Get
rlocus(G)
grid

Clicking where the locus intersects the y axis reveals that the closed-loop poles become
unstable for k = 1.51. So the loop gain should remain smaller than 1.5 for closed-loop
stability.

Response Characteristics

77
Right-clicking on response plots gives access to a variety of options and annotations. In
particular, the Characteristics menu lets you display standard metrics such as rise time
and settling time for step responses, or peak gain and stability margins for frequency
response plots.

Using the example from the previous section, plot the closed-loop step response:

Get
step(T)

Now, right-click on the plot to display the Peak Response and Settling Time
Characteristics, and click on the blue dots to read the corresponding overshoot and
settling time values:

Analyzing MIMO Systems

78
All commands mentioned so far fully support multi-input multi-output (MIMO) systems.
In the MIMO case, these commands produce arrays of plots. For example, consider the
following two-input, two-output system.

Get
sys = rss(3,2,2);
sys.A = [-0.5 -0.3 -0.2 ; 0 -1.3 -1.7; 0.4 1.7 -1.3];
The step response is a 2-by-2 array of plots where each column shows the step response
of a particular input channel.

Get
step(sys)

You can group all four responses on a single plot by right-clicking on the plot and
selecting the I/O Grouping -> All submenu.

79
The following additional plots are useful for analysing MIMO systems:

 Singular value plot (sigma), which shows the principal gains of the frequency
response

 Pole/zero map for each I/O pair (iopzplot)

For example, plot the peak gain of sys as a function of frequency:

Get
sigma(sys)
grid

Comparing Systems

You can plot multiple systems at once using any of the response plot commands. You can
assign a specific color, marker, or line style to each system for easy comparison. Using
the feedback example above, plot the closed-loop step response for three values of the
loop gain k in three different colors:

Get
k1 = 0.4;
T1 = feedback(G*k1,1);
k2 = 1;
T2 = feedback(G*k2,1);
step(T,'b',T1,'r',T2,'g')
legend('k = 0.7','k = 0.4','k = 1')

80
Modify Time or Frequency Axis Values

You can modify the time and frequency vectors for existing linear analysis plots.

For step and impulse plots, you can specify the time vector by right-clicking the plot area
and selecting Specify time.

In the Specify time dialog box, you can define time values and units using one of the
following methods.

 Generate automatically — Automatically generate the time vector based on the


system dynamics. This option is not supported for sparse systems.

 Define stop time — Specify the stop time, which creates a time vector starting at
time 0. The step size for the time vector is determined based on the system dynamics.

 Define vector — Specify the times to plot as a vector of monotonically increasing


evenly spaced time values.

For bode, Nyquist, Nichols, and Sigma plots, you can specify the frequency vector by
right-clicking the plot area and selecting Specify frequency.

81
In the Specify frequency dialog box, you can define frequency values and units using one
of the following methods.

 Generate automatically — automatically generate the frequency vector based on


the system dynamics. This method is not supported for sparse systems.

 Define range — specify the frequency range. This method is not supported for sparse
systems.

 Define vector — specify the frequencies to plot as a vector.

If your system is an FRD object, the plot interpolates the response between frequency
values. Changing the time and frequency units specifies the units for the input and does
not change the units in the plot.

Results

The time and different frequency response plots of linear control system are studied.

82

You might also like