This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

Showing posts with label 8051 Programming. Show all posts
Showing posts with label 8051 Programming. Show all posts

Sunday, 27 January 2013

SERIAL COMMUNICATION

SERIAL COMMUNICATION

BASICS OF SERIAL COMMUNICATION:

Computers transfer data in two ways:
  • Parallel
    • Often 8 or more lines (wire conductors) are used to transfer data to a device that is only a few feet away
  • Serial
    • To transfer to a device located many meters away, the serial method is used
    • The data is sent one bit at a time
  • At the transmitting end, the byte of data must be converted to serial bits using parallel-in-serial-out shift register
  • At the receiving end, there is a serialin- parallel-out shift register to receive the serial data and pack them into byte
  • When the distance is short, the digital signal can be transferred as it is on a simple wire and requires no modulation
  • If data is to be transferred on the telephone line, it must be converted from 0s and 1s to audio tones
    • This conversion is performed by a device called a modem, “Modulator/demodulator”


Methods of Serial Communication:

Serial data communication uses two methods
  • Synchronous method transfers a block of data at a time
  • Asynchronous method transfers a single byte at a time

Half- and Full- Duplex Transmission

If data can be transmitted and received, it is a duplex transmission
  • If data transmitted one way a time, it is referred to as half duplex
  • If data can go both ways at a time, it is full duplex
  • This is contrast to simplex transmission

Data Transfer Rate

  • The rate of data transfer in serial data communication is stated in bps (bits per second)
    • Another widely used terminology for bps is baud rate
    • It is modem terminology and is defined as the number of signal changes per second
    • In modems, there are occasions when a single change of signal transfers several bits of data
Example:
With XTAL = 11.0592 MHz, find the TH1 value needed to have the following baud rates. (a) 9600 (b) 2400 (c) 1200
Solution:
The machine cycle frequency of 8051 = 11.0592 / 12 = 921.6 kHz, and 921.6 kHz / 32 = 28,800 Hz is frequency by UART to timer 1 to set baud rate.
  1. 28,800 / 3 = 9600 where -3 = FD (hex) is loaded into TH1
  2. 28,800 / 12 = 2400 where -12 = F4 (hex) is loaded into TH1
  3. 28,800 / 24 = 1200 where -24 = E8 (hex) is loaded into TH1
Notice that dividing 1/12 of the crystal frequency by 32 is the default value upon activation of the 8051 RESET pin.

SBUF Register

  • SBUF is an 8-bit register used solely for serial communication
    • For a byte data to be transferred via the TxD line, it must be placed in the SBUF register
      • The moment a byte is written into SBUF, it is framed with the start and stop bits and transferred serially via the TxD line
  • SBUF holds the byte of data when it is received by 8051 RxD line
    • When the bits are received serially via RxD, the 8051 deframes it by eliminating the stop and start bits, making a byte out of the data received, and then placing it in SBUF
Example:
MOV SBUF,#’D’         ;load SBUF=44h, ASCII for ‘D’
MOV SBUF,A              ;copy accumulator into SBUF
MOV A,SBUF              ;copy SBUF into accumulator

SCON Register

SCON is an 8-bit register used to program the start bit, stop bit, and data bits of data framing, among other things
SM0
SCON.7
Serial port mode specifier
SM1
SCON.6
Serial port mode specifier
SM2
SCON.5
Used for multiprocessor communication
REN
SCON.4
Set/cleared by software to enable/disable reception
TB8
SCON.3
Not widely used
RB8
SCON.2
Not widely used
TI
SCON.1
Transmit interrupt flag. Set by HW at the begin of the stop bit mode 1. And cleared by SW
RI
SCON.0
Receive interrupt flag. Set by HW at the begin of the stop bit mode 1. And cleared by SW
Note:    Make SM2, TB8, and RB8 =0

SM0, SM1
  • They determine the framing of data by specifying the number of bits per character, and the start and stop bits
  • Only MODE1 is of our interest. 
SM0
SM1

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

SM2
  • This enables the multiprocessing capability of the 8051
