You are on page 1of 49

Keypad is organized as a matrix of switches in rows and column.

The article uses a 4X3 matrix keypad and a 16x2 LCD for displaying the output of keypad. The circuit diagram shows the connection of keypad with the controller. Port P2 of the microcontroller is used to send the data for displaying on the LCD. P1^1, P1^2, P1^3 pins of microcontroller is connected to RS, RW, EN pins of LCD respectively. Port P0 is used to scan input from the keypad (refer circuit diagram for connection).

The concept of interfacing keypad with the MCU is simple. Every number is assigned two unique parameters, i.e., row and column number (n(R, C) for example 6 (2, 3)). Hence every time a key is pressed the number is identified by detecting the row and column number of the key pressed.

Initially all the rows are set to zero by the controller and the columns are scanned to check if any key is pressed. In case no key is pressed the output of all the columns will be high. Whenever a key is pressed the row and column corresponding to the key will get short, resulting in the output of the corresponding column goes to go low (since we have made all the rows zero). This gives the column number of the pressed key.
Once the column number is detected, the controller sets all the rows to high. Now one by one each row is set to zero by controller and the earlier detected column is checked if it becomes zero. The row corresponding to which the column gets zero is the row number of the digit.

\The above process is very fast and even if the switch is pressed for a very small duration of time the controller can detect the key which is pressed. The controller displays the number corresponding to the row and column on the LCD.

#include<reg52.h> //including sfr registers for ports of the controller #include<lcd.h> //LCD Module Connections sbit RS = P0^0; sbit EN = P0^1; sbit D0 = P2^0; sbit D1 = P2^1; sbit D2 = P2^2; sbit D3 = P2^3; sbit D4 = P2^4; sbit D5 = P2^5; sbit D6 = P2^6; sbit D7 = P2^7; //End LCD Module Connections //Keypad Connections sbit R1 = P1^0; sbit R2 = P1^1; sbit R3 = P1^2; sbit R4 = P1^3; sbit C1 = P1^4; sbit C2 = P1^5; sbit C3 = P1^6; sbit C4 = P1^7; //End Keypad Connections void Delay(int a) { int j; int i; for(i=0;i<a;i++) {

for(j=0;j<100;j++) { } } } char Read_Keypad() { C1=1; C2=1; C3=1; C4=1; R1=0; R2=1; R3=1; R4=1; if(C1==0){Delay(100);while(C1==0);return if(C2==0){Delay(100);while(C2==0);return if(C3==0){Delay(100);while(C3==0);return if(C4==0){Delay(100);while(C4==0);return R1=1; R2=0; R3=1; R4=1; if(C1==0){Delay(100);while(C1==0);return if(C2==0){Delay(100);while(C2==0);return if(C3==0){Delay(100);while(C3==0);return if(C4==0){Delay(100);while(C4==0);return R1=1; R2=1; R3=0; R4=1; if(C1==0){Delay(100);while(C1==0);return if(C2==0){Delay(100);while(C2==0);return if(C3==0){Delay(100);while(C3==0);return if(C4==0){Delay(100);while(C4==0);return R1=1; R2=1; R3=1; R4=0; if(C1==0){Delay(100);while(C1==0);return if(C2==0){Delay(100);while(C2==0);return if(C3==0){Delay(100);while(C3==0);return if(C4==0){Delay(100);while(C4==0);return return 0; } void main() { int i=0; char c,p; Lcd8_Init(); while(1) { Lcd8_Set_Cursor(1,1); Lcd8_Write_String("Keys Pressed:"); Lcd8_Set_Cursor(2,1);

'7';} '8';} '9';} '/';}

'4';} '5';} '6';} 'X';}

'1';} '2';} '3';} '-';}

'C';} '0';} '=';} '+';}

Lcd8_Write_String("Times:"); while(!(c = Read_Keypad())); p=c; while(p==c) { i++; Lcd8_Set_Cursor(1,14); Lcd8_Write_Char(c); Lcd8_Set_Cursor(2,7); Lcd8_Write_Char(i+48); Delay(100); while(!(c = Read_Keypad())); } i=0; Lcd8_Clear(); } }

Interfacing of GSM Module with 8051 microcontroller (AT89C51) using PC


GSM is widely used mobile communication architecture used in most of the countries. This project demonstrates the interfacing of microcontroller AT89C51 with HyperTerminal and GSM module. It aims to familiarize with the syntax of AT Commands and their Information Response and Result Codes. The ASCII values of characters in the Information Response, Result Codes and their syntax can be monitored by an LED array. For the basic concepts, working and operation of AT commands and GSM module refer GSM/GPRS Module. he project explains interfacing of the AT89C51 microcontroller with the GSM module and the HyperTerminal. HyperTerminal is a Windows application. The AT commands are sent by the HyperTerminal to the GSM module. The Information Response and/or Result Codes are received at the microcontroller and retransmitted to the HyperTerminal by the controller.

A GSM module has an RS232 interface for serial communication with an external peripheral. In this case, the transmit pin (Tx) of the computers Serial port is connected with the receive pin (Rx) of the GSM modules RS-232 interface. The transmit pin (Tx) of the RS-232 of GSM module is connected to receive pin (Rx) of microcontrollers serial transmission pin. And the serial transmit pin of the microcontroller is connected to the receive pin of the computers Serial port. Therefore the commands and t heir results are transmitted and received in a triangular fashion as depicted below.

In subsequent projects (see MC075 & MC076), the HyperTerminal will be replaced by the microcontroller itself; thus avoiding the need of using a Computer to establish an interface. This would lead to an independent GSM based system.]

The microcontroller is programmed to receive and transmit data at a baud rate of 9600. For more details on setting the baud rate of microcontroller, refer serial communication with 8051.

The controller can receive data signals either by polling or by making use of serial interrupt (ES). Serial interrupt has been explained in interrupt programming. In polling, the controller continuously scans serial port for incoming data from the GSM module. In this project, interrupt has been used for monitoring and controlling the flow of data by the controller instead of the polling method.
T commands are used to control MODEMs. AT is the abbreviation for Attention. These commands come from Hayes commands that were used by the Hayes smart modems. The Hayes commands started with AT to indicate the attention from the MODEM. The dial up and wireless MODEMs (devices that involve machine to machine communication) need AT commands to interact with a computer. These include the Hayes command set as a subset, along with other extended AT commands.

AT commands with a GSM/GPRS MODEM or mobile phone can be used to access following information and services: 1. Information and configuration pertaining to mobile device or MODEM and SIM card. 2. SMS services. 3. MMS services. 4. Fax services. 5. Data and Voice link over mobile network.

The Hayes subset commands are called the basic commands and the commands specific to a GSM network are called extended AT commands.

) Test commands - used to check whether a command is supported or not by the MODEM. SYNTAX: For example: AT<command name>=? ATD=?

2) Read command - used to get mobile phone or MODEM settings for an operation. SYNTAX: For example: AT<command name>? AT+CBC?

3) Set commands - used to modify mobile phone or MODEM settings for an operation. SYNTAX: AT<command name>=value1, value2, , valueN

Some values in set commands can be optional. For example: AT+CSCA=+9876543210, 120

