0% found this document useful (0 votes)
6 views11 pages

8051 Microcontroller Timer Programming

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

8051 Microcontroller Timer Programming

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT V

INTERFACING MICROCONTROLLER

5.1 Programming 8051 Timers:


One of the primary uses of timers is to measure time.
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. A single machine cycle consists
of 12 crystal pulses. Thus a running timer will be incremented: 11,059,000 / 12 =
921,583 times per second.

Unlike instructions which require 1 machine cycle, 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. To execute an event once per second
you’d have to wait for the timer to count from 0 to 50,000 18.45times.
To calculate how many times, the timer will be incremented in .05 seconds, a simple
multiplication can be done: 0 .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.0. To work with timers is to control the timers and initialize them.
TMOD 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 1whereas the
low four bits (bits 0 through 3) perform the exact same functions, but for timer 0. The
modes of operation are:

Table 5.1 Modes of Timer

TxM1 TxM0 Timer Mode Description of Mode


0 0 0 13-bit Timer.
0 1 1 16-bit Timer
1 0 2 8-bit auto-reload
1 1 3 13-bit Time Mode (mode 0)

Timer mode "0" is a 13-bit timer. 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. 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.
16-bit Time Mode (mode 1)
Timer mode "1" is a 16-bit timer. 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 [Link] 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, if TH0 holds the value FDh and TL0 holds the
value FEh values of TH0 and TL0 for a few machine cycles:
The value of TH0 never changed. When we use mode 2 you almost always set THx to a known
value and TLxis the SFR that is constantly incremented. The benefit of auto-reload mode is the
timer always have a value from 200 to 255. If you use mode 0 or 1, you’d 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. Auto-reload mode is very commonly used for establishing a baud rate in Serial
Communications.

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

Detecting Timer Overflow


Whenever a timer overflows from its highest value back to 0, the microcontroller
automatically sets the TFx bit in the TCON register. 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. it takes
the 8051 1/20thof 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.

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

5.2 Serial Port Programming: 8051 Serial Communication


One of the 8051’s many powerful features -integrated UART, known as a serial port to
easily read and write values to the serial port instead of turning on and off one of the I/O
lines in rapid succession to properly "clock out" each individual bit, including start bits,
stop bits and parity bits.
 Setting the Serial Port Mode configures it by specifying 8051 how many data
bits we want, the baud rate we will be using and how the baud rate will be determined.
First, let’s present the "Serial Control" (SCON) SFR and define what each bit of the
SFR represents:

Table 5.2 Definition of SCON SFR

Bit
Bit Name Explanation of Function
Address
7 SM0 9Fh Serial port mode bit 0
6 SM1 9Eh Serial port mode bit 1.
5 SM2 9Dh Mutli processor Communications Enable
4 REN 9Ch Receiver Enable. This bit must be set in order to receive
Characters.
3 TB8 9Bh Transmit bit 8. The 9th bit to transmit in mode 2 and 3.
2 RB8 9AH Receive bit 8. The 9th bit received in mode 2 and 3.
Transmit Flag. Set when a byte has been completely
1 T1 99h
Transmitted.
Receive Flag. Set when a byte has been completely
0 RI 98h
Received.

Additionally, it is necessary to define the function of SM0 and SM1 by an additional


table: Table 5.3 SCON as serial Port.

Table 5.3 Modes of SCON

SM0 SM1 Serial Mode Explanation Baud Rate

0 0 0 0 8-bit Shift Register Oscillator / 12


0 1 1 8-bit UART Set by Timer 1 (*)
1 0 2 9-bit UART Oscillator / 32 (*)
1 1 3 9-bit UART Set by Timer 1 (*)

