Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

2019 DEPARTMENT OF

Pattern ELECTRICAL ENGINEERING

Fundamentals of

CLASS NOTES
Microcontroller
& its Application

UNIT-III
Mr. RAJAN PATEL
Asst. Prof.
Electrical Engg. Dept., GCOERC
Course Outcome: CO-3
Write programs in C language for microcontroller 8051.
Teaching Hours: 6 Insem Marks: 10
Content: -
8051 Programming in C, Data types in C. Ports of 8051, their use, and programming in C (Byte
Level and Bit-level). Time delay programming in C. Timers and counters in 8051, Timer modes 0, 1,
2 and its programming in C and counter-programming.

 Overview of C Language
 C is a structured programming language developed by Dennis Ritchie in 1973 at Bell
Laboratories.
 It is one of the most popular computer languages today because of its structure, high-level
abstraction, machine independent feature etc.
 C language was developed to write the UNIX operating system,
 Features of C language
 It is a robust language with rich set of built-in functions and operators that can be used to
write any complex program.
 The C compiler combines the capabilities of an assembly language with features of a high-
level language.
 Programs Written in C are efficient and fast. This is due to its variety of data type and
powerful operators.
 It is many time faster than BASIC.
 C is highly portable this means that programs once written can be run on another machines
with little or no modification.
 Another important feature of C program, is its ability to extend itself.
 A C program is basically a collection of functions that are supported by C library. We can
also create our own function and add it to C library.
 C language is the most widely used language in operating systems and embedded system
development today.
 Character set
 In C language characters are grouped into the following catagories,
 Letters (all alphabets a to z & A to Z).
 Digits (all digits 0 to 9).
 Special characters, (such as colon:, semicolon ;, period ., underscore _, ampersand &etc).
 White spaces.
 What are Keywords in C?
 Keywords are preserved words that have special meaning in C language.
 The meaning of C language keywords has already been described to the C compiler.
 These meaning cannot be changed.
 Thus, keywords cannot be used as variable names.
 There are total 32 keywords in C language.

Prepared By: - Mr. R. V. Patel 2


Auto double int struct char float short unsigned
Break else long switch continue for signed volatile
Case enum register typedef default goto sizeof void
const extern return union do if static while
 What are Identifiers?
 In C language identifiers are the names given to variables, constants, functions and user-
define data.
 These identifier are defined against a set of rules.
 Rules for an Identifier
 An Identifier can only have alphanumeric characters (a-z, A-Z, 0-9) and underscore (_).
 The first character of an identifier can only contain alphabet (a-z, A-Z) or underscore (_).
 Identifiers are also case sensitive in C. For example name and Name are two different
identifiers in C.
 Keywords are not allowed to be used as Identifiers.
 No special characters, such as semicolon, period, whitespaces, slash or comma are permitted
to be used in or as Identifier.
 Variables in C Language
 When we want to store any information (data) on our computer/laptop, we store it in the
computer's memory space.
 Instead of remembering the complex address of that memory space where we have stored
our data, our operating system provides us with an option to create folders, name them, so
that it becomes easier for us to find it and access it.
 Similarly, in C language, when we want to use some data value in our program, we can store
it in a memory space and name the memory space so that it becomes easier to access it.
 The naming of an address is known as variable.
 Data type of Variable
 A variable in C language must be given a type, which defines what type of data the variable
will hold.
 It can be:
 char: Can hold/store a character in it.
 int: Used to hold an integer.
 float: Used to hold a float value.
 double: Used to hold a double value.
 void
 Rules to name a Variable
1) Variable name must not start with a digit.
2) Variable name can consist of alphabets, digits and special symbols like underscore _.
3) Blank or spaces are not allowed in variable name.
4) Keywords are not allowed as variable name.
5) Upper and lower case names are treated as different, as C is case-sensitive, so it is suggested
to keep the variable names in lower case.
 Declaring, Defining and initializing a variable

Prepared By: - Mr. R. V. Patel 3


 Declaration of variables must be done before they are used in the program. Declaration does
the following things.
1) It tells the compiler what the variable name is.
2) It specifies what type of data the variable will hold.
3) Until the variable is defined the compiler doesn't have to worry about allocating memory
space to the variable.
4) Declaration is more like informing the compiler that there exist a variable with following
data type which is used in the program.
5) A variable is declared using the extern keyword, outside the main( ) function.
 Ex:
int a;
float b, c;
 C – Data Types
 C data types are defined as the data storage format that a variable can store a data to perform