4) Execution commands - used to carry out an operation. SYNTAX: parameterN The read commands are not available to get value of last parameter assigned in execution commands because parameters of execution commands are not stored. For example: AT+CMSS=1,+ 9876543210, 120 AT<command name>=parameter1, parameter2, ,

1)

AT - This command is used to check communication between the module and the

computer. For example, AT OK The command returns a result code OK if the computer (serial port) and module are connected properly. If any of module or SIM is not working, it would return a result code ERROR.

2)

+CMGF - This command is used to set the SMS mode. Either text or PDU mode can be selected by assigning 1 or 0 in the command. SYNTAX: AT+CMGF=<mode> 0: for PDU mode 1: for text mode

The text mode of SMS is easier to operate but it allows limited features of SMS. The PDU (protocol data unit) allows more access to SMS services but the operator

requires bit level knowledge of TPDUs. The headers and body of SMS are accessed in hex format in PDU mode so it allows availing more features.

For example, AT+CMGF=1 OK

3)

+CMGW - This command is used to store message in the SIM. SYNTAX: AT+CMGW= Phone number> Message to be stored Ctrl+z

As one types AT+CMGW and phone number, > sign appears on next line where one can type the message. Multiple line messages can be typed in this case. This is why the

message is terminated by providing a Ctrl+z combination. As Ctrl+z is pressed, the following information response is displayed on the screen.

+CMGW: Number on which message has been stored

4)

+CMGS - This command is used to send a SMS message to a phone number. SYNTAX: AT+CMGS= serial number of message to be send.

As the command AT+CMGS and serial number of message are entered, SMS is sent to the particular SIM. For example, AT+CMGS=1 OK

5)

ATD - This command is used to dial or call a number. SYNTAX: ATD<Phone number>;(Enter) For example, ATD123456789;

6)

ATA - This command is used to answer a call. An incoming call is indicated by a message RING which is repeated for every ring of the call. When the call ends NO CARRIER is displayed on the screen. SYNTAX: ATA(Enter)

As ATA followed by enter key is pressed, incoming call is answered. For example, RING

RING ATA

7)

ATH - This command is used to disconnect remote user link with the GSM module. SYNTAX: ATH (Enter)

he AT commands for both, GSM module and the mobile phone, are listed below. Some of these commands may not be supported by all the GSM modules available. Also there might be some commands which wont be supported by some mobile handsets.

AT

Checking communication module and computer.

between

the

ATA Answer command

ATD Dial command ATH Hang up call

ATL Monitor speaker loudness GSM is a digital mobile telephony system. GSM digitizes and compresses data, then sends it down a channel with two other streams of user data, each in its own time slot. It operates at either the 900 MHz or 1800 MHz frequency band. - See more at: http://www.pantechsolutions.net/accessory-boards/gsm-interfacing-with8051#sthash.ZILHHAME.dpuf

Fig. 1 shows how to interface the GSM with microcontroller. The GSM module is communicate the microcontroller with mobile phones through UART. To communicate over UART or USART, we just need three basic signals which are namely, RXD (receive), TXD (transmit), GND (common ground).

GSM modem interfacing with microcontroller for SMS control of industrial equipments. The sending SMS through GSM modem when interfaced with microcontroller or PC is much simpler as compared with sending SMS through UART.

Text message may be sent through the modem by interfacing only three signals of the serial interface of modem with microcontroller i.e., TxD, RxD and GND. In this scheme RTS and CTS signals of serial port interface of GSM Modem are connected with each other. The transmit signal of serial port of microcontroller is connected with transmit signal (TxD) of the serial interface of GSM Modem while receive signal of microcontroller serial port is connected with receive signal (RxD) of serial interface of GSM Modem. The SMS message in text mode can contain only 140 characters at the most. It depends upon the amount of information collected from GPS Engine that you need at the base station for tracking vehicle or person. - See more at: http://www.pantechsolutions.net/accessory-boards/gsm-interfacing-with8051#sthash.ZILHHAME.dpuf We now want to display a text in mobile from 8051 Primer Board by using GSM module through UART. In 8051 Primer Board contains two serial interfaces that are UART0 & UART1. Here we are using UART0. The GSM modem is being interfaced with the microcontroller 8051 Primer Board for SMS communication. The SMS can be sending and receiving for the data sharing and situation information and control. - See more at: http://www.pantechsolutions.net/accessory-boards/gsm-interfacing-with8051#sthash.ZILHHAME.dpuf

Give +5V power supply to 8051 Primer Board; connect the +9V adapter with GSM module which is connected with 8051 Primer Board through UART0. Open the Hyper Terminal screen, select which port you are using and set the default settings. Now the screen should show some text messages.

The following Commands and sequence of events performed for sending text message to a mobile phone through GSM Modem interfaced with microcontroller:

First select the text mode for SMS by sending the following AT Command to GSM Modem : AT+CMGF = 1 . This command configures the GSM modem in text mode.

Send the following AT Command for sending SMS message in text mode along with mobile number to the GSM Modem : AT+CMGS =+923005281046 . This command sends the mobile number of the recipient mobile to the GSM modem. Send the text message string ("GSM Modem Test") to the GSM Modem This is a test message from UART". Send ASCII code for CTRL+Z i.e., 0x1A to GSM Modem to transmit the message to mobile phone. After message string has been sent to the modem, send CTRL+Z to the micro-controller, which is equivalent to 0x1A (ASCII value).

If you not reading any text from UART0, then you just check the jumper connections & just check the serial cable is working. Otherwise you just check the code with debugging mode in Keil. If you want to see more details about debugging just see the videos in below link. - See more at: http://www.pantechsolutions.net/accessory-boards/gsm-interfacing-with8051#sthash.ZILHHAME.dpuf

#include <REG51.H> #include <stdio.h> #define LED P0 void serial_init(void);

/* special function register declarations */ /* prototype declarations for I/O functions */ //define prot P0 for LED

unsigned int j; //Setup the serial port for 9600 baud at 11.0592MHz. //------------------------------------------------void serial_init(void) { SCON = 0x50; /* SCON: mode 1, 8-bit UART, enable rcvr */ TMOD |= 0x20; /* TMOD: timer 1, mode 2, 8-bit reload */ TH1 = 0xFD; /* TH1: reload value for 9600 baud @ 11.0592MHz*/ TR1 = 1; /* TR1: timer 1 run */ TI = 1; /* TI: set TI to send first char of UART */ }

//Delay Routine start here void delay1(int n) { int i; for(i=0;i<n;i++); } void delay2(int n) { int i; for(i=0;i<n;i++) delay1(1000); } void led_left() { for (j=0x01; j<=0x80; j<<=1) { LED = j; delay1(1000); } } //-------------------------------------

// Main program starts here //------------------------------------void main(void) { serial_init(); //serial initialization LED = 0x00; printf("AT+CMGF=1%c",13); delay2(20); //Text Mode | hex value of 13 is 0x0D (CR ) printf("AT+CMGS=\"9600292363\"%c",13); delay2(20); //Type your mobile number Eg : "9884467058" led_left(); //scroll left delay1(20); printf("Hi :-) GSM Modem Test"); delay2(20); //Type text as u want printf("%c",0x1A); delay2(20); //line feed command while(1); } - See more at: http://www.pantechsolutions.net/accessory-boards/gsm-interfacing-with8051#sthash.ZILHHAME.dpuf