The SCON SFR allows us to configure the Serial Port. The first four bits (bits 4
through 7) are configuration bits:
Bits SM0 and SM1 is to set the serial mode to a value between 0 and 3, inclusive
as in table above selecting the Serial Mode selects the mode of operation (8-bit/9-bit,
UART or Shift Register) and also determines how the baud rate will be calculated. In
modes 0 and 2 the baud rate is fixed based on the oscillator’s frequency. In modes 1 and
3 the baud rate is variable based on how often Timer 1 overflows.
The next bit, SM2, is a flag for " Multiprocessor communication whenever a byte has
been received the 8051 will set the "RI" (Receive Interrupt) flag to let the program know
that a byte has been received and that it needs to be processed.
However, when SM2 is set the "RI" flag will only be triggered if the 9th bit
received was a "1". if SM2 is set and a byte is received whose 9th bit is clear, the RI flag
will never be set .You will almost always want to clear this bit so that the flag is set upon
reception of any character.
The next bit, REN, is "Receiver Enable." is set indicate to data received via the
serial port.
The last four bits (bits 0 through 3) are operational bits. They are used when
actually sending and receiving data--they are not used to configure the serial port.
The TB8 bit is used in modes 2 and 3. In modes 2 and 3, a total of nine data bits are
transmitted. The first 8 data bits are the 8 bits of the main value, and the ninth bit is taken
from TB8. If TB8 is set and a value is written to the serial port, the data’s bits will be
written to the serial line followed by a "set" ninth bit. If TB8 is clear the ninth bit will be
"clear."
The RB8 also operates in modes 2 and 3and functions essentially the same way
as TB8, but on the reception side. When a byte is received in modes 2 or 3, a total of
nine bits are received. In this case, the first eight bits received are the data of the serial
byte received and the value of the ninth bit received will be placed in [Link] means
"Transmit Interrupt."
When a program writes a value to the serial port, a certain amount of time will pass
before the individual bits of the byte are "clocked out" the serial port. If the program
were to write another byte to the serial port before the first byte was completely output,
the data being sent would be garbled. Thus, the8051 lets the program know that it has
"clocked out" the last byte by setting the TI bit.
When the TI bit is set, the program may assume that the serial port is "free" and ready
to send the next byte. Finally, the RI bit means "Receive Interrupt." It functions
similarly, to the "TI" bit, but it indicates that a byte has been received.
Whenever the 8051 has received a complete byte it will trigger the RI bit to
let the program know that it needs to read the value quickly, before another byte is read.

Setting the Serial Port Baud Rate

Once the Serial Port Mode has been configured, the program must configure the serial
port’s baud rate. This only applies to Serial Port modes 1 and 3. The Baud Rate is
determined based on the oscillator’s frequency when in mode 0 and 2. In mode 0,
the baud rate is always the oscillator frequency divided by 12. This means if you’re
crystal is 1.059 Mhz, mode 0 baud rate will always be 921,583 baud. In mode 2 the baud
rate is always the oscillator frequency divided by 64, so a 11.059Mhz crystal speed will
yield a baud rate of172,797.
In modes 1 and 3, the baud rate is determined by how frequently timer 1 overflows. The
more frequently timer 1 overflows, the higher the baud rate. There are many ways one
can cause timer 1 to overflow at a rate that determines a baud rate, but the most common
method is to put timer 1 in 8-bit auto-reload mode (timer mode2) and set a reload value
(TH1) that causes Timer 1 to overflow at a frequency appropriate to generate a baud
rate.

To determine the value that must be placed in TH1 to generate a given baud
rate, (assuming PCON.7 is clear).

TH1 = 256 - ((Crystal / 384) / Baud)


If PCON.7 is set then the baud rate is effectively doubled, thus the equation
becomes:
TH1 = 256 - ((Crystal / 192) / Baud)

 Writing to the Serial Port


Once the Serial Port has been properly configured as explained above, the serial port is
ready to be used to send data and receive data.
To write a byte to the serial write the value to the SBUF (99h) SFR. For example, if
you wanted to send the letter "A" to the serial port, it could be accomplished as easily
as:
MOV SBUF, #’A’
Upon execution of the above instruction the 8051 will begin transmitting the character
via the serial port. Obviously transmission is not instantaneous--it takes a measureable
amount of time to transmit. And since the 8051 does not have a serial output buffer we
need to be sure that a character is completely transmitted before we try to transmit the
next character.
The 8051 lets us know when it is done transmitting a character by setting the TI
bit in SCON. When this bit is set the last character has been transmitted and that send
the next character, if any. Example:
CLR TI; Be sure the bit is initially clear
MOV SBUF, #’A’; Send the letter ‘A’ to the serial port
JNB TI, $; Pause until the RI bit is set.
MOV A, SBUF; Read the character from the serial port