a specific operation.
 Data types are used to define a variable before to use in a program.
 Size of variable, constant and array are determined by data types.
 C language supports 2 different type of data types:
1) Primary data types:
 These are fundamental data types in C namely integer (int), floating point(float),
character(char) and void.
2) Derived data types:
 Derived data types are nothing but primary data types but a little twisted or grouped
together like array, stucture, union and pointer. These are discussed in details later.
 Primary Data Types
1) INTEGER DATA TYPE:
 Integer data type allows a variable to store numeric values.
 “int” keyword is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.
 It varies depend upon the processor in the CPU that we use. If we are using 16 bit
processor, 2 byte (16 bit) of memory will be allocated for int data type.
 Likewise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory
for 64 bit processor is allocated for int data type.
 If you want to use the integer value that crosses the above limit, you can go for “long int”
and “long long int” for which the limits are very high.
 Size and range of Integer type on 16-bit machine:
Type Size(bytes) Range
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
unsigned short int 1 0 to 255
long int or signed long int 4 -2,147,483,648 to 2,147,483,647

Prepared By: - Mr. R. V. Patel 4


unsigned long int 4 0 to 4,294,967,295
 Floating Point Data Type:
 Floating point data type consists of 2 types. They are,
1. float
2. double
1. Float:
 Float data type allows a variable to store decimal values.
 Storage size of float data type is 4. This also varies depend upon the processor in the CPU
as “int” data type.
 We can use up-to 6 digits after decimal using float data type.
 For example, 10.456789 can be stored in a variable using float data type.
2. Double:
 Double data type is also same as float data type which allows up-to 10 digits after decimal.
 The range for double data type is from 1E–37 to 1E+37.
 Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
Float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
 Character Data Type:
 Character data type allows a variable to store only one character.
 Storage size of character data type is 1. We can store only one character using character
data type.
 “char” keyword is used to refer character data type.
 For example, ‘A’ can be stored using char data type. You can’t store more than one
character using char data type.
 Size and range of Integer type on 16-bit machine

Type Size(bytes) Range


char or signed char 1 -128 to 127
unsigned char 1 0 to 255

 Void Type
 void type means no value.
 This is usually used to specify the type of functions which returns nothing.
 We will get acquainted to this data type as we start learning more advanced topics in C
language, like functions, pointers etc.
 Derived data types
 C supports three derived data types:
Data Types Description
Arrays Arrays are sequences of data items having homogeneous values. They have
adjacent memory locations to store values.

Prepared By: - Mr. R. V. Patel 5


References Function pointers allow referencing functions with a particular signature.
Pointers These are powerful C features which are used to access the memory and deal
with their addresses.

 Operators in C Language
 C language supports a rich set of built-in operators. An operator is a symbol that tells the
compiler to perform a certain mathematical or logical manipulation. Operators are used in
programs to manipulate data and variables.
 C operators can be classified into following types:
A. Arithmetic operators
B. Relational operators
C. Logical operators
D. Bitwise operators
E. Assignment operators
F. Conditional operators
G. Special operators
 Arithmetic operators
 C supports all the basic arithmetic operators. The following table shows all the basic
arithmetic operators.
Operator Description
+ Adds Two Operands
- Subtract Second Operands From First
* Multiply Two Operand
/ Divide Numerator By Denominator
% Remainder Of Division
++ Increment Operator - Increases Integer Value By One
-- Decrement Operator - Decreases Integer Value By One
 Relational Operators:
 Relational operators are used for comparison of two values. Let’s see them one by one:
 ‘==’ operator checks whether the two given operands are equal or not. If so, it returns true.
Otherwise it returns false.
o For example, 5==5 will return true.
 ‘!=’ operator checks whether the two given operands are equal or not. If not, it returns true.
Otherwise it returns false. It is the exact boolean complement of the ‘==’operator.
o For example, 5!=5 will return false.
 ‘>’ operator checks whether the first operand is greater than the second operand. If so, it
returns true. Otherwise it returns false.
o For example, 6>5 will return true.
 ‘<‘operator checks whether the first operand is lesser than the second operand. If so, it
returns true. Otherwise it returns false.
o For example, 6<5 will return false.

Prepared By: - Mr. R. V. Patel 6


 ‘>=’ operator checks whether the first operand is greater than or equal to the second
operand. If so, it returns true. Otherwise it returns false.
o For example, 5>=5 will return true.
 ‘<=’ operator checks whether the first operand is lesser than or equal to the second operand.