How to interface computer's Serial Port (RS232) with 8051 microcontroller (AT89C51)
Several devices collect data from sensors and need to send it to another unit, like a computer, for further processing. Data transfer/communication is generally done in two ways: parallel and serial. In the parallel mode, data transfer is fast and uses more number of lines. This mode is good for short range data transfer. Serial communication on the other hand, uses only one or two data lines to transfer data and is generally used for long distance communication. In serial communication the data is sent as one bit at a time. This article describes the interfacing of 8051 microcontroller (AT89C51) with a computer via serial port, RS232. Serial communication is commonly used in applications such as industrial automation systems, scientific analysis and certain consumer products.

The microcontroller AT89C51 has an inbuilt UART for carrying out serial communication. The serial communication is done in the asynchronous mode. A serial port, like other PC ports, is a physical interface to establish data transfer between computer and an external hardware or device. This transfer, through serial port, takes place bit by bit.

BM introduced the DB-9 RS-232 version of serial I/O standard, which is most widely used in PCs and several devices. In RS232, high and low bits are represented by flowing voltage ranges

Bit 0 1

Voltage Range (in V) +3 -25 +25 -3

The range -3V to +3V is undefined. The TTL standards came a long time after the RS232 standard was set. Due to this reason RS232 voltage levels are not compatible with TTL logic. Therefore, while connecting an RS232 to microcontroller system, a voltage converter is required. This converter converts the microcontroller output level to the RS232 voltage levels, and vice versa. IC MAX232, also known as line driver, is very commonly used for this purpose. The simplest connection between a PC and microcontroller requires a minimum of three pins, RxD (receiver, pin2), TxD (transmitter, pin3) and ground (pin5) of the serial port of computer.
TxD pin of serial port connects to RxD pin of controller via MAX232. And similarly, RxD pin of serial port connects to the TxD pin of controller through MAX232. MAX232 has two sets of line drivers for transferring and receiving data. The line drivers used for transmission are called T1 and T2, where as the line drivers for receiver are designated as R1 and R2. The connection of MAX232 with computer and the controller is shown in the circuit diagram.

An important parameter considered while interfacing serial port is the Baud rate which is the speed at which data is transmitted serially. It is defined as number of bits transmitted or received per second. It is generally expressed in bps (bits per second). AT89C51 microcontroller can be set to transfer and receive serial data at different baud rates using software instructions. Timer1 is used to set the baud rate of serial communication for the microcontroller. For this purpose, Timer1 is used in mode2 which is an 8-bit auto reload mode. (Refer Timer programming with 8051) To get baud rates compatible with the PC, TH1 should be loaded with the values as shown: Baud Rate (bps) 9600 4800 2400 1200 TH1 (Hex value) FD FA F4 E8

In this project baud rate 9600bps is used. For serial communication AT89C51 has registers SBUF and SCON (Serial control register). SBUF is an 8bit register. For transmitting a data byte serially, it needs to be placed in the SBUF register. Similarly whenever a data byte is received serially, it comes in the SBUF register, i.e., SBUF register should be read to receive the serial byte.

SCON register is used to set the mode of serial communication. The project uses Mode1, in which the data length is of 8 bits and there is a start and a stop bit. The SCON register is bit addressable register. The following table shows the configuration of each bit.

SM0 D7

SM1 D6

SM2 D5

REN D4

TB8 D3

RB8 D2

TI D1

RI

D0

SM0

SM1

0 0 1 1

0 1 0 1

Serial mode 0 Serial mode 1, 8-bit data, 1 start bit, 1 stop bit Serial mode 2 Serial mode 3

I (transmit interrupt) is an important flag bit in the SCON register. The controller raises the TI flag when the 8-bit character is transferred. This indicates that the next byte can be transferred now. The TI bit is raised at the beginning of the stop bit.

RI (receive interrupt) is also a flag bit of the SCON register. On receiving the serial data, the microcontroller skips the start and stop bits, and puts the byte is SBUF register. The RI flag bit is then raised to indicate that the byte has been received and should be picked up.

Hyper Terminal
Hyper Terminal, a Windows XP application, can be used to receive or transmit serial data through RS232. To open Hyper Terminal, go to Start Menu, select all programs, go to Accessories, click on Communications and select Hyper Terminal.

To start a new connection, go to File menu and click on new connection. The connection window opens up. Give a name to your connection and select 1 st icon and click on OK. Connection property window opens here. Select Bit rate as 9600bps, Data bits 8, Parity as none, Stop bit 1, Flow control none and click OK. Now the serial data can be read on hyper terminal.

In program, Timer1 is used with auto reload setting. The baud rate is fixed to 9600bps by loading TH1 to 0xFD. The value 0x50 is loaded in the SCON register. This will initialize the serial port in Mode1. The program continuously receives a character (say a) from the serial port of the computer and transmits it back.

OV TMOD,#0x20 ;TIMER1,MODE 2,AUTO RELOAD

MOV TH1,#-6 ;4800 BAUD RATE

MOV SCON,#0x50 ;8-BIT,1 STOP,REN ENABLED

SETB TR1 ;START TIMER 1

AGAIN:

MOV SBUF,P2 ;P2 TO BE TRANSFERRED

HERE:

JNB TI,HERE ;WAIT FOR THE LAST BIT

Receiver Module

MOV TMOD,#0x20 ;TIMER1,MODE2

MOV TH1,#-6 ;4800 BAUD

MOV SCON,#0x50 ;8-BIT,1 STOP,REN ENABLED

SETB TR1 ;START TIMER1

HERE:

JNB RI,HERE ;WAIT FOR CHAR TO COME

MOV A,SBUF ;SAVE INCOMING BYTE IN A

MOV P2,A ;SEND TO PORT1

RS232 is a communication protocol, commonly used to communicate between PC & various electronics equipments. Now, USB being commonly used and has almost replaced the Serial Ports on every electronic system. The Simple microcontrollers like 89S52 or many 8 bit AVRs, PICs have no direct USB facility built-in. These microcontroller depends on a Serial To USB converters. FTDI has one such USB to Serial converter named FT232RL. This IC connects to PCs via USB and on other side connects to legacy microcontrollers over TTL level Serial Lines. 89S52 has one TTL serial port (5V) built in. P3.0 acts as Rx & P3.1 acts as Tx pin for the serial communication

PCAM+ Kit has one RS232 Serial Port Interface section located at Top Right Corner. Locate the RX, TX pins from these sections. The application described here does following: 1. Waits for characters to be received from PC 2. Prints the received character to 16x2 LCD 3. Sends back the same character to PC 4. A terminal Program on PC shows the received characters