REN (receive enable)
  • It is a bit-adressable register
    • When it is high, it allows 8051 to receive data on RxD pin
    • If low, the receiver is disable
TI (transmit interrupt)
  • When 8051 finishes the transfer of 8-bit character
    • It raises TI flag to indicate that it is ready to transfer another byte
    • TI bit is raised at the beginning of the stop bit
RI (receive interrupt)
  • When 8051 receives data serially via RxD, it gets rid of the start and stop bits and places the byte in SBUF register
    • It raises the RI flag bit to indicate that a byte has been received and should be picked up before it is lost
    • RI is raised halfway through the stop bit

Programming Serial Data Transmitting

In programming the 8051 to transfer character bytes serially
  1. TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode 2 (8-bit auto-reload) to set baud rate
  2. The TH1 is loaded with one of the values to set baud rate for serial data transfer
  3. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8- bit data is framed with start and stop bits
  4. TR1 is set to 1 to start timer 1
  5. TI is cleared by CLR TI instruction
  6. The character byte to be transferred serially is written into SBUF register
  7. The TI flag bit is monitored with the use of instruction JNB TI,xx to see if the character has been transferred completely
  8. To transfer the next byte, go to step 5
Example:
Write a program for the 8051 to transfer letter “A” serially at 4800 baud, continuously.
Solution:
MOV TMOD,#20H            ;timer 1,mode 2(auto reload)
MOV TH1,#-6                    ;4800 baud rate
MOV SCON,#50H             ;8-bit, 1 stop, REN enabled
SETB TR1                           ;start timer 1
AGAIN:
MOV SBUF,#”A”               ;letter “A” to transfer
HERE:
JNB TI,HERE                      ;wait for the last bit
CLR TI                                ;clear TI for next char
SJMP AGAIN                     ;keep sending A

Example:
Write a program for the 8051 to transfer “YES” serially at 9600 baud, 8-bit data, 1 stop bit, do this continuously
Solution:
MOV TMOD,#20H            ;timer 1,mode 2(auto reload)
MOV TH1,#-3                     ;9600 baud rate
MOV SCON,#50H             ;8-bit, 1 stop, REN enabled
SETB TR1                            ;start timer 1
AGAIN:
MOV A,#”Y”                       ;transfer “Y”
ACALL TRANS
MOV A,#”E”                       ;transfer “E”
ACALL TRANS
MOV A,#”S”                       ;transfer “S”
ACALL TRANS
SJMP AGAIN                      ;keep doing it
         ;serial data transfer subroutine
TRANS:
MOV SBUF,A                     ;load SBUF
HERE:
JNB TI,HERE                       ;wait for the last bit
CLR TI                                  ;get ready for next byte
RET 

Importance of TI Flag


The steps that 8051 goes through in transmitting a character via TxD
  • The byte character to be transmitted is written into the SBUF register
  • The start bit is transferred
  • The 8-bit character is transferred on bit at a time
  • The stop bit is transferred
    • It is during the transfer of the stop bit that 8051 raises the TI flag, indicating that the last character was transmitted
  • By monitoring the TI flag, we make sure that we are not overloading the SBUF
    • If we write another byte into the SBUF before TI is raised, the untransmitted portion of the previous byte will be lost
  • After SBUF is loaded with a new byte, the TI flag bit must be forced to 0 by CLR TI in order for this new byte to be transferred
By checking the TI flag bit, we know whether or not the 8051 is ready to transfer another byte
  • It must be noted that TI flag bit is raised by 8051 itself when it finishes data transfer
  • It must be cleared by the programmer with instruction CLR TI
  • If we write a byte into SBUF before the TI flag bit is raised, we risk the loss of a portion of the byte being transferred
The TI bit can be checked by
  • The instruction JNB TI,xx
  • Using an interrupt

Programming Serial Data Receiving