If so, it returns true. Otherwise it returns false.
o For example, 5<=5 will also return true.

Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand

 Logical Operators:
 They are used to combine two or more conditions/constraints or to complement the
evaluation of the original condition in consideration.
 They are described below:
 Logical AND: The ‘&&’ operator returns true when both the conditions in
consideration are satisfied. Otherwise it returns false.
o For example, a && b returns true when both a and b are true (i.e. non-zero).
 Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in
consideration is satisfied. Otherwise it returns false.
o For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course,
it returns true when both a and b are true.
 Logical NOT: The ‘!’ operator returns true the condition in consideration is not
satisfied. Otherwise it returns false.
o For example, !a returns true if a is false, i.e. when a=0.

Operator Description Example


&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false

 Bitwise operators
 Bitwise operators perform manipulations of data at bit level.
 These operators also perform shifting of bits from right to left.
 Bitwise operators are not applied to float or double (These are datatypes, we will learn
about them in the next tutorial).

Prepared By: - Mr. R. V. Patel 7


Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift

 The bitwise shift operator, shifts the bit value.


 The left operand specifies the value to be shifted and the right operand specifies the number
of positions that the bits in the value have to be shifted.
 Both operands have the same precedence.
 Assignment Operators
 Assignment operators supported by C language are as follows.
Operator Description Example
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result a+=b is same as
to left a=a+b
-= subtracts right operand from the left operand and assign the a-=b is same as
result to left operand a=a-b
*= mutiply left operand with the right operand and assign the a*=b is same as
result to left operand a=a*b
/= divides left operand with the right operand and assign the a/=b is same as
result to left operand a=a/b
%= calculate modulus using two operands and assign the result a%=b is same as
to left operand a=a%b

 Special operator
Operator Description Example
sizeof Returns the size of an variable size of(x) return size of the variable x
& Returns the address of an variable &x ; return address of the variable x
* Pointer to a variable *x ; will be pointer to a variable x

 Precedence of operators
 If more than one operators are involved in an expression, C language has a predefined rule
of priority for the operators.
 This rule of priority of operators is called operator precedence.
 In C, precedence of arithmetic operators ( *, %, /, +, -) is higher than relational operators(==,
!=, >, <, >=, <=) and precedence of relational operator is higher than logical operators(&&, ||
and !).
o Example of precedence
(1 > 2 + 3 && 4)

Prepared By: - Mr. R. V. Patel 8


This expression is equivalent to:
((1 > (2 + 3)) && 4)
i.e, (2 + 3) executes first resulting into 5 then, first part of the expression (1 > 5) executes
resulting into 0 (false) then, (0 && 4) executes resulting into 0 (false)
Output:- 0
 Control Statements
 It is often necessary to control the sequence of operations in a program. This can be done by
using control statements.
 Conditional statements are divided into three types:-
1) Conditional
2) Unconditional
3) Looping
1. Conditional Control Statements:
 A ‘c ’program is a set of statements which are normally executed sequentially in the order in
which they appear.
 This happens when no options (or) no repetitions of certain calculations are necessary.
 However in practice we have a number of situations where we may have to change the order
of execution of statements until certain specified conditions are met.
 This involves a kind of “decision making” to see whether a particular condition has occurred
(or0 not & then direct the computer to execute certain statements accordingly.
 ‘C’ language passes such decision making capabilities & supports the following statements
known as conditional (or) decision making statements.
A. if statements
B. switch statement
C. conditional operator statement
A. If statement
 The 'if' statement is a powerful decision making statement and is used to control the flow of
execution of statements.
 It is basically a two way decision statement and is used in conjunction with as expression .
 The if statement may be implemented in different forms depending on the complexity of
condition to be tested
I. simple if statement
II. if …else statement
III. nested if …else statement
IV. else if ladder
I. Simple if statement
 The general form of a simple if statement is,
if(expression)
{
statement inside;
}
statement outside;

Prepared By: - Mr. R. V. Patel 9


 If the expression returns true, then the statement-inside will be executed,
otherwise statement-inside is skipped and only the statement-outside is executed.
 Example:
#include <stdio.h>

void main( )
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
printf("x is greater than y");
}
}

Out Put:
x is greater than y
 Flowchart for simple-if:

II. If….else statement