5.3 Interrupt Programming:

The following events will cause an interrupt:


 Timer 0 Overflow.
 Timer 1 Overflow.
 Reception/Transmission of Serial Character.
 External Event 0.
 External Event 1.
To distinguish between various interrupts and executing different code depending on
what interrupt was triggered 8051may be jumping to a fixed address when a given
interrupt occurs.
Table 5.4 Interrupt handling

Interrupt Flag Interrupt Handler Address


External 0 IE0 0003h
Timer 0 TF0 000Bh
External 1 IE1 0013h
Timer 1 TF1 001Bh
Serial RI/TI 0023h

If Timer 0 overflows (i.e., the TF0 bit is set), the main program will be temporarily
suspended and control will jump to 000BH if we have code at address 0003H that
handles the situation of Timer 0 overflowing.
 Setting Up Interrupts
By default, at power up, all interrupts are disabled. Even if, for example, the TF0 bit is
set, the 8051 will not execute the interrupt. Your program must specifically tell the
8051 that it wishes to enable interrupts and specifically which interrupts it wishes to
enable. Your program may enable and disable interrupts by modifying the IE SFR
(A8h):

Table 5.5 Interrupts and address

Bit
Name Bit Address Explanation of Function

7 EA AFh Global Interrupt Enable/Disable


6 AEh Undefined
5 ADh Undefined
4 ES ACh Enable Serial Interrupt
3 ET1 ABh Enable Timer 1 Interrupt
2 EX1 AAh Enable External 1 Interrupt
1 ET0 A9h Enable Timer 0 Interrupt
0 EX0 A8h Enable External 0 Interrupt
 Polling Sequence
The 8051 automatically evaluates whether an interrupt should occur after every
instruction. When checking for interrupt conditions, it checks them in the following
order:
1) External 0 Interrupt
2) Timer 0 Interrupt
3) External 1 Interrupt
4) Timer 1 Interrupt
5) Serial Interrupt
6)
Interrupt Priorities
The 8051 offers two levels of interrupt priority: high and low. By using interrupt
priorities, you may assign higher priority to certain interrupt conditions. For example,
you may have enabled Timer 1 Interrupt which is automatically called every time Timer
1 overflows. Additionally, you may have enabled the Serial Interrupt which is called
every time a character is received via the serial port. However, you may consider that
receiving a character is much more important than the timer interrupt. In this case, if
Timer 1 Interrupt is already executing you may wish that the serial interrupt itself
interrupts the Timer 1 Interrupt. When the serial interrupt is complete, control passes
back to Timer 1 Interrupt and finally back to the main program. You may accomplish
this by assigning a high priority to the Serial Interrupt and a low priority to the Timer 1
Interrupt. Interrupt priorities are controlled by the IPSFR (B8h).
 Serial Interrupts
Serial Interrupts are slightly different than the rest of the interrupts. This is due to the
fact that there are two interrupt flags: RI and TI. If either flag is set, a serial interrupt is
triggered. As you will recall from the section on the serial port, the RI bit is set when a
byte is received by the serial port and the TI bit is set when a byte has been sent. This
means that when your serial interrupt is executed, it may have been triggered because
the RI flag was set or because the TI flag was set--or because both flags were set. Thus,
your routine must check the status of these flags to determine what action is appropriate.
Also, since the 8051does not automatically clear the RI and TI flags you must clear these
bits in your interrupt handler.

INT_SERIAL: JNB RI, CHECK_TI; If the RI flag is not set, we jump to


check TI MOV A, SBUF; If we got to this line, it’s because the RI bit *was*
set
CLR RI; Clear the RI bit after we’ve processed it
CHECK_TI: JNB TI, EXIT_INT; If the TI flag is not set, we jump to the exit
point CLR TI; Clear the TI bit before we send another character
MOV SBUF, #’A’; Send another character to the
serial port EXIT_INT: RETI