In programming the 8051 to receive character bytes serially
  1. TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode
  2. (8-bit auto-reload) to set baud rate
  3. TH1 is loaded to set baud rate
  4. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8- bit data is framed with start and stop bits
  5. TR1 is set to 1 to start timer 1
  6. RI is cleared by CLR RI instruction
  7. The RI flag bit is monitored with the use of instruction JNB RI,xx to see if an entire character has been received yet
  8. When RI is raised, SBUF has the byte, its contents are moved into a safe place
  9. To receive the next character, go to step 5
Example:
Write a program for the 8051 to receive bytes of data serially, and put them in P1, set the baud rate at 4800, 8-bit data, and 1 stop bit

Solution:
MOV TMOD,#20H            ;timer 1,mode 2(auto reload)
MOV TH1,#-6                    ;4800 baud rate
MOV SCON,#50H             ;8-bit, 1 stop, REN enabled
SETB TR1                           ;start timer 1
HERE:
JNB RI,HERE                      ;wait for char to come in
MOV A,SBUF                     ;saving incoming byte in A
MOV P1,A                           ;send to port 1
CLR RI                                 ;get ready to receive next byte
SJMP HERE                         ;keep getting data

Example:
Assume that the 8051 serial port is connected to the COM port of IBM PC, and on the PC, we are using the terminal.exe program to send and receive data serially. P1 and P2 of the 8051 are connected to LEDs and switches, respectively. Write an 8051 program to (a) send to PC the message “We Are Ready”, (b) receive any data send by PC and put it on LEDs connected to P1, and (c) get data on switches connected to P2 and send it to PC serially. The program should perform part (a) once, but parts (b) and (c) continuously, use 4800 baud rate.



ORG 0
MOV P2,#0FFH                 ;make P2 an input port
MOV TMOD,#20H            ;timer 1, mode 2
MOV TH1,#0FAH              ;4800 baud rate
MOV SCON,#50H             ;8-bit, 1 stop, REN enabled
SETB TR1                              ;start timer 1
MOV DPTR,#MYDATA    ;load pointer for message
H_1:
CLR A
MOV A,@A+DPTR           ;get the character
JZ B_1                                ;if last character get out
ACALL SEND                    ;otherwise call transfer
INC DPTR                          ;next one
SJMP H_1                          ;stay in loop
B_1:
MOV a,P2                          ;read data on P2
ACALL SEND                   ;transfer it serially
ACALL RECV                   ;get the serial data
MOV P1,A                         ;display it on LEDs
SJMP B_1                          ;stay in loop indefinitely
;----serial data transfer. ACC has the data------
SEND:
MOV SBUF,A                   ;load the data
H_2:
JNB TI,H_2                       ;stay here until last bit gone
CLR TI                              ;get ready for next char
RET ;return to caller
;----Receive data serially in ACC----------------
RECV:
JNB RI,RECV                   ;wait here for char
MOV A,SBUF                  ;save it in ACC
CLR RI                             ;get ready for next char
RET                                  ;return to caller
;-----The message---------------
MYDATA: DB “We Are Ready”,0
END

Importance of RI Flag

In receiving bit via its RxD pin, 8051 goes through the following steps
  • It receives the start bit
    • Indicating that the next bit is the first bit of the character byte it is about to receive
  • The 8-bit character is received one bit at time
  • The stop bit is received
    • When receiving the stop bit 8051 makes RI = 1, indicating that an entire character byte has been received and must be picked up before it gets overwritten by an incoming character
  • By checking the RI flag bit when it is raised, we know that a character has been received and is sitting in the SBUF register
    • We copy the SBUF contents to a safe place in some other register or memory before it is lost
  • After the SBUF contents are copied into a safe place, the RI flag bit must be forced to 0 by CLR RI in order to allow the next received character byte to be placed in SBUF
    • Failure to do this causes loss of the received character
By checking the RI flag bit, we know whether or not the 8051 received a character byte
  • If we failed to copy SBUF into a safe place, we risk the loss of the received byte
  • It must be noted that RI flag bit is raised by 8051 when it finish receive data
  • It must be cleared by the programmer with instruction CLR RI
  • If we copy SBUF into a safe place before the RI flag bit is raised, we risk copying garbage
  • The RI bit can be checked by
    • The instruction JNB RI,xx
    • Using an interrupt