To complete this application, you will need: 1. Product - PCAM+ (Practical Course For ATMEL Microcontrollers - Upgraded) 2. HandyProg-USB Programmer for 89S52 (Included with the PCAM+ kit) 3. Single pin female to female connectors - 2 + 3 + 8 4. Serial cable M-F Straight 5. Any Serial Terminal Program loaded on your PC (I found the Serial Monitor available from Arduino IDE easy to use. You may write VB or VB.Net program to transmit & receive) Connections: 1. Connect Serail M-F cable between PC and PCAM+ Kit's serial port. 2. Connect Rx & Tx pins from serial port section of PCAM+ kit to P3.0 & P3.1 pins respectively 3. Connect RS, RW, EN pins of LCD section to P2.0, P2.1, P2.2 of 89S52 section 4. Connect 0-7 pins of LCD to P0 of 89S52 5. Power up and flash the hex of code described below 6. After Programming the controller, LCD should display "Waiting" message 7. From PC, use any serial terminal program (Don't use hyperterminal.) Connect the terminal program at 2400 baud rate. Select correct COM Port Number. 8. Send some characters from PC's terminal program. 9. You will see these characters on LCD. 10. And also the terminal program will show them back as received text.

Some details about baud Rate calculation: 1. Speed of serial communication is called as baud rate 2. The speed i.e. baud rate is set with the help of Timer1 3. In other words, when using serial communication, Timer1 is unavailable for other use Timer1 gets dedicated to Serial Communication when serial communication is enabled 4. Set approprieate values to TMOD, TCON, TL1, TH1 registers to configure baud rate 5. Write appropriete values for SCON, SBUF, PCON.7 to enable Serial Communication 6. Timer1 us used in 8-bit auto reload mode thus TMOD value will be 00100000b

7. Value of TL1 increments every machine cycle 8. Value of TH1 acts as the "relaod" value for TL1. In otehr words, TL1 starts incrementing not from Zero but from same value as saved in TH1. If Th1 has value 100, then after TL1 overflows, it will re-start with 100 again 9. Formula for TH1 value calculation is simple: TH1 = 256 ((Crsytal Frequency /384)/Baud Rate) This application will communicate at 2400 baud rate TH1 = 256 ((11059200/384)/2400) TH1 = 244d Thus hex value of 244d is F4h 10. SCON value will be 01000000b 11. The 6th bit of SCON is set to enable 8-bit UART mode of Serial Communication 12. The serial communication starts only after the TR1 bit is set to high 13. Set REN bit to enable serial Receive

Here is the program developed with the help of 8051IDE for PCAM+ Kit:

baudnum EQU 0f4h ;For LCD EN EQU P2.2 ;change as per your connections RS EQU P2.0 ;change as per your connections RW EQU P2.1 ;change as per your connections PDATA EQU P0 ;change as per your connections LCALL INIT_LCD LCALL CLEAR_LCD START: MOV A,#'W' LCALL WRITE_TEXT MOV A,#'a' LCALL WRITE_TEXT MOV A,#'i' LCALL WRITE_TEXT MOV A,#'t' LCALL WRITE_TEXT MOV A,#'i' LCALL WRITE_TEXT MOV A,#'n'

LCALL WRITE_TEXT MOV A,#'g' LCALL WRITE_TEXT

MOV PCON,#00h MOV TMOD,#00100000b MOV TH1,#baudnum SETB TR1 MOV SCON,#40h SETB REN MAIN: JBC RI,RECEIVED_CHAR NOP SJMP MAIN ;Loop till character is not received LCALL CLEAR_LCD

RECEIVED_CHAR: MOV A,SBUF ;Received char is stored in SBUF, make a copy of it MOV R7,A ;Copy backup of received char CLR RI LCALL WRITE_TEXT

;Now transmitting back the received char MOV A,R7 ;transmit back from backup Mov SBUF,A ACALL Transmit LJMP MAIN Transmit: ;Wait till transmit is not over. JNB TI,Transmit CLR TI RET

INIT_LCD: CLR RS MOV PDATA,#00110100b SETB EN CLR EN LCALL WAIT_LCD CLR RS MOV PDATA,#00111100b

SETB EN CLR EN LCALL WAIT_LCD CLR RS MOV PDATA,#0Ch SETB EN CLR EN LCALL WAIT_LCD

CLR RS MOV PDATA,#06h SETB EN CLR EN LCALL WAIT_LCD RET ;NOTE: Copy character to be displayed in A WRITE_TEXT: SETB RS MOV PDATA,A SETB EN CLR EN LCALL WAIT_LCD RET CLEAR_LCD: CLR RS MOV PDATA,#01h SETB EN CLR EN LCALL WAIT_LCD RET WAIT_LCD: CLR EN CLR RS SETB RW MOV PDATA,#0FFh SETB EN MOV A,PDATA JB ACC.7,WAIT_LCD CLR EN CLR RW RET

TIMER PROGRAMMING:

Email:

Password:

Remember Me | Create Account (Free)

Consulting Services The 8052.com Book Message Forum Tutorials 8052 FAQs News Links About 8052.com

8051 Tutorial: Timers

The 8051 comes equipped with two timers, both of which may be controlled, set, read, and configured individually. The 8051 timers have three general functions: 1) Keeping time and/or calculating the amount of time between events, 2) Counting the events themselves, or 3) Generating baud rates for the serial port. The three timer uses are distinct so we will talk about each of them separately. The first two uses will be discussed in this chapter while the use of timers for baud rate generation will be discussed in the chapter relating to serial ports.

How does a timer count? How does a timer count? The answer to this question is very simple: A timer always counts up. It doesnt matter whether the timer is being used as a timer, a counter, or a baud rate generator: A timer is always incremented by the microcontroller. Programming Tip: Some derivative chips actually allow the program to configure whether the timers count up or down. However, since this option only exists on some derivatives it is beyond the scope of this tutorial which is aimed at the standard 8051. It is only mentioned here in the event that you absolutely need a timer to count backwards, you will know that you may be able to find an 8051-compatible microcontroller that does it. USING TIMERS TO MEASURE TIME Obviously, one of the primary uses of timers is to measure time. We will discuss this use of timers first and will subsequently discuss the use of timers to count events. When a timer is used to measure time it is also called an "interval timer" since it is measuring the time of the interval between two events. How long does a timer take to count? First, its worth mentioning that when a timer is in interval timer mode (as opposed to event counter mode) and correctly configured, it will increment by 1 every machine cycle. As you will recall from the previous chapter, a single machine cycle consists of 12 crystal pulses. Thus a running timer will be incremented: 11,059,000 / 12 = 921,583 921,583 times per second. Unlike instructions--some of which require 1 machine cycle, others 2, and others 4--the timers are consistent: They will always be incremented once per machine cycle. Thus if a timer has counted from 0 to 50,000 you may calculate: 50,000 / 921,583 = .0542 .0542 seconds have passed. In plain English, about half of a tenth of a second, or one-twentieth of a second. Obviously its not very useful to know .0542 seconds have passed. If you want to execute an event once per second youd have to wait for the timer to count from 0 to 50,000 18.45 times. How can you wait "half of a time?" You cant. So we come to another important calculation. Lets say we want to know how many times the timer will be incremented in .05 seconds. We can do simple multiplication: .05 * 921,583 = 46,079.15.