If both flags were set, both sections of code will be executed. Also note that each section
of code clears its corresponding interrupt flag. If you forget to clear the interrupt bits,
the serial interrupt will be executed over and over until you clear the bit. Thus it is very
important that you always clear the interrupt flags in a serial interrupt.

5.4 Interfacing a Microprocessor to Keyboard

The key board interfaced is a matrix keyboard. This key board is designed with a
particular rows and columns. These rows and columns are connected to the
microcontroller through its ports of the micro controller 8051. We normally use 8*8
matrix key board. So only two ports of 8051 can be easily connected to the rows and
columns of the key board.
Whenever a key is pressed, a row and a column gets shorted through that pressed
key and all the other keys are left open. When a key is pressed only a bit in the port
goes high which indicates microcontroller that the key is pressed. By this high on
the bit key in the corresponding column is identified.
Once we are sure that one of key in the key board is pressed next our aim is to
identify that key. To do this we firstly check for particular row and then we check
the corresponding column the key board.
To check the row of the pressed key in the keyboard, one of the row is made high by
making one of bit in the output port of 8051 high . This is done until the row is found
out.
Once we get the row next job is to find out the column of the pressed key. The
column is detected by contents in the input ports with the help of a counter. The content
of the input port is rotated with carry until the carry bit is set.
The contents of the counter are then compared and displayed in the display. This display
is designed using a seven segment display and a BCD to seven segment decoder IC 7447.
The BCD equivalent number of counter is sent through output part of 8051 displays the
number of pressed key.

Fig 5.1 Interfacing Keyboard to 8051 Microcontroller

5.5 Interfacing Analog to Digital Data Converters


• In most of the cases, the PPI 8255 is used for interfacing the analog to digital
converters with microprocessor.
• The analog to digital converters is treaded as an input device by the microprocessor,
that sends an initializing signal to the ADC to start the analogy to digital data
conversation process. The start of conversation signal is a pulse of a specific duration.
• The process of analog to digital conversion is a slow process, and the microprocessor
has to wait for the digital data till the conversion is over. After the conversion is over,
the ADC sends end of conversion EOC signal to inform the microprocessor that the
conversion is

over and the result is ready at the output buffer of the ADC. These tasks of issuing an
SOC pulse to ADC, reading EOC signal from the ADC and reading the digital output of
the ADC are carried out by the CPU using 8255 I/O ports.
• The time taken by the ADC from the active edge of SOC pulse till the active edge of
EOC signal is called as the conversion delay of the ADC.
• It may range anywhere from a few microseconds in case of fast ADC to even a few
hundred milliseconds in case of slow ADCs.
• The available ADC in the market use different conversion techniques for conversion
of analog signal to digitals. Successive approximation techniques and dual slope
integration techniques are the most popular techniques used in the integrated ADC chip.

• General algorithm for ADC interfacing contains the following steps:
1. Ensure the stability of analog input, applied to the ADC.
2. Issue start of conversion pulse to ADC
3. Read end of conversion signal to mark the end of conversion processes.
4. Read digital data output of the ADC as equivalent digital output.
5. Analog input voltage must be constant at the input of the ADC right from the
start of Conversion to of conversion till the end of the conversion to get correct
results. This may be ensured by a sample and hold circuit which samples the
analog signal and holds it constant for a specific time duration. The
microprocessor may issue a hold signal to the sample and hold circuit.
6. If the applied input changes before the complete conversion process is over,
the digital equivalent of the analog input calculated by the ADC may not be
correct.
ADC 0808/0809:
The analog to digital converter chips 0808 and 0809 are 8-bit CMOS,
successive approximation converters. This technique is one of the fast
techniques for analog to digital conversion. The conversion delay is 100μs at
a clock frequency of 640 KHz, which is quite low as compared to other
converters. These converters do not need any external zero or full scale
adjustments as they are already taken care of by internal circuits.

Fig.5.2 Interfacing ADC with 8255 and Microcontroller


[Source:Doughlas [Link], “Microprocessors and Interfacing, Programming and Hardware:,TMH, 2012]