Doubling Baud Rate

There are two ways to increase the baud rate of data transfer
  • To use a higher frequency crystal (The System Crystel is Fix)
  • To change a bit in the PCON register
PCON register is an 8-bit register
  • When 8051 is powered up, SMOD is zero
  • We can set it to high by software and thereby double the baud rate
MOV A,PCON         ;place a copy of PCON in ACC
SETB ACC.7            ;make D7=1
MOV PCON,A         ;changing any other bits

Example:
Assume that XTAL = 11.0592 MHz for the following program, state (a) what this program does, (b) compute the frequency used by timer 1 to set the baud rate, and (c) find the baud rate of the data transfer.
MOV A,PCON              ;A=PCON
MOV ACC.7                 ;make D7=1
MOV PCON,A              ;SMOD=1, double baud rate
   ;with same XTAL freq.
MOV TMOD,#20H       ;timer 1, mode 2
MOV TH1,-3                  ;19200 (57600/3 =19200)
MOV SCON,#50H         ;8-bit data, 1 stop bit, RI enabled
SETB TR1                      ;start timer 1
MOV A,#”B”                  ;transfer letter B
A_1:
CLR TI                            ;make sure TI=0
MOV SBUF,A                ;transfer it
H_1:
JNB TI,H_1                    ;stay here until the last bit is gone
SJMP A_1                      ;keep sending “B” again
Solution:
(a) This program transfers ASCII letter B (01000010 binary) continuously
(b) With XTAL = 11.0592 MHz and SMOD = 1 in the above program, we have: 
11.0592 / 12 = 921.6 kHz machine cycle frequency. 921.6 / 16 = 57,600 Hz frequency used by timer 1 to set the baud rate. 57600 / 3 = 19,200, the baud rate. 

TIMER and COUNTER PROGRAMMING

Timers/Counters Programming

  • The 8051 has two timers/counters, they can be used either as
    • Timers to generate a time delay or as
    • Event counters to count events happening outside the microcontroller
  • Both Timer 0 and Timer 1 are 16 bits wide
    • Since 8051 has an 8-bit architecture, each 16-bits timer is accessed as two separate registers of low byte and high byte
      • The low byte register is called TL0/TL1 
      • The high byte register is called TH0/TH1

TMOD Register

Both timers 0 and 1 use the same register, called TMOD (timer mode), to set the various timer operation modes
  • TMOD is a 8-bit register
    • The lower 4 bits are for Timer 0
    • The upper 4 bits are for Timer 1
    • In each case,
      • The lower 2 bits are used to set the timer mode
      • The upper 2 bits to specify the operation
Modes of Operation:
M0
M1
Mode
Operating mode
0
0
0
13-bit timer mode
8-bit timer/counter THx with TLx as 5-bit prescaler
0
1
1
16-bit timer mode
16-bit timer/counter THx and TLx are cascaded; there is no prescaler
1
0
2
8-bit auto reload
8-bit auto reload timer/counter; THx holds a value which is to be reloaded TLx each time it overfolws
1
1
3
Split timer mode
  • C/T : Timer or counter selected
    • Cleared for timer operation (input from internal system clock)
    • Set for counter operation (input from Tx input pin)
  • GATE:Gating control when set.
    • Timer/counter is enable only while the INTx pin is high and the TRx control pin is set
    • When cleared, the timer is enabled whenever the TRx control bit is set
Timers of 8051 do starting and stopping by either software or hardware control
  • In using software to start and stop the timer where GATE=0
  • The start and stop of the timer are controlled by way of software by the TR (timer start) bits TR0 and TR1
    • The SETB instruction starts it, and it is stopped by the CLR instruction
    • These instructions start and stop the timers as long as GATE=0 in the TMOD register
  • The hardware way of starting and stopping the timer by an external source is achieved by making GATE=1 in the TMOD register

Case of GATE = 1

  • If GATE = 1, the start and stop of the timer are done externally through pins P3.2 and P3.3 for timers 0 and 1, respectively
  • This hardware way allows to start or stop the timer externally at any time via a simple switch