This tells us that it will take .05 seconds (1/20th of a second) to count from 0 to 46,079. Actually, it will take it .049999837 seconds--so were off by .000000163 seconds--however, thats close enough for government work. Consider that if you were building a watch based on the 8051 and made the above assumption your watch would only gain about one second every 2 months. Again, I think thats accurate enough for most applications--I wish my watch only gained one second every two months! Obviously, this is a little more useful. If you know it takes 1/20th of a second to count from 0 to 46,079 and you want to execute some event every second you simply wait for the timer to count from 0 to 46,079 twenty times; then you execute your event, reset the timers, and wait for the timer to count up another 20 times. In this manner you will effectively execute your event once per second, accurate to within thousandths of a second. Thus, we now have a system with which to measure time. All we need to review is how to control the timers and initialize them to provide us with the information we need. Timer SFRs As mentioned before, the 8051 has two timers which each function essentially the same way. One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs (TMOD and TCON) which control the timers, and each timer also has two SFRs dedicated solely to itself (TH0/TL0 and TH1/TL1). Weve given SFRs names to make it easier to refer to them, but in reality an SFR has a numeric address. It is often useful to know the numeric address that corresponds to an SFR name. The SFRs relating to timers are:
SFR Name TH0 TL0 TH1 TL1 TCON TMOD Description Timer 0 High Byte Timer 0 Low Byte Timer 1 High Byte Timer 1 Low Byte Timer Control Timer Mode SFR Address 8Ch 8Ah 8Dh 8Bh 88h 89h

When you enter the name of an SFR into an assembler, it internally converts it to a number. For example, the command: MOV TH0,#25h moves the value 25h into the TH0 SFR. However, since TH0 is the same as SFR address 8Ch this command is equivalent to: MOV 8Ch,#25h

Now, back to the timers. First, lets talk about Timer 0. Timer 0 has two SFRs dedicated exclusively to itself: TH0 and TL0. Without making things too complicated to start off with, you may just think of this as the high and low byte of the timer. That is to say, when Timer 0 has a value of 0, both TH0 and TL0 will contain 0. When Timer 0 has the value 1000, TH0 will hold the high byte of the value (3 decimal) and TL0 will contain the low byte of the value (232 decimal). Reviewing low/high byte notation, recall that you must multiply the high byte by 256 and add the low byte to calculate the final value. That is to say: TH0 * 256 + TL0 = 1000 3 * 256 + 232 = 1000 Timer 1 works the exact same way, but its SFRs are TH1 and TL1. Since there are only two bytes devoted to the value of each timer it is apparent that the maximum value a timer may have is 65,535. If a timer contains the value 65,535 and is subsequently incremented, it will reset--or overflow--back to 0. The TMOD SFR Lets first talk about our first control SFR: TMOD (Timer Mode). The TMOD SFR is used to control the mode of operation of both timers. Each bit of the SFR gives the microcontroller specific information concerning how to run a timer. The high four bits (bits 4 through 7) relate to Timer 1 whereas the low four bits (bits 0 through 3) perform the exact same functions, but for timer 0. The individual bits of TMOD have the following functions: TMOD (89h) SFR
Bit Name 7 6 5 4 3 2 1 0 GATE1 C/T1 T1M1 T1M0 GATE0 C/T0 T0M1 T0M0 Explanation of Function Timer When this bit is set the timer will only run when INT1 (P3.3) is high. 1 When this bit is clear the timer will run regardless of the state of INT1. When this bit is set the timer will count events on T1 (P3.5). When this 1 bit is clear the timer will be incremented every machine cycle. Timer mode bit (see below) Timer mode bit (see below) 1 1

When this bit is set the timer will only run when INT0 (P3.2) is high. 0 When this bit is clear the timer will run regardless of the state of INT0. When this bit is set the timer will count events on T0 (P3.4). When this 0 bit is clear the timer will be incremented every machine cycle. Timer mode bit (see below) Timer mode bit (see below) 0 0

As you can see in the above chart, four bits (two for each timer) are used to specify a mode of operation. The modes of operation are:
TxM1 TxM0 Timer Mode Description of Mode

0 0 1 1

0 1 0 1

0 1 2 3

13-bit Timer. 16-bit Timer 8-bit auto-reload Split timer mode

13-bit Time Mode (mode 0) Timer mode "0" is a 13-bit timer. This is a relic that was kept around in the 8051 to maintain compatability with its predecesor, the 8048. Generally the 13-bit timer mode is not used in new development. When the timer is in 13-bit mode, TLx will count from 0 to 31. When TLx is incremented from 31, it will "reset" to 0 and increment THx. Thus, effectively, only 13 bits of the two timer bytes are being used: bits 0-4 of TLx and bits 0-7 of THx. This also means, in essence, the timer can only contain 8192 values. If you set a 13-bit timer to 0, it will overflow back to zero 8192 machine cycles later. Again, there is very little reason to use this mode and it is only mentioned so you wont be surprised if you ever end up analyzing archaeic code which has been passed down through the generations (a generation in a programming shop is often on the order of about 3 or 4 months). 16-bit Time Mode (mode 1) Timer mode "1" is a 16-bit timer. This is a very commonly used mode. It functions just like 13bit mode except that all 16 bits are used. TLx is incremented from 0 to 255. When TLx is incremented from 255, it resets to 0 and causes THx to be incremented by 1. Since this is a full 16-bit timer, the timer may contain up to 65536 distinct values. If you set a 16-bit timer to 0, it will overflow back to 0 after 65,536 machine cycles. 8-bit Time Mode (mode 2) Timer mode "2" is an 8-bit auto-reload mode. What is that, you may ask? Simple. When a timer is in mode 2, THx holds the "reload value" and TLx is the timer itself. Thus, TLx starts counting up. When TLx reaches 255 and is subsequently incremented, instead of resetting to 0 (as in the case of modes 0 and 1), it will be reset to the value stored in THx. For example, lets say TH0 holds the value FDh and TL0 holds the value FEh. If we were to watch the values of TH0 and TL0 for a few machine cycles this is what wed see:
Machine Cycle TH0 Value TL0 Value 1 2 3 FDh FDh FDh FEh FFh FDh

4 5 6 7

FDh FDh FDh FDh

FEh FFh FDh FEh

As you can see, the value of TH0 never changed. In fact, when you use mode 2 you almost always set THx to a known value and TLx is the SFR that is constantly incremented. Whats the benefit of auto-reload mode? Perhaps you want the timer to always have a value from 200 to 255. If you use mode 0 or 1, youd have to check in code to see if the timer had overflowed and, if so, reset the timer to 200. This takes precious instructions of execution time to check the value and/or to reload it. When you use mode 2 the microcontroller takes care of this for you. Once youve configured a timer in mode 2 you dont have to worry about checking to see if the timer has overflowed nor do you have to worry about resetting the value--the microcontroller hardware will do it all for you. The auto-reload mode is very commonly used for establishing a baud rate which we will talk more about in the Serial Communications chapter. Split Timer Mode (mode 3) Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, it essentially becomes two separate 8-bit timers. That is to say, Timer 0 is TL0 and Timer 1 is TH0. Both timers count from 0 to 255 and overflow back to 0. All the bits that are related to Timer 1 will now be tied to TH0. While Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be put into modes 0, 1 or 2 normally--however, you may not start or stop the real timer 1 since the bits that do that are now linked to TH0. The real timer 1, in this case, will be incremented every machine cycle no matter what. The only real use I can see of using split timer mode is if you need to have two separate timers and, additionally, a baud rate generator. In such case you can use the real Timer 1 as a baud rate generator and use TH0/TL0 as two separate timers. The TCON SFR Finally, theres one more SFR that controls the two timers and provides valuable information about them. The TCON SFR has the following structure: TCON (88h) SFR
Bit Name 7 TF1 Bit Address 8Fh Explanation of Function Timer 1 Overflow. This bit is set by the microcontroller when Timer 1 overflows. Timer 1