These converters internally have a 3:8 analog multiplexers so that at a time eight
different analog conversion by using address lines - ADD A, ADD B, ADD C. Using
these address inputs, multichannel data acquisition system can be designed using a single
ADC. The CPU may drive these lines using output port lines in case of multichannel
applications. In case of single input applications, these may be hardwired to select the
proper input.
There is unipolar analog to digital converters, i.e. they are able to convert only positive
analog input voltage to their digital equivalent. These chips do not contain any internal
sample and hold circuit. If one needs a sample and hold circuit for the conversion of fast signal
into equivalent digital quantities, it has to be externally connected at each of the analog inputs.
5.6 External Memory Interface:

Fig.5.3 Interfacing External Memories with Microcontroller

[Source: Mohamed Ali Mazidi, Janice Gillispie Mazidi, Rolin McKinlay, “The 8051 Microcontroller
and Embedded Systems: Using Assembly and C”, Second Edition, Pearson Education, 2011]

8031 chip is a ROM less version of the 8051. In other words, it is exactly like any member of the 8051 family
such as the 8751 or 89C51 as far as executing the instructions and features are concerned, but it has no on-
chip ROM. Therefore, to make the 8031 execute 8051 code, it must be connected to external ROM memory
containing the program code. In this section we look at interfacing the 8031 microcontroller with external
ROM. Before we discuss this topic, one might wonder why someone would want to use the 8031 when they
could buy an 8751, 89C51, or DS5000. The reason is that all these chips have a limited amount of on-chip
ROM. Therefore, in many systems where the on-chip ROM of the 8051 is not sufficient, the use of an 8031 is
ideal since it allows the program size to be as large as 64K bytes. Although the 8031 chip itself is much cheaper
than other family members, an 8031-based system is much more expensive since the ROM containing the
program code is connected externally and requires more supporting circuitry, as we explain next. First, we
review some of the pins of the 8031/51 used in external memory interfacing.
EA pin
In 8751/89C51/DS5000-based systems, we connect the EA pin to Vcc to indicate that the program code is
stored in the microcontroller’s on-chip ROM. To indicate that the program code is stored in external ROM,
this pin must be connected to GND. This is the case for the 8051-based system. In fact, there are times when,
due to repeated burning and erasing of on-chip ROM, its UV-EPROM is no longer working. In such cases one
can also use the 8751 (or 89C51 or any 8051) as the 8031. All we have to do is to connect the EA pin to ground
and connect the chip to external ROM containing the program code.
5.7 Stepper Motor Interface

The complete board consists of transformer, control circuit, keypad and stepper motor
as shown in snap.
The circuit has inbuilt 5 V power supply so when it is connected with transformer it will
give the supply to circuit and motor both. The 8 Key keypad is connected with circuit
through which user can give the command to control stepper motor. The control circuit
includes micro controller 89C51, indicating LEDs, and current driver chip ULN2003A.
One can program the controller to control the operation of stepper motor. He can give
different commands through keypad like, run clockwise, run anticlockwise,
increase/decrease RPM, increase/decrease revolutions, stop motor, change the mode,
etc.

Unipolar stepper motor: - unipolar stepper motor has four coils. One end of each coil
is tied together and it gives common terminal which is always connected with positive
terminal of supply. The other ends of each coil are given for interface.
By means of controlling a stepper motor operation we can
1. Increase or decrease the RPM (speed) of it
2. Increase or decrease number of revolutions of it
3. Change its direction means rotate it clockwise or anticlockwise
To vary the RPM of motor we have to vary the PRF (Pulse Repetition
Frequency). Number of applied pulses will vary number of rotations and last to change
direction we have to change pulse sequence.
So all these three things just depend on applied pulses. Now there are three different
modes to rotate this motor
1. Single coil excitation
2. Double coil excitation
3. Half step excitation
Fig.5.4 Stepper motor control board circuit

[Source: Mohamed Ali Mazidi, Janice Gillispie Mazidi, Rolin McKinlay, “The 8051 Microcontroller
and Embedded Systems: Using Assembly and C”, Second Edition, Pearson Education, 2011]

You might also like