Mode 1 Programming

The following are the characteristics and operations of mode1:
  • It is a 16-bit timer; therefore, it allows value of 0000 to FFFFH to be loaded into the timer’s register TL and TH
  • After TH and TL are loaded with a 16-bit initial value, the timer must be started
    • This is done by SETB TR0 for timer 0 and SETB TR1 for timer 1
  • After the timer is started, it starts to count up
    • It counts up until it reaches its limit of FFFFH
  • When it rolls over from FFFFH to 0000, it sets high a flag bit called TF (timer flag)
    •  Each timer has its own timer flag: TF0 for timer 0, and TF1 for timer 1
    •  This timer flag can be monitored
  • When this timer flag is raised, one option would be to stop the timer with the instructions CLR TR0 or CLR TR1, for timer 0 and timer 1, respectively
  • After the timer reaches its limit and rolls over, in order to repeat the process
    • TH and TL must be reloaded with the original value, and
    • TF must be reloaded to 0

Steps to Mode 1 Program

To generate a time delay
  • Load the TMOD value register indicating which timer (timer 0 or timer 1) is to be used and which timer mode (0 or 1) is selected
  • Load registers TL and TH with initial count value
  • Start the timer
  • Keep monitoring the timer flag (TF) with the JNB TFx,target instruction to see if it is raised
    • Get out of the loop when TF becomes high
  • Stop the timer
  • Clear the TF flag for the next round
  • Go back to Step 2 to load TH and TL again
Example:
In the following program, we create a square wave of 50% duty cycle (with equal portions high and low) on the P1.5 bit. Timer 0 is used to generate the time delay. Analyze the program

MOV TMOD,#01                ;Timer 0, mode 1(16-bit mode)
HERE:
MOV TL0,#0F2H                ;TL0=F2H, the low byte
MOV TH0,#0FFH               ;TH0=FFH, the high byte
CPL P1.5                               ;toggle P1.5
ACALL DELAY
SJMP HERE

In the above program notice the following step.
1. TMOD is loaded.
2. FFF2H is loaded into TH0-TL0.
3. P1.5 is toggled for the high and low portions of the pulse.

DELAY:
SETB TR0              ;start the timer 0
AGAIN:
JNB TF0,AGAIN                 ;monitor timer flag 0
        ;until it rolls over
CLR TR0                 ;stop timer 0
CLR TF0                 ;clear timer 0 flag
RET

4. The DELAY subroutine using the timer is called.
5. In the DELAY subroutine, timer 0 is started by the SETB TR0 instruction.
6. Timer 0 counts up with the passing of each clock, which is provided by the crystal oscillator. As the timer counts up, it goes through the states of FFF3, FFF4, FFF5, FFF6, FFF7, FFF8, FFF9, FFFA, FFFB, and so on until it reaches FFFFH. One more clock rolls it to 0, raising the timer flag (TF0=1). At that point, the JNB instruction falls through.
7. Timer 0 is stopped by the instruction CLR TR0. The DELAY subroutine ends, and the process is repeated.
Notice that to repeat the process, we must reload the TL and TH registers, and start the process is repeated



Example:
Find the delay generated by timer 0 in the following code, using both of the Methods of Figure 9-4. Do not include the overhead due to instruction.

CLR P2.3                            ;Clear P2.3
MOV TMOD,#01               ;Timer 0, 16-bitmode
HERE:
MOV TL0,#3EH                 ;TL0=3Eh, the low byte
MOV TH0,#0B8H              ;TH0=B8H, the high byte
SETB P2.3                          ;SET high timer 0
SETB TR0                           ;Start the timer 0
AGAIN:
JNB TF0,AGAIN                ;Monitor timer flag 0
CLR TR0                             ;Stop the timer 0
CLR TF0                              ;Clear TF0 for next round
CLR P2.3