6 5 4

TR1 TF0 TR0

8Eh 8Dh 8Ch

Timer 1 Run. When this bit is set Timer 1 is turned on. When this bit is clear Timer 1 is off. Timer 0 Overflow. This bit is set by the microcontroller when Timer 0 overflows. Timer 0 Run. When this bit is set Timer 0 is turned on. When this bit is clear Timer 0 is off.

1 0 0

As you may notice, weve only defined 4 of the 8 bits. Thats because the other 4 bits of the SFR dont have anything to do with timers--they have to do with Interrupts and they will be discussed in the chapter that addresses interrupts. A new piece of information in this chart is the column "bit address." This is because this SFR is "bit-addressable." What does this mean? It means if you want to set the bit TF1--which is the highest bit of TCON--you could execute the command: MOV TCON, #80h ... or, since the SFR is bit-addressable, you could just execute the command: SETB TF1 This has the benefit of setting the high bit of TCON without changing the value of any of the other bits of the SFR. Usually when you start or stop a timer you dont want to modify the other values in TCON, so you take advantage of the fact that the SFR is bit-addressable. Initializing a Timer Now that weve discussed the timer-related SFRs we are ready to write code that will initialize the timer and start it running. As youll recall, we first must decide what mode we want the timer to be in. In this case we want a 16-bit timer that runs continuously; that is to say, it is not dependent on any external pins. We must first initialize the TMOD SFR. Since we are working with timer 0 we will be using the lowest 4 bits of TMOD. The first two bits, GATE0 and C/T0 are both 0 since we want the timer to be independent of the external pins. 16-bit mode is timer mode 1 so we must clear T0M1 and set T0M0. Effectively, the only bit we want to turn on is bit 0 of TMOD. Thus to initialize the timer we execute the instruction: MOV TMOD,#01h Timer 0 is now in 16-bit timer mode. However, the timer is not running. To start the timer running we must set the TR0 bit We can do that by executing the instruction: SETB TR0

Upon executing these two instructions timer 0 will immediately begin counting, being incremented once every machine cycle (every 12 crystal pulses). Reading the Timer There are two common ways of reading the value of a 16-bit timer; which you use depends on your specific application. You may either read the actual value of the timer as a 16-bit number, or you may simply detect when the timer has overflowed. Reading the value of a Timer If your timer is in an 8-bit mode--that is, either 8-bit AutoReload mode or in split timer mode-then reading the value of the timer is simple. You simply read the 1-byte value of the timer and youre done. However, if youre dealing with a 13-bit or 16-bit timer the chore is a little more complicated. Consider what would happen if you read the low byte of the timer as 255, then read the high byte of the timer as 15. In this case, what actually happened was that the timer value was 14/255 (high byte 14, low byte 255) but you read 15/255. Why? Because you read the low byte as 255. But when you executed the next instruction a small amount of time passed--but enough for the timer to increment again at which time the value rolled over from 14/255 to 15/0. But in the process youve read the timer as being 15/255. Obviously theres a problem there. The solution? Its not too tricky, really. You read the high byte of the timer, then read the low byte, then read the high byte again. If the high byte read the second time is not the same as the high byte read the first time you repeat the cycle. In code, this would appear as:
REPEAT: MOV A,TH0 MOV R0,TL0 CJNE A,TH0,REPEAT ...

In this case, we load the accumulator with the high byte of Timer 0. We then load R0 with the low byte of Timer 0. Finally, we check to see if the high byte we read out of Timer 0--which is now stored in the Accumulator--is the same as the current Timer 0 high byte. If it isnt it means weve just "rolled over" and must reread the timers value--which we do by going back to REPEAT. When the loop exits we will have the low byte of the timer in R0 and the high byte in the Accumulator. Another much simpler alternative is to simply turn off the timer run bit (i.e. CLR TR0), read the timer value, and then turn on the timer run bit (i.e. SETB TR0). In that case, the timer isnt running so no special tricks are necessary. Of course, this implies that your timer will be stopped for a few machine cycles. Whether or not this is tolerable depends on your specific application. Detecting Timer Overflow

Often it is necessary to just know that the timer has reset to 0. That is to say, you are not particularly interest in the value of the timer but rather you are interested in knowing when the timer has overflowed back to 0. Whenever a timer overflows from its highest value back to 0, the microcontroller automatically sets the TFx bit in the TCON register. This is useful since rather than checking the exact value of the timer you can just check if the TFx bit is set. If TF0 is set it means that timer 0 has overflowed; if TF1 is set it means that timer 1 has overflowed. We can use this approach to cause the program to execute a fixed delay. As youll recall, we calculated earlier that it takes the 8051 1/20th of a second to count from 0 to 46,079. However, the TFx flag is set when the timer overflows back to 0. Thus, if we want to use the TFx flag to indicate when 1/20th of a second has passed we must set the timer initially to 65536 less 46079, or 19,457. If we set the timer to 19,457, 1/20th of a second later the timer will overflow. Thus we come up with the following code to execute a pause of 1/20th of a second: MOV TH0,#76;High byte of 19,457 (76 * 256 = 19,456) MOV TL0,#01;Low byte of 19,457 (19,456 + 1 = 19,457) MOV TMOD,#01;Put Timer 0 in 16-bit mode SETB TR0;Make Timer 0 start counting JNB TF0,$;If TF0 is not set, jump back to this same instruction In the above code the first two lines initialize the Timer 0 starting value to 19,457. The next two instructions configure timer 0 and turn it on. Finally, the last instruction JNB TF0,$, reads "Jump, if TF0 is not set, back to this same instruction." The "$" operand means, in most assemblers, the address of the current instruction. Thus as long as the timer has not overflowed and the TF0 bit has not been set the program will keep executing this same instruction. After 1/20th of a second timer 0 will overflow, set the TF0 bit, and program execution will then break out of the loop. Timing the length of events The 8051 provides another cool toy that can be used to time the length of events. For example, let's say we're trying to save electricity in the office and we're interested in how long a light is turned on each day. When the light is turned on, we want to measure time. When the light is turned off we don't. One option would be to connect the lightswitch to one of the pins, constantly read the pin, and turn the timer on or off based on the state of that pin. While this would work fine, the 8051 provides us with an easier method of accomplishing this. Looking again at the TMOD SFR, there is a bit called GATE0. So far we've always cleared this bit because we wanted the timer to run regardless of the state of the external pins. However, now it would be nice if an external pin could control whether the timer was running or not. It can. All we need to do is connect the lightswitch to pin INT0 (P3.2) on the 8051 and set the bit GATE0. When GATE0 is set Timer 0 will only run if P3.2 is high. When P3.2 is low (i.e., the lightswitch is off) the timer will automatically be stopped.