The general form of if...else statement is
{
if( expression1 )
{
statement block1;
}
else
{

Prepared By: - Mr. R. V. Patel 10


statement block2;
}
 Flowchart for if….else:

 If the condition is true, statement1 is executed, followed by statement3.


 If the condition is false, statement2 is executed, followed by statement 3.
 It should be kept in mind that statement1 and statement2 can be single or compound
statement.
III. Nested if....else statement
 The general form of a nested if...else statement is,
if( expression )
{
if( expression1 )
{
statement block1;
}
else
{
statement block2;
}
}
else
{
statement block3;
}
 if expression is false then statement-block3 will be executed, otherwise the execution
continues and enters inside the first if to perform the check for the next if block, where
if expression 1 is true the statement-block1 is executed otherwise statement-block2 is
executed.
 Example:
#include <stdio.h>
void main( )
{
int a, b, c;
printf("Enter 3 numbers...");

Prepared By: - Mr. R. V. Patel 11


scanf("%d%d%d",&a, &b, &c);
if(a > b)
{
if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)
{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
}
}
 Flowchart for Nested if….else:

Prepared By: - Mr. R. V. Patel 12


2. Looping
 It is also called a Repetitive control structure.
 Sometimes we require a set of statements to be executed a number of times by changing the
value of one or more variables each time to obtain a different result.
 This type of program execution is called looping. C++ provides the following constructs.
I. while loop
II. do - while loop
III. for loop
I. While loop
 Syntax of while loop
while (condition)
{
statement(s);
}
 Flowchart for while loop:

 The flow diagram indicates that a condition is first evaluated.


 If the condition is true, the loop body is executed and the condition is re-evaluated.
 Hence, the loop body is executed repeatedly as long as the condition remains true.
 As soon as the condition becomes false, it comes out of the loop and goes to the statement
next to the ‘while’ loop.
 Example
# include <iostream.h>
void main ( )
{
int n, total = 0 ;
n=1;
while (n < = 10)
{
total + = n ;
n++;
}
cout << “sum of first ten natural number” << total :
}

Prepared By: - Mr. R. V. Patel 13


II. do-while loop
 Syntax of do-while loop
do
{
while (condition);
}
 The flow diagram indicates that after each execution of the loop body, the condition is true,
the loop body is executed again.
 If the condition evaluates to false, loop exit occurs and the next program statement is
executed.
 Note: The loop body is always executed at least once.
 One important difference between the while loop and the do-while loop is the relative
ordering of the conditional test and loop body execution.
 In the while loop, the loop repetition test is performed before each execution of the loop
body; the loop body is not executed at all if the initial test fails.
 In the do-while loop, the loop termination test is Performed after each execution of the loop
body; hence, the loop body is always executed at least once.
 Flowchart for do-while loop:

III. For loop


 It is a count controlled loop in the sense that the program knows in advance how
 many times the loop is to be executed.
 syntax of for loop
for (intialization; decision; increment/decrement)
{
statement(s);
}
 Flowchart for while loop:

Prepared By: - Mr. R. V. Patel 14


 The flow diagram indicates that in for loop three operations take place:
(i) Initialization of loop control variable
(ii) Testing of loop control variable
(iii) Update the loop control variable either by incrementing or decrementing.
 Operation (i) is used to initialize the value.
 Operation (ii) is used to test whether the condition is true or false.
 If the condition is true, the program executes the body of the loop and then the value of loop
control variable is updated.
 Again it checks the condition and so on. If the condition is true, it gets out of the loop.
 Ports of 8051
 Features of the four ports of 8051
 Each port has 8 pins. Thus the four ports jointly comprise 32 pins.
 All ports are bidirectional.
 They are constructed with a D type output latch. They have output drivers and input
buffers.
 We can modify their functions using software and hardware that they connect to.
 All the ports are configured as input ports on Reset.
 To configure ports as an input port 1 must be written to that port
 To configure it as an output port 0 must be written to it.
 Input/Output (I/O) pin

Prepared By: - Mr. R. V. Patel 15


 Figure above illustrates a simplified schematic of all circuits within the microcontroller
connected one of its pins.
 It refers to all the pins except those of the P0 port which do not have pull-up resistors built-
in.
 Output pin
 A logic zero (0) is applied to a bit of the P register.
 The output FE transistor is turned on, thus connecting the appropriate pin to ground.

 Input pin
 A logic one (1) is applied to a bit of the P register.
 The output FE transistor is turned off and the appropriate pin remains connected to the
power supply voltage over a pull-up resistance.

Prepared By: - Mr. R. V. Patel 16


 Port 0
 Features of Port 0
 Address is 80H.
 Construction: Port 0 has a D-type latch, unidirectional buffer, and 2 FETs at each pin. It does
not have an internal pull-up resistor. An external pull-up resistor is needed when Port 0 is
defined as an output port.
 Port 0 of the 8051 has two main functions: To be used as a simple input-output port and to
access external memory in conjunction with Port 2.

 Functions of Port 0
1. Simple I/O port:
 When we use Port 0 as an input port, the internal latch should know that it’s being used for
input, and thus, a digital 1 (FFH) is written at the port address of 80H.
 This turns off the transistors causing the pin to float in high impedance state connecting it to
the input buffer.
 We can read data from ‘Read Pin Data’/’Read Latch Bit.’
 When we use Port 0 as an output port, the latch programmed to 0 will turn on. Consequently,
the FET will connect to GND.
 We will require an external pull up resistor (10k Ohm) here to give a logic ‘1’ for using Port
0 as an output port.
2. Access external memory:
 When the 8051 wants to access external memory, the address for the memory generates due
to Port 0 and Port 2.
 We get the lower half of the address from Port 0 and the upper half from Port 2.
 This is done using ALE pulses, which help to latch the address to the external bus. Once done,
the Port 0 goes back to being an input port to read data from that memory.
 Read/Write Operation of PORT-0
 To write 0 to pin of the microcontroller:
 Write a '0' to pin: The D latch output is one, the mosfet M1 is turned ON output is grounded
as shown in the figure.

Prepared By: - Mr. R. V. Patel 17


 To write 1 to pin of the microcontroller:
 Write a '1' to pin: The D latch output is zero, the MOSFET M1 is turned OFF output is 1 as
shown in the figure.

 To read 0 from the pin of the microcontroller:


 Write one to pin.
 M1 turns OFF
 Read PIN latch is turned ON
 External zero grounds the pin.

Prepared By: - Mr. R. V. Patel 18


 To read 1 from the pin of the microcontroller:

 Port 1
 Features of Port 1:
 Address is 90H
 Construction: Port 1 has one D latch, two unidirectional buffers, 1 FET, and one internal pull-
up resistor at each pin.
 It has only one function – to act as an Input-Output port.
 The function of Port 1 – I/O port:
 When Port 1 is functioning in the capacity of an input port, a digital ‘1’ (FFH) is written to
the latch. At 90H.
 This turns off the transistor, and the pin floats in a high impedance state. Consequently, it
connects to the input buffer.
 When Port 1 is functioning in the capacity of an output port, the latch is given a ‘LOW’ signal
(00H).
 This turns the FER (Field Effect Transistor) o. The pull-up resistor is OFF, and the port is
used as an output port.
 Port 2
 Features of Port 2
 Address is 10H
 Construction: Port 2 has a D type latch, 1 FET, an internal pull-up resistor, two unidirectional
buffers, and a Control Logic block.
 Its main functions are kind of similar to those of Port 0. It can be used as an input-output
port. And can access external memory in conjunction with Port 0.
 Functions of Port 2
1. I/O port:
 Quite similar to Port 0. The only difference here is that in Port 2, we use one FET with an
internal pull-up resistor instead of the two FETs we saw in Port 0.
2. Memory Access:
 Port 2 is used in conjunction with Port 0 to generate the upper address of the external
memory location that needs to be accessed.

Prepared By: - Mr. R. V. Patel 19


 However, one key difference is that it doesn’t need to turn around and get a 1 in the latch
immediately for input as in Port 0. It can remain stable.
 Port 3
 Features of Port 3
 Address is B0H
 Construction: The third Port of 8051 has a D-type latch. In addition to that, it has three
unidirectional buffers. A FET with an internal pull-up resistor. Additionally, it also has a
NAND gate connected to the FET.
 Port 3 performs two main functions, as we will see below.
 Functions of Port 3
 I/O port
 Just like Port 2, Port 3 can function as an input-output port.
 Alternate SFR function
 The input to SFR 1, we get the output of latch as 1, which turns on the NAND gate, and
depending on the value of ‘Alternate Output Pin,’ FET will be wither ON/OFF.
RXD: this is used for a serial input port
TXD: this is used for serial output port
INT0: this used for an external interrupt 0
INT1: this used for external interrupt 1
T0: Timer 0 external input
T1: Timer 1 external input
WR: external data memory write strobe
RD: external data memory Read strobe
 PORT Programming:
Example-1: - LEDs are connected to bits PI and P2. Write an 8051 C program that shows the count
from 0 to FFH (0000 0000 to 1111 1111 in binary) on the LEDs.
Solution:

Example-2: - Write an 8051 C program to get a byte of data from PI, wait 1/2 second, and then send
it to P2.
Solution:

Prepared By: - Mr. R. V. Patel 20


Example-3: - Write an 8051 C program to get a byte of data from PO. If it is less than 100, send it to
PI; otherwise, send it to P2.
Solution:

Example-4: - Write an 8051 C program to toggle only bit P2.4 continuously without disturbing the
rest of the bits of P2.
Solution:

Prepared By: - Mr. R. V. Patel 21


Example-5: - Write an 8051 C program to monitor bit PI.5. If it is high, send 55H to PO; otherwise,
send AAH to P2.
Solution:

 8051 Timers and Counters


 A timer is a specialized type of clock which is used to measure time intervals.
 A timer that counts from zero upwards for measuring time elapsed is often called
a stopwatch.
 It is a device that counts down from a specified time interval and used to generate a time
delay, for example, an hourglass is a timer.
 A counter is a device that stores (and sometimes displays) the number of times a particular
event or process occurred, with respect to a clock signal.
 It is used to count the events happening outside the microcontroller.
 In electronics, counters can be implemented quite easily using register-type circuits such as
a flip-flop.
 Difference between a Timer and a Counter
 The points that differentiate a timer from a counter are as follows −
Timer Counter
The register incremented for every The register is incremented considering 1 to 0 transition
machine cycle. at its corresponding to an external input pin (T0, T1).
Maximum count rate is 1/12 of the Maximum count rate is 1/24 of the oscillator frequency.
oscillator frequency.
A timer uses the frequency of the A counter uses an external signal to count pulses.
internal clock, and generates delay.

 Timer
 The 8051 has two counters/timers which can be used either as timer to generate a time
delay or as counter to count events happening outside the microcontroller.

Prepared By: - Mr. R. V. Patel 22


 The 8051 has two timers: timer0 and timer1.
 They can be used either as timers or as counters. Both timers are 16 bits wide.
 Since the 8051 has an 8-bit architecture, each 16-bit is accessed as two separate registers of
low byte and high byte.

 Block Diagram

 Timers Associated Registers


 Counters and Timers in 8051 microcontroller contain two special function registers: TMOD
(Timer Mode Register) and TCON (Timer Control Register), which are used for activating
and configuring timers and counters.
 Timer Mode Control (TMOD)
 TMOD is an 8-bit register used for selecting timer or counter and mode of timers.
 Lower 4-bits are used for control operation of timer 0 or counter0, and remaining 4-bits are
used for control operation of timer1 or counter1.
 This register is present in SFR register, the address for SFR register is 89th.

Prepared By: - Mr. R. V. Patel 23


 Its lower 4 bits are used for Timer0 and the upper 4 bits are used for Timer1
Bit 7,3 – GATE:
1 = Enable Timer/Counter only when the INT0/INT1 pin is high and TR0/TR1 is set.
0 = Enable Timer/Counter when TR0/TR1 is set.
Bit 6,2 - C/ (Counter/Timer): Timer or Counter select bit
1 = Use as Counter
0 = Use as Timer
Bit 5:4 & 1:0 - M1:M0: Timer/Counter mode select bit
These are Timer/Counter mode select bit as per the below table
M1 M0 Mode Operation
0 0 0 (13-bit timer mode) 13-bit timer/counter, 8-bit of THx & 5-bit of TLx
0 1 1 (16-bit timer mode) 16-bit timer/counter, THx cascaded with TLx
1 0 2 (8-bit auto-reload 8-bit timer/counter (auto-reload mode), TLx reload
mode) with the value held by THx each time TLx overflow
1 1 3 (split timer mode) Split the 16-bit timer into two 8-bit timers i.e. THx and
TLx like two 8-bit timer

 TCON Register

 TCON is an 8-bit control register and contains a timer and interrupt flags.
Bit 7 - TF1: Timer1 Overflow Flag
1 = Timer1 overflow occurred (i.e. Timer1 goes to its max and roll over back to zero).

Prepared By: - Mr. R. V. Patel 24


0 = Timer1 overflow not occurred.
It is cleared through software. In the Timer1 overflow interrupt service routine, this bit will get cleared
automatically while exiting from ISR.
Bit 6 - TR1: Timer1 Run Control Bit
1 = Timer1 start.
0 = Timer1 stop.
It is set and cleared by software.
Bit 5 – TF0: Timer0 Overflow Flag
1 = Timer0 overflow occurred (i.e. Timer0 goes to its max and roll over back to zero).
0 = Timer0 overflow not occurred.
It is cleared through software. In the Timer0 overflow interrupt service routine, this bit will get cleared
automatically while exiting from ISR.
Bit 4 – TR0: Timer0 Run Control Bit
1 = Timer0 start.
0 = Timer0 stop.
It is set and cleared by software.
Bit 3 - IE1: External Interrupt1 Edge Flag
1 = External interrupt1 occurred.
0 = External interrupt1 Processed.
It is set and cleared by hardware.
Bit 2 - IT1: External Interrupt1 Trigger Type Select Bit
1 = Interrupt occurs on falling edge at INT1 pin.
0 = Interrupt occur on a low level at the INT1 pin.
Bit 1 – IE0: External Interrupt0 Edge Flag
1 = External interrupt0 occurred.
0 = External interrupt0 Processed.
It is set and cleared by hardware.
Bit 0 – IT0: External Interrupt0 Trigger Type Select Bit
1 = Interrupt occurs on falling edge at INT0 pin.
0 = Interrupt occur on a low level at INT0 pin.
 Timer Modes
 Timers have their operation modes which are selected in the TMOD register using M0 & M1
bit combinations.
 Mode 0 of Timer/Counter

Prepared By: - Mr. R. V. Patel 25


 The Mode 0 operation is the 8-bit timer or counter with a 5-bit pre-scaler.
 So it is a 13-bit timer/counter.
 It uses 5 bits of TL0 or TL1 and all of the 8-bits of TH0 or TH1.

Example
Let's generate a square wave of 2mSec period using an AT89C51 microcontroller with timer0
in mode0 on the P1.0 pin of port1. Assume xtal oscillator frequency of 11.0592 MHz.

As the Xtal oscillator frequency is 11.0592 MHz we have a machine cycle of 1.085uSec. Hence,
the required count to generate a delay of 1mSec. is,
Count =(1×10^-3)/(1.085×10^-6) ≈ 921
The maximum count of Mode0 is 2^13 (0 - 8191) and the Timer0 count will increment from
0 – 8191. So we need to load value which is 921 less from its maximum count i.e. 8191. Also, here
in the below program, we need an additional 13 MC (machine cycles) from call to return of delay
function. Hence value needed to be loaded is,
Value=(8191-Count)+Function_MCycles+1 =7284= 0x1C74
So we need to load 0x1C74 value in Timer0.
1C74 = 0001 1100 0111 0100 b, now load lower 5-bit in TL0 and next 8-bit in TH0
so here we get,
TL0 = 0001 0100 = 0x14 and TH0 = 1110 0011 = 0xE3
 Programming steps for delay function
o Load Tmod register value i.e. TMOD = 0x00 for Timer0/1 mode0 (13-bit timer mode).
o Load calculated THx value i.e. here TH0 = 0xE3.
o Load calculated TLx value i.e. here TL0 = 0x14.
o Start the timer by setting a TRx bit. i.e. here TR0 = 1.
o Poll TFx flag till it does not get set.
o Stop the timer by clearing TRx bit. i.e. here TR0 = 0.

Prepared By: - Mr. R. V. Patel 26


o Clear timer flag TFx bit i.e. here TF0 = 0.
o Repeat from step 1 to 7 for the delay again.
o Program for timer mode0

#include <reg51.h> /* Include x51 header file */


sbit test = P1^0; /* set test pin 0 of port1 */

void timer_delay() /* Timer0 delay function */


{
TH0 = 0xE3; /* Load 8-bit in TH0 (here Timer0 used) */
TL0 = 0x14; /* Load 5-bit in TL0 */
TR0 = 1; /* Start timer0 */
while(TF0 == 0); /* Wait until timer0 flag set */
TR0 = 0; /* Stop timer0 */
TF0 = 0; /* Clear timer0 flag */
}
void main()
{
TMOD = 0x00; /* Timer0/1 mode0 (13-bit timer mode) */
while(1)
{
test = ~test; /* Toggle test pin */
timer_delay(); /* Call timer0 delay */
}
}
 Mode 1 of Timer/Counter
 The Mode 1 operation is the 16-bit timer or counter.
 In the following diagram, we are using Mode 1 for Timer0.

 In this case every event for counter operations or machine cycles for timer operation, the
TH0– TL0 register-pair will be incremented by 1.
 When the register pair overflows from FFFFH to 0000H, then the TF0 of TCON register will
be high, and it stops the timer/counter.
 Mode 2 of Timer/Counter
 The Mode 2 operation is the 8-bit auto reload timer or counter.
 In the following diagram, we are using Mode 2 for Timer1.

Prepared By: - Mr. R. V. Patel 27


 In this case every event for counter operations or machine cycles for timer operation, the
TL1register will be incremented by 1.
 When the register pair overflows from FFH to 00H, then the TF1 of TCON register will be
high, also theTL1 will be reloaded with the content of TH1 and starts the operation again.
 Mode 3 of Timer/Counter
 Mode 3 is different for Timer0 and Timer1. When the Timer0 is working in mode 3, the TL0
will be used as an 8-bit timer/counter.
 It will be controlled by the standard Timer0 control bits, T0 and INT0 inputs.
 The TH0 is used as an 8-bit timer but not the counter.
 This is controlled by Timer1 Control bit TR1. When the TH0 overflows from FFH to 00H, then
TF1 is set to 1.
 In the following diagram, we can Timer0 in Mode 3.

 When the Timer1 is working in Mode 3, it simply holds the count but does not run.
 When Timer0 is in mode 3, the Timer1 is configured in one of the mode 0, 1 and 2.
 In this case, the Timer1 cannot interrupt the microcontroller.
 When the TF1 is used by TH0 timer, the Timer1 is used as Baud Rate Generator.

Prepared By: - Mr. R. V. Patel 28


 Timer Calculation
 8051 Oscillator frequency is divided by 12 and then fed to the controller, Time to
increment the Timer count by one(timer tick) can be determined as below.
tick = (1/(Fosc/12)
$$tick = 12/Fosc$$ For Fosc == 11.0592Mhz, the tick time will be
tick = 12/11.0592M = 1.085069444us = 1.085us
 Now the Timer value for the required delay can be calculated as below.
Delay = TimerCount * tick
Count = (Delay/tick)
RegValue = TimerMax- Count
RegValue = TimerMax-(Delay/tick) = TimerMax - (Delay/1.085us)
$$RegValue = TimerMax-((Delay/1.085) * 10^6)$$
 Timer-1: - Let’s generate a square wave of 2mSec time period using an AT89C51
microcontroller with timer0 in mode1 on the P1.0 pin of port1. Assume Xtal oscillator
frequency of 11.0592 MHz.

As Xtal is 11.0592 MHz we have a machine cycle of 1.085uSec.


Hence, the required count to generate a delay of 1mSec. is,
Count =(1×10^(-3)) / (1.085×10^(-6) ) ≈ 921
And mode1 has a max count is 2^16 (0 - 65535) and it increments from 0 to 65535 so we need to
load value which is 921 less from its max. count i.e. 65535. Also, here in the below program, we need
an additional 13 MC (machine cycles) from call to return of delay function. Hence value needed to
be loaded is,
Value=(65535-Count)+Function_MCycles+1 =64615= (FC74)Hex
So we need to load FC74 Hex value higher byte in TH0 and lower byte in TL0 as,
TH0 = 0xFC & TL0 = 0x74
 Programming steps for delay function
o Load Tmod register value i.e. TMOD = 0x01 for Timer0 mode1 (16-bit timer mode).
o Load calculated THx value i.e. here TH0 = 0xFC.

Prepared By: - Mr. R. V. Patel 29


o Load calculated TLx value i.e. here TL0 = 0x74.
o Start the timer by setting a TRx bit. i.e. here TR0 = 1.
o Poll TFx flag till it does not get set.
o Stop the timer by clearing TRx bit. i.e. here TR0 = 0.
o Clear timer flag TFx bit i.e. here TF0 = 0.
o Repeat from step 1 to 7 for the delay again.
 Program for timer mode1
#include <reg51.h> /* Include x51 header file */
sbit test = P1^0; /* set test pin0 of port1 */
void timer_delay() /* Timer0 delay function */
{
TH0 = 0xFC; /* Load higher 8-bit in TH0 */
TL0 = 0x74; /* Load lower 8-bit in TL0 */
TR0 = 1; /* Start timer0 */
while(TF0 == 0); /* Wait until timer0 flag set */
TR0 = 0; /* Stop timer0 */
TF0 = 0; /* Clear timer0 flag */
}
void main()
{
TMOD = 0x01; /* Timer0 mode1 (16-bit timer mode) */
while(1)
{
test = ~test; /* Toggle test pin */
timer_delay(); /* Call timer0 delay */
}
}

Prepared By: - Mr. R. V. Patel 30

You might also like