Solution:
(a) (FFFFH – B83E + 1) = 47C2H = 18370 in decimal and 18370 × 1.085 us = 19.93145 ms
(b) Since TH – TL = B83EH = 47166 (in decimal) we have 65536 – 47166 = 18370. This means that the timer counts from B38EH to FFFF. This plus Rolling over to 0 goes through a total of 18370 clock cycles, where each clock is 1.085 us in duration. Therefore, we have 18370 × 1.085 us = 19.93145 ms as the width of the pulse.


Example:
Modify TL and TH in Example above to get the largest time delay possible. Find the delay in ms. In your calculation, exclude the overhead due to the instructions in the loop.

Solution:
To get the largest delay we make TL and TH both 0. This will count up from 0000 to FFFFH and then roll over to zero.
CLR P2.3                            ;Clear P2.3
MOV TMOD,#01               ;Timer 0, 16-bitmode
HERE:
MOV TL0,#0                       ;TL0=0, the low byte
MOV TH0,#0                      ;TH0=0, the high byte
SETB P2.3                           ;SET high P2.3
SETB TR0                            ;Start timer 0
AGAIN:
JNB TF0,AGAIN                 ;Monitor timer flag 0
CLR TR0                              ;Stop the timer 0
CLR TF0                               ;Clear timer 0 flag
CLR P2.3
Making TH and TL both zero means that the timer will count from 0000 to FFFF, and then roll over to raise the TF flag. As a result, it goes through a total Of 65536 states. Therefore, we have delay =
(65536 - 0) × 1.085 us = 71.1065ms.

Example:
The following program generates a square wave on P1.5 continuously using timer 1 for a time delay. Find the frequency of the square wave if XTAL = 11.0592 MHz. In your calculation do not include the overhead due to Instructions in the loop.

MOV TMOD,#10               ;Timer 1, mod 1 (16-bitmode)
AGAIN:
 MOV TL1,#34H                 ;TL1=34H, low byte of timer
MOV TH1,#76H                  ;TH1=76H, high byte timer
SETB TR1                            ;start the timer 1
BACK:
JNB TF1,BACK                  ;till timer rolls over
CLR TR1                             ;stop the timer 1
CPL P1.5                             ;comp. p1. to get hi, lo
CLR TF1                             ;clear timer flag 1
SJMP AGAIN                     ;is not auto-reload

Solution:
Since FFFFH – 7634H = 89CBH + 1 = 89CCH and 89CCH = 35276 clock count and 35276 × 1.085 us = 38.274 ms for half of the square wave. The frequency = 13.064Hz. Also notice that the high portion and low portion of the square wave pulse are equal. In the above calculation, the overhead due to all the instruction in the loop is not included.

Finding the Loaded Timer Values

To calculate the values to be loaded into the TL and TH registers, look at the following example
  • Assume XTAL = 11.0592 MHz, we can use the following steps for finding the TH, TL registers’ values
  1. Divide the desired time delay by 1.085 us
  2. Perform 65536 – n, where n is the decimal value we got in Step1
  3. Convert the result of Step2 to hex, where yyxx is the initial hex value to be loaded into the timer’s register
  4. Set TL = xx and TH = yy
Example:
Assume that XTAL = 11.0592 MHz. What value do we need to load the timer’s register if we want to have a time delay of 5 ms (milliseconds)? Show the program for timer 0 to create a pulse width of 5 ms on P2.3.
Solution:
Since XTAL = 11.0592 MHz, the counter counts up every 1.085 us. This means that out of many 1.085 us intervals we must make a 5 ms pulse. To get that, we divide one by the other. We need 5 ms / 1.085 us = 4608 clocks. To Achieve that we need to load into TL and TH the value 65536 – 4608 = EE00H. Therefore, we have TH = EE and TL = 00.

CLR P2.3                            ;Clear P2.3
MOV TMOD,#01               ;Timer 0, 16-bitmode
HERE:
MOV TL0,#0                      ;TL0=0, the low byte
MOV TH0,#0EEH              ;TH0=EE, the high byte
SETB P2.3                          ;SET high P2.3
SETB TR0                          ;Start timer 0
AGAIN:
JNB TF0,AGAIN               ;Monitor timer flag 0
CLR TR0                            ;Stop the timer 0
CLR TF0                            ;Clear timer 0 flag