Thus, with no control code whatsoever, the external pin P3.2 can control whether or not our timer is running or not. USING TIMERS AS EVENT COUNTERS We've discussed how a timer can be used for the obvious purpose of keeping track of time. However, the 8051 also allows us to use the timers to count events. How can this be useful? Let's say you had a sensor placed across a road that would send a pulse every time a car passed over it. This could be used to determine the volume of traffic on the road. We could attach this sensor to one of the 8051's I/O lines and constantly monitor it, detecting when it pulsed high and then incrementing our counter when it went back to a low state. This is not terribly difficult, but requires some code. Let's say we hooked the sensor to P1.0; the code to count cars passing would look something like this:
JNB P1.0,$ ;If a car hasn't raised the signal, keep waiting JB P1.0,$ ;The line is high which means the car is on the sensor right now INC COUNTER ;The car has passed completely, so we count it

As you can see, it's only three lines of code. But what if you need to be doing other processing at the same time? You can't be stuck in the JNB P1.0,$ loop waiting for a car to pass if you need to be doing other things. Of course, there are ways to get around even this limitation but the code quickly becomes big, complex, and ugly. Luckily, since the 8051 provides us with a way to use the timers to count events we don't have to bother with it. It is actually painfully easy. We only have to configure one additional bit. Let's say we want to use Timer 0 to count the number of cars that pass. If you look back to the bit table for the TCON SFR you will there is a bit called "C/T0"--it's bit 2 (TCON.2). Reviewing the explanation of the bit we see that if the bit is clear then timer 0 will be incremented every machine cycle. This is what we've already used to measure time. However, if we set C/T0 timer 0 will monitor the P3.4 line. Instead of being incremented every machine cycle, timer 0 will count events on the P3.4 line. So in our case we simply connect our sensor to P3.4 and let the 8051 do the work. Then, when we want to know how many cars have passed, we just read the value of timer 0--the value of timer 0 will be the number of cars that have passed. So what exactly is an event? What does timer 0 actually "count?" Speaking at the electrical level, the 8051 counts 1-0 transitions on the P3.4 line. This means that when a car first runs over our sensor it will raise the input to a high ("1") condition. At that point the 8051 will not count anything since this is a 0-1 transition. However, when the car has passed the sensor will fall back to a low ("0") state. This is a 1-0 transition and at that instant the counter will be incremented by 1. It is important to note that the 8051 checks the P3.4 line each instruction cycle (12 clock cycles). This means that if P3.4 is low, goes high, and goes back low in 6 clock cycles it will probably not be detected by the 8051. This also means the 8051 event counter is only capable of counting events that occur at a maximum of 1/24th the rate of the crystal frequency. That is to say, if the

crystal frequency is 12.000 Mhz it can count a maximum of 500,000 events per second (12.000 Mhz * 1/24 = 500,000). If the event being counted occurs more than 500,000 times per second it will not be able to be accurately counted by the 8051.

Previous: Low-Level Information/Timing

Tutorial Contents

Next: Serial Port Operation

What is a Timer
Timer is a clock that controls the sequence of an event while counting in fixed intervals of time. A Timer is used for producing precise time delay. Secondly, it can be used to repeat or initiate an action after/at a known period of time. This feature is very commonly used in several applications. An example could be setting up an alarm which triggers at a point of time or after a period of time.

Timers in a controller: Why to use them


Most of the microcontrollers have inbuilt Timers. Timers in a controller not only generate time delays but they can also be used as counters. They are used to count an action or event. The value of counter increases by one, every time its corresponding action or event occurs. Timers in a controller are inbuilt chips that are controlled by special function registers (SFRs) assigned for Timer operations. These SFRs are used to configure Timers in different modes of operations. While working with microcontrollers, it is more than often required to generate time delays. There are two possible ways of generating time delays. First is by using the code, like using for or while loops in a C program. However, the delays provided by the software are not very precise. The other method is to use Timers. Timers provide time delays that are very precise and accurate. The programming of 8051 Timers can be done by using either polling method or by using interrupt. In polling, the microcontroller keeps monitoring the status of Timer flag. While doing so, it does no other operation and consumes all its processing time in checking the Timer flag until it is raised on a rollover. In interrupt method controller responds to only when the Timer flag is raised. The interrupt method prevents the wastage of controllers processing time unlike polling method. Polling is mostly used for time delay generation and interrupt method is more useful when waveforms are to be generated or some action has to be repeated in fixed delays. (i) Polling Method The polling method involves the following algorithm:

1. Configure the Timer mode by passing a hex value into the TMOD register. This will tell the controller about which Timer is be used; the mode of Timer; operation (to be used as timer or counter); and whether external interrupt is required to start Timer. 2. Load the initial values in the Timer low TLx and high THx byte. (x = 0/1) 3. Start the Timer by setting TRx bit. 4. Wait while the Timer flag TFx is raised. 5. Clear the Timer flag. The Timer flag is raised when Timer rolls over from FFFFH to 0000H. If the Timer is not stopped, it will start updating from 0000H in case of modes 0 & 1 while with initial value in case of mode 2. If TFx is not cleared, controller will not be able to detect next rollover. 6. Stop the Timer by clearing TRx bit. If TRx bit is not cleared the Timer will restart updating from 0000H after the rollover in case of modes 0 and 1 while with initial value in case of mode 2. (ii) Interrupt Method The interrupt method makes use of a register called Interrupt Enable (IE) register. An 8051 microcontroller has 6 hardware interrupts. The interrupts refer to a notification, communicated to the controller, by a hardware device or software, on receipt of which controller skips temporarily whatsoever it was doing and responds to the interrupt. The controller starts the execution of an Interrupt Service Routine (ISR) or Interrupt Handler which is a piece of code that tells the processor or controller what to do on receipt of an interrupt. After the execution of ISR, controller returns to whatever it was doing earlier (before the interrupt was received). The Interrupt Enable register has the following bits which enable or disable the hardware interrupts of 8051 microcontroller.

When EA (IE.7) is set (=1), interrupts are enabled. When clear (EA=0), interrupts are disabled and controller does not respond to any interrupts. ET0, ET1 & ET2 (IE.3, IE.4 & IE.5) are Timer interrupt bits. When set (high) the timer are enabled and when cleared (low) they are disabled. (8052 controllers have three Timers, so ET2 is its Timer 2 interrupt bit.) The ISR corresponding to these interrupts are executed when the TFx flags of respective Timers are raised. For more details on other IE register bits, refer Interrupts with 8051. Note that IE register is bit addressable. Timer programming using Timer interrupts involves following algorithm. 1. Configure the Timer mode by passing a hex value to TMOD register. 2. Load the initial values in the Timer low TLx and high THx byte.

3. Enable the Timer interrupt by passing hex value to IE register or setting required bits of IE register. For example, IE = 0x82; enables Timer 0 interrupt IE = 0x88; enables Timer 1 interrupt or EA = 1; ET0 = 1; IE^7 = 1; IE^3 = 1;