Example:
Assume that XTAL = 11.0592 MHz, write a program to generate a square wave of 2 kHz frequency on pin P1.5.
Solution:
This is similar to Examples above, except that we must toggle the bit to generate the square wave. Look at the following steps.
(a) T = 1 / f = 1 / 2 kHz = 500 us the period of square wave.
(b) 1 / 2 of it for the high and low portion of the pulse is 250 us.
(c) 250 us / 1.085 us = 230 and 65536 – 230 = 65306 which in hex is FF1AH.
(d) TL = 1A and TH = FF, all in hex. The program is as follow.

MOV TMOD,#01               ;Timer 0, 16-bitmode
AGAIN:
MOV TL1,#1AH                ;TL1=1A, low byte of timer
MOV TH1,#0FFH              ;TH1=FF, the high byte
SETB TR1                           ;Start timer 1
BACK:
JNB TF1,BACK                 ;until timer rolls over
CLR TR1                            ;Stop the timer 1
CLR P1.5                           ;Clear timer flag 1
CLR TF1                            ;Clear timer 1 flag
SJMP AGAIN                    ;Reload timer

Example:
Assume XTAL = 11.0592 MHz, write a program to generate a square wave of 50 kHz frequency on pin P2.3.
Solution:
Look at the following steps.
(a) T = 1 / 50 = 20 ms, the period of square wave.
(b) 1 / 2 of it for the high and low portion of the pulse is 10 ms.
(c) 10 ms / 1.085 us = 9216 and 65536 – 9216 = 56320 in decimal, and in hex it is DC00H.
(d) TL = 00 and TH = DC (hex).

MOV TMOD,#10H            ;Timer 1, mod 1
AGAIN:
MOV TL1,#00                     ;TL1=00,low byte of timer
MOV TH1,#0DCH              ;TH1=DC, the high byte
SETB TR1                              ;Start timer 1
BACK:
JNB TF1,BACK                    ;until timer rolls over
CLR TR1                                ;Stop the timer 1
CLR P2.3                               ;Comp. p2.3 to get hi, lo
SJMP AGAIN                      ;Reload timer
;mode 1 isn’t auto-reload

Generating Large Time Delay

Example:

Examine the following program and find the time delay in seconds. Exclude the overhead due to the instructions in the loop.

MOV TMOD,#10H            ;Timer 1, mod 1
MOV R3,#200                    ;cnter for multiple delay
AGAIN:
MOV TL1,#08H                 ;TL1=08,low byte of timer
MOV TH1,#01H                ;TH1=01,high byte
SETB TR1                          ;Start timer 1
BACK:
JNB TF1,BACK                 ;until timer rolls over
CLR TR1                            ;Stop the timer 1
CLR TF1                            ;clear Timer 1 flag
DJNZ R3,AGAIN              ;if R3 not zero then
       ;reload timer
Solution:
TH-TL = 0108H = 264 in decimal and 65536 – 264 = 65272. Now 65272 × 1.085 μs = 70.820 ms, and for 200 of them we have 200 ×70.820 ms = 14.164024 seconds.

Mode 2 Programming

Characteriustics of Mode 2

The following are the characteristics and operations of mode 2:
  • It is an 8-bit timer; therefore, it allows only values of 00 to FFH to be loaded into the timer’s register TH
  • After TH is loaded with the 8-bit value, the 8051 gives a copy of it to TL
    • Then the timer must be started
    • This is done by the instruction SETB TR0 for timer 0 and SETB TR1 for timer 1
  • After the timer is started, it starts to count up by incrementing the TL register
    • It counts up until it reaches its limit of FFH
    • When it rolls over from FFH to 00, it sets high the TF (timer flag) When the TL register rolls from FFH to 0 and TF is set to 1, TL is reloaded automatically with the original value kept by the TH register
  • When the TL register rolls from FFH to 0 and TF is set to 1, TL is reloaded automatically with the original value kept by the TH register
    • To repeat the process, we must simply clear TF and let it go without any need by the programmer to reload the original value
    • This makes mode 2 an auto-reload, in contrast with mode 1 in which the programmer has to reload TH and TL

Steps to Mode 2 Program

To generate a time delay
  • Load the TMOD value register indicating which timer (timer 0 or timer 1) is to be used, and the timer mode (mode 2) is selected
  • Load the TH registers with the initial count value
  • Start timer
  • Keep monitoring the timer flag (TF) with the JNB TFx,target instruction to see whether it is raised
    • Get out of the loop when TF goes high
  • Clear the TF flag
  • Go back to Step4, since mode 2 is autoreload
Example:
Assume XTAL = 11.0592 MHz, find the frequency of the square wave generated on pin P1.0 in the following program

MOV TMOD,#20H            ;T1/8-bit/auto reload
MOV TH1,#5                     ;TH1 = 5
SETB TR1                          ;start the timer 1
BACK:
JNB TF1,BACK                ;till timer rolls over
CPL P1.0                           ;P1.0 to hi, lo
CLR TF1                           ;clear Timer 1 flag
SJMP BACK                     ;mode 2 is auto-reload

Solution:
First notice the target address of SJMP. In mode 2 we do not need to reload TH since it is auto-reload. Now (256 - 05) × 1.085 us = 251 × 1.085 us = 272.33 us is the high portion of the pulse. Since it is a 50% duty cycle square wave, the period T is twice that; as a result T = 2 × 272.33 us = 544.67 us and the frequency = 1.83597 kHz



Example:

Find the frequency of a square wave generated on pin P1.0.
Solution:
MOV TMOD,#2H          ;Timer 0, mod 2
   ;(8-bit, auto reload)
MOV TH0,#0
AGAIN:
MOV R5,#250                ;multiple delay count
ACALL DELAY
CPL P1.0
SJMP AGAIN
DELAY:
SETB TR0                       ;start the timer 0
BACK:
JNB TF0,BACK             ;stay timer rolls over
CLR TR0                        ;stop timer
CLR TF0                        ;clear TF for next round
DJNZ R5,DELAY
RET
T = 2 ( 250 × 256 × 1.085 us ) = 138.88ms, and frequency = 72 Hz 

COUNTER PROGRAMMING


Timers can also be used as counters counting events happening outside the 8051

  • When it is used as a counter, it is a pulse outside of the 8051 that increments the TH, TL registers
  • TMOD and TH, TL registers are the same as for the timer discussed previously

C/T Bit in TMOD Register

  • The C/T bit in the TMOD registers decides the source of the clock for the timer
    • When C/T = 1, the timer is used as a counter and gets its pulses from outside the 8051
    • The counter counts up as pulses are fed from pins 14 and 15, these pins are called T0 (timer 0 input) and T1 (timer 1 input)
Example:
Assuming that clock pulses are fed into pin T1, write a program for counter 1 in mode 2 to count the pulses and display the state of the TL1 count on P2, which connects to 8 LEDs.
Solution:
MOV TM0D,#01100000B     ;counter 1, mode 2,
;C/T=1 external pulses
MOV TH1,#0                          ;clear TH1
SETB P3.5                               ;make T1 input
AGAIN:
SETB TR1                               ;start the counter
BACK:
MOV A,TL1                            ;get copy of TL
MOV P2,A                              ;display it on port 2
JNB TF1,Back                         ;keep doing, if TF = 0
CLR TR1                                 ;stop the counter 1
CLR TF1                                 ;make TF=0
SJMP AGAIN                         ;keep doing it
Notice in the above program the role of the instruction SETB P3.5. Since ports are set up for output when the 8051 is powered up, we make P3.5 an input port by making it high. In other words, we must configure (set high) the T1 pin (pin P3.5) to allow pulses to be fed into it. 

TCON Register

TCON (timer control) register is an 8- bit register

  • The upper four bits are used to store the TF and TR bits of both timer 0 and 1
  • The lower 4 bits are set aside for controlling the interrupt bits