enables Timer 0 interrupt

enables Timer 1 interrupt

4. Start the Timer by setting TRx bit. 5. Write Interrupt Service Routine (ISR) for the Timer interrupt. For example,

ISR definition for Timer 0 : void ISR_Timer0(void) interrupt 1 { <Body of ISR> } ISR definition for Timer 1 : void ISR_Timer1(void) interrupt 3 { <Body of ISR> }

6. If the Timer has to be stopped after once the interrupt has occurred, the ISR must contain the statement to stop the Timer. For example, void ISR_Timer1(void) interrupt 3 { <Body of ISR> TR1 =0; } 7. If a routine written for Timer interrupt has to be repeated again and again, the Timer run bit need not be cleared. But it should be kept in mind that Timer will start updating from 0000H and not the initial values in case of mode 0 and 1. So the initial values must be reloaded in the interrupt service routine. For example, void ISR_Timer1(void) interrupt 3 { <Body of ISR>

TH1 =0XFF; TL1 }


EngineersGarage

//load with initial values if in mode 0 or 1 = 0xFC;

Home Insight EG Labs


o

o o o

Microcontroller 8051 AVR PIC Arduino Electronic Circuits Components Tutorials

Articles Invention Stories Forum Knowledge Base o Projects o Blogs o How to o Guest Column DMohanKumar o C-Programs Advertise Submit Contact Us

Timers & 8051 Timer Programming


TUT003 Table of Contents: 1. 2. 3. 4. 5. 6. Timers & 8051 Timer Programming 8051 Timers and Registers How a Timer functions Configuring a Timer Programming 8051 Timer Different modes of a Timer

Different modes of a Timer


There are four Timer modes designated as Modes 0, 1, 2 and 3. A particular mode is selected by configuring the M1 & M0 bits of TMOD register. Mode Mode 0 Mode 1 Mode 2 Mode 3 M1 0 0 1 1 M0 0 1 0 1 Operation 13-bit Timer 16-bit Timer 8-bit Auto Reload Split Timer Mode

(i) Mode 0 : 13-bit Timer

Mode 0 is a 13 bit Timer mode and uses 8 bits of high byte and 5 bit prescaler of low byte. The value that the Timer can update in mode0 is from 0000H to 1FFFH. The 5 bits of lower byte append with the bits of higher byte. The Timer rolls over from 1FFFH to 0000H to raise the Timer flag.

(ii) Mode 1 : 16-bit Timer

Mode1 is one of the most commonly used Timer modes. It allows all 16 bits to be used for the Timer and so it allows values to vary from 0000H to FFFFH.

If a value, say YYXXH, is loaded into the Timer bytes, then the delay produced by the Timer will be equal to the product : [ ( FFFFH YYXXH +1 ) x ( period of one timer clock ) ].

It can also be considered as follows: convert YYXXH into decimal, say NNNNN, then delay will be equal to the product :

[ ( 65536-NNNNN ) x ( period of one timer clock ) ]. The period of one timer clock is 1.085 s for a crystal of 11.0592 MHz frequency as discussed above.

Now to produce a desired delay, divide the required delay by the Timer clock period. Assume that the division yields a number NNNNN. This is the number of times Timer must be updated before it stops. Subtract this number from 65536 (binary equivalent of FFFFH) and convert the difference into hex. This will be the initial value to be loaded into the Timer to get the desired delay. The calculator application in Windows can be a handy tool to carry out these calculations.

Example code Time delay in Mode1 using polling method

// Use of Timer mode 1 for blinking LED using polling method // XTAL frequency 11.0592MHz #include<reg51.h> sbit led = P1^0; // LED connected to 1st pin of port P1 void delay(); main() { unsigned while(1) { led=~led; for(i=0;i<1000;i++) delay(); } } void delay() Timer 0 { TMOD = 0x01; TH0= 0xFC; value for TL0 TR0 = 1; while(TF0 == 0); // Delay generation using mode 1 // Mode1 of Timer0 // FC66 evaluated hex 1millisecond delay = 0x66; // Start Timer // Using polling method int // // Toggle Call i; LED delay

TR0 = 0; TF0 = 0; }
Example code Time delay in Mode1 using interrupt method

// //

Stop Clear

Timer flag

// Use of Timer mode 1 for blinking LED with interrupt method // XTAL frequency 11.0592MHz #include<reg51.h> sbit LED = P1^0; // LED connected to 1st pin of port P1 void Timer(void) interrupt 1 // Interrupt No.1 for Timer 0 { led=~led; // Toggle LED on interrupt } main() { TMOD = 0x01; TH0=0x00; to Timer TL0=0x00; IE = 0x82; TR0=1; while(1); }
(iii) Mode 2 : 8-bit Auto Reload Mode 2 is an 8 bit mode. The initial value is loaded into the higher byte. A copy of the same is passed to the lower byte. The Timer can update from 00H to FFH. The Timer rolls over from FFH to initial value automatically. Mode 2 is commonly used for setting baud rates for serial communication.

// Mode1 of Timer0 // Initial values loaded // Enable interrupt // Start Timer // Do nothing

Example code Time delay in Mode2 using polling method

// Use of Timer mode 2 for blinking LED with polling method // XTAL frequency 11.0592MHz #include<reg51.h>

sbit led = P1^0; pin of port main() { unsigned while(1) { led=~led; for(i=0;i<1000;i++) delay(); } } void { TMOD = 0x02; TH0= 0xA2; Timer TR0 = 1; while(TF0 == 0); TR0 = 0; TF0 = 0; } (iv) Mode 3 : Split Timer

//

LED connected to 1st P1void delay(); i;

int // Toggle LED // Call

delay

delay() // Mode1 of Timer0 // Initial value loaded to // // // // Start Polling for Stop Clear Timer flag bit Timer flag

In mode 3, also known as split mode, the Timer breaks into two 8-bit Timers that can count from 00H up to FFH. The initial values are loaded into the higher byte and lower byte of the Timer. In this case the start and flag bits associated with the other Timer are now associated with high byte Timer. So one cannot start or stop the other Timer. The other Timer can be used in modes 0, 1 or 2 and is updated automatically for every machine cycle.

For example, if Timer0 is used in split mode, TH0 and TL0 will become separate Timers. The start and flag bits associated with Timer1 will now be associated with the TH0. Timer 1 cannot be stopped or started, but will be updated for every machine cycle. Split mode is useful when two Timers are required in addition to a baud rate generator.

106444 reads

Join us on Facebook for latest updates User login


Username or e-mail: * Password: *

Create new account Request new password

Insight-Discover how Gadgets work?


Adapter Banana Jack Electric Beard Trimmer HDMI Cable Membrane Keypad Micro Switch Scientific Calculator SMPS Telephone Turbidity Sensor USB Connector ...more

Related Content
Microcontrollers 8051 and 8051 Microcontroller AVR Microcontroller PIC Microcontroller Arduino : What is Arduino

You are here Home


Top

Copyright 2012 EngineersGarage. All rights reserved. Privacy Policy | Refund Policy | About Us

You might also like