Timers Counters

Embed Size (px)

Citation preview

  • 8/9/2019 Timers Counters

    1/25

    Page | 1

    Timer / Counter :

    Many microcontroller applications require the counting of external events orthe generation of time delay between two actions. Timing and counting tasks can be

    implemented by software. But software loops keep the microcontroller to be occupiedand other tasks can not be done. To avoid this, hardware timers/counters are availablein 8051.

    8051 has two 16 bit timer/counter registers namely Timer 0 and Timer 1. Theycan be independently configured to operate as timer or counter.

    When used as a timer, the register is incremented after every machine cycle.Since one machine cycle consists of 12 oscillator periods, the count rate is 1/12 of theoscillator frequency.

    When used as a counter, the register is incremented in response to a high tolow transition of the corresponding external input pin T 0 and T 1.

    Timer / Counter mode control register (TMOD):

    Timer0 and Timer1 have four operating modes. The Timer or Counteroperation and the mode of operation can be configured using TMOD register in thespecial function registers.

    TMOD is dedicated to the two timers and can be considered to be twoduplicate 4 bit registers.

    MSB LSBG C / T M1 M0 G C/T M1 M0

    TIMER 1 TIMER 0

    G gate enable bit which controls RUN/STOP of timers. Set to 1 by program toenable timer to run if bit TR in TCON is set and signal on external interrupt INTis high.

    C/T set by program; =1 to use as counter; =0 to use as timer

    M1 M00 0 MODE 0 8 bit timer (TH) with TL as 5 bit prescalar.0 1 MODE 1 16 bit timer.1 0 MODE 2 8 bit auto reloaded timer. TH has a value which is to

    be reloaded into TL each time it overflows.1 1 MODE 3 timer 1 stopped. Timer 0 TH & TL two separate

    8 bit counters.

  • 8/9/2019 Timers Counters

    2/25

    Page | 2

    Timer Control (TCON) Register:

    TCON is a bit addressable special function register. TCON has control bitsand flags for the timers in the upper nibble and control bits and flags for the externalinterrupts in the lower nibble.

    MSB LSBTF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0

    TIMER INTERRUPT TF timer overflow flag. Set when timer rolls from all 1s to 0. Cleared when interrupt

    processed.

    TR timer run control bit. Set to 1 by program to enable timer to count.Cleared to 0 by Program, to halt timer. Does not reset timer.

    IE external interrupt edge flag. Set when high to low edge signal is received on INT pin. Cleared when processor vector to interrupt service subroutine. Not relatedto timer operations.

    IT external interrupt signal type control bit. Set to 1 by program to enable a lowLevel signal on external interrupt to generate an interrupt.

    Timer Modes of Operation:

    The timers may operate in any of four modes that are determined by the mode bits M1 and M0 in the TMOD register.

    MODE 0:

    In this mode, the timer register is configured as a 13 bit register ( TL 5 bits andTH 8 bits ). The 5 bits in the TL sets the divide by 32 prescale to the TH as an 8 bitcounter.

    The timer is enabled when TR=1 and G=0 or INT =1. Setting G=1 allows thetimer to be controlled by external input INT.

    Timer 0 in mode 0 (13-bit timer)

    This mode is for compatibility with the previous versions of microcontrollers.This mode configures timer 0 as a 13-bit timer which consists of all 8 bits of TH0 andthe lower 5 bits of TL0. As a result, the Timer 0 uses only 13 of 16 bits. How does itoperate? Each coming pulse causes the lower register bits to change their states. Afterreceiving 32 pulses, this register is loaded and automatically cleared, while the higher

    byte (TH0) is incremented by 1. This process is repeated until registers count up 8192 pulses. After that, both registers are cleared and counting starts from 0.

  • 8/9/2019 Timers Counters

    3/25

    Page | 3

    Timer 0 in mode 1 (16-bit timer)

    Mode 1 configures timer 0 as a 16-bit timer comprising all the bits of bothregisters TH0 and TL0. Timer operates in the same way as in mode 0, with differenceat the registers count up to 65 536 as allowable by the 16 bits.

    Timer 0 in mode 2 (Auto-Reload Timer)

    Mode 2 configures timer 0 as an 8-bit timer. Actually, timer 0 uses only one8-bit register for counting and never counts from 0, but from an arbitrary value(0-255) stored in another (TH0) register.

    The following example shows the advantages of this mode. Suppose it isnecessary to constantly count up 55 pulses generated by the clock.

    If mode 1 or mode 0 is used, It is necessary to write the number 200 to thetimer registers and constantly check whether an overflow has occured, i.e. whether

  • 8/9/2019 Timers Counters

    4/25

    Page | 4

    they reached the value 255. When it happens, it is necessary to rewrite the number200 and repeat the whole procedure. The same procedure is automatically performed

    by the microcontroller if set in mode 2. In fact, only the TL0 register operates as atimer, while another (TH0) register stores the value from which the counting starts.When the TL0 register is loaded, instead of being cleared, the contents of TH0 will be

    reloaded to it. Referring to the previous example, in order to register each 55th pulse,the best solution is to write the number 200 to the TH0 register and configure thetimer to operate in mode 2.

    Timer 0 in Mode 3 (Split Timer)

    Mode 3 configures timer 0 so that registers TL0 and TH0 operate as separate8-bit timers. In other words, the 16-bit timer consisting of two registers TH0 and TL0is split into two independent 8-bit timers. This mode is provided for applicationsrequiring an additional 8-bit timer or counter. The TL0 timer turns into timer 0, whilethe TH0 timer turns into timer 1. In addition, all the control bits of 16-bit Timer 1(consisting of the TH1 and TL1 register), now control the 8-bit Timer 1. Even thoughthe 16-bit Timer 1 can still be configured to operate in any of modes (mode 1, 2 or 3),it is no longer possible to disable it as there is no control bit to do it. Thus, itsoperation is restricted when timer 0 is in mode 3.

  • 8/9/2019 Timers Counters

    5/25

    Page | 5

    Program to generate a 2KHz. square wave at P1.7 using Timer/counter 1 in8bit TIMER mode.

  • 8/9/2019 Timers Counters

    6/25

    Page | 6

    Program to generate a 50Hz. square wave at P1.7 using ; Timer/counter 1 in16bit Timer mode.

    Serial Communication:

    Synchronous Serial Communication

    Synchronous serial Communication requires that the sender and receiver share a clockwith one another, or that the sender provide a strobe so that the receiver knows when toread the next bit of the data. In most forms of serial Synchronous communication, ifthere is no data available at a given instant to transmit, a fill character must be sent so thatdata is always being transmitted. Synchronous communication is usually more efficient

    because only data bits are transmitted between sender and receiver, and synchronous

    communication can be more costly if extra wiring and circuits are required to share a clocksignal between the sender and receiver.

    A form of Synchronous transmission is used with printers and fixed disk devices inthat the data is sent on one set of wires while a clock or strobe is sent on a different wire.Printers and fixed disk devices are not normally serial devices because most fixed diskinterface standards send an entire word of data for each clock or strobe signal by using aseparate wire for each bit of the word. In the PC industry, these are known as Paralleldevices.

    The standard serial communications hardware in the PC does not supportSynchronous operations. This mode is described here for comparison purposes only.

  • 8/9/2019 Timers Counters

    7/25

    Page | 7

    Asynchronous Serial Transmission

    Asynchronous transmission allows data to be transmitted without the sender having tosend a clock signal to the receiver. Instead, the sender and receiver must agree on timing

    parameters in advance and special bits are added to each word which are used to

    synchronize the sending and receiving units. When a word is given to the UART for Asynchronous transmissions, a bit called the

    "Start Bit" is added to the beginning of each word that is to be transmitted. The Start Bit isused to alert the receiver that a word of data is about to be sent, and to force the clock inthe receiver into synchronization with the clock in the transmitter. These two clocks must

    be accurate enough to not have the frequency drift by more than 10% during thetransmission of the remaining bits in the word. (This requirement was set in the days ofmechanical teleprinters and is easily met by modern electronic equipment.)

    After the Start Bit, the individual bits of the word of data are sent, with the LeastSignificant Bit (LSB) being sent first. Each bit in the transmission is transmitted forexactly the same amount of time as all of t he other bits, and the receiver looks at the wireat approximately halfway through the period assigned to each bit to determine if the bit is a1 or a 0 . For example, if it takes two seconds to send each bit, the receiver will examine thesignal to determine if it is a 1 or a 0 after one second has passed, then it will wait twoseconds and then examine the value of the next bit, and so on.

    The sender does not know when the receiver has looked at the value of the bit. Thesender only knows when the clock says to begin transmitting the next bit of the word.

    When the entire data word has been sent, the transmitter may add a Parity Bit that thetransmitter generates. The Parity Bit may be used by the receiver to perform simple error

    checking. Then at least one Stop Bit is sent by the transmitter.

    When the receiver has received all of the bits in the data word, it may check for theParity Bits (both sender and receiver must agree on whether a Parity Bit is to be used), andthen the receiver looks for a Stop Bit. If the Stop Bit does not appear when it is supposedto, the UART considers the entire word to be garbled and will report a Framing Error to thehost processor when the data word is read. The usual cause of a Framing Error is that thesender and receiver clocks were not running at the same speed, or that the signal wasinterrupted.

    Regardless of whether the data was received correctly or not, the UART automatically

    discards the Start, Parity and Stop bits. If the sender and receiver are configuredidentically, these bits are not passed to the host.

    If another word is ready for transmission, the Start Bit for the new word can be sent assoon as the Stop Bit for the previous word has been sent.

    Because asynchronous data is self synchronizing, if there is n o data to transmit, thetransmission line can be idle.

  • 8/9/2019 Timers Counters

    8/25

    Page | 8

    Sequence without framing

    Framed data

    Framed data including a parity bit

    RS-232 Serial Communications

    The EIA RS-232 serial communication standard is a universal standard,originally used to connect teletype terminals to modem devices. Figure shows a PCconnected to a device such as a modem or a serial printer using the RS-232connection. In a modern PC the RS-232 interface is referred to as a COM port. TheCOM port uses a 9-pin D-type connector to attach to the RS-232 cable. The RS-232standard defines a 25-pin D-type connector but IBM reduced this connector to a 9-pindevice so as to reduce cost and size. Figure shows a simple simplex serialcommunication link where data is being transmitted serially from left to right. Asingle Tx (transmit) wire is used for transmission and the return (Gnd) wire isrequired to complete the electrical circuit. Figure shows the inclusion of another

    physical wire to support full-duplex (or half-duplex) serial communication. TheRS-232 (COM port) standard includes additional signal wires for hand -shake

    purposes, but the fundamental serial communication can be achieved with just two or

  • 8/9/2019 Timers Counters

    9/25

    Page | 9

    three wires as shown. The serial data is transmitted at a predefined rate, referred to asthe baud rate. The term baud rate refers to the number of state changes per secondwhich is the same as the bit rate for this particular communication scheme. Typical

    baud rates are: 9600 bps; 19,200 bps; 56kbps etc.

    SBUF Register

    SBUF is an SFR register which can be written to, so as to hold the next data byte to be transmitted. Also it can be read from to get the latest data byte received bythe serial port. SBUF is thus effectively two registers: one for transmitting and one forreceiving.

    SCON RegisterThe SCON (Serial Control) register is an SFR register, used for configuring

    and monitoring the serial port status .

  • 8/9/2019 Timers Counters

    10/25

    Page | 10

    SM0, SM1 bits define the mode of operation, such as the number of data bits(8 or9), the clock source etcSM2 is set to 0 for normal operationREN is set to 1 to enable reception, 0 to disable receptionTB8 is the ninth bit (parity bit) to be transmittedRB8 is the ninth bit received (parity bit)TI Transmit Interrupt flag. A logic 1 indicates that transmit buffer (SBUF) is empty.This flag must be cleared by software.RI Receive Interrupt flag. A logic 1 indicates that data has been received in thereceive buffer (SBUF). This flag must be cleared by software.

    Setting the BAUD rate

    Timer/Counter 1 (in SCON mode 3) provides the serial port baud rate clock.Usually the 8-bit auto reload operation (Timer/Counter mode 2) is used. The tableshows some values defined for the TH1 register to achieve some of the more common

    baud rates.The values shown assume a processor clock rate of 11.059MHz. This is acommon crystal value for 8051 based designs as it divides down to provide accurate

    baud rates.

    Note. The most significant bit of the PCON register is assumed to be at 0. If this wereset to 1 the baud rate value would be doubled.

  • 8/9/2019 Timers Counters

    11/25

    Page | 11

    8051 Microcontroller Interrupts

    There are five interrupt sources for the 8051, which means that they canrecognize 5 different events that can interrupt regular program execution. Eachinterrupt can be enabled or disabled by setting bits of the IE register. Likewise, thewhole interrupt system can be disabled by clearing the EA bit of the same register.Refer to figure below.

    Now, it is necessary to explain a few details referring to external interrupts-INT0 and INT1. If the IT0 and IT1 bits of the TCON register are set, an interrupt will

    be generated on high to low transition, i.e. on the falling pulse edge (only in thatmoment). If these bits are cleared, an interrupt will be continuously executed as far asthe pins are held low.

    IE Register (Interrupt Enable)

    EA - global interrupt enable/disable:o 0 - disables all interrupt requests.o 1 - enables all individual interrupt requests.

    ES - enables or disables serial interrupt:

  • 8/9/2019 Timers Counters

    12/25

    Page | 12

    o 0 - UART system cannot generate an interrupt.o 1 - UART system enables an interrupt.

    ET1 - bit enables or disables Timer 1 interrupt:o 0 - Timer 1 cannot generate an interrupt.o 1 - Timer 1 enables an interrupt.

    EX1 - bit enables or disables external 1 interrupt:o 0 - change of the pin INT0 logic state cannot generate an interrupt.o 1 - enables an external interrupt on the pin INT0 state change.

    ET0 - bit enables or disables timer 0 interrupt:o 0 - Timer 0 cannot generate an interrupt.o 1 - enables timer 0 interrupt.

    EX0 - bit enables or disables external 0 interrupt:o 0 - change of the INT1 pin logic state cannot generate an interrupt.o 1 - enables an external interrupt on the pin INT1 state change.

    Interrupt Priorities

    It is not possible to foreseen when an interrupt request will arrive. If severalinterrupts are enabled, it may happen that while one of them is in progress, anotherone is requested. In order that the microcontroller knows whether to continueoperation or meet a new interrupt request, there is a priority list instructing it what todo.

    The priority list offers 3 levels of interrupt priority:

    1. Reset! The absolute master. When a reset request arrives, everything isstopped and the microcontroller restarts.

    2. Interrupt priority 1 can be disabled by Reset only.3. Interrupt priority 0 can be disabled by both Reset and interrupt priority 1.

    The IP Register (Interrupt Priority Register) specifies which one of existinginterrupt sources have higher and which one has lower priority. Interrupt priority isusually specified at the beginning of the program. According to that, there are several

    possibilities:

    If an interrupt of higher priority arrives while an interrupt is in progress, it will be immediately stopped and the higher priority interrupt will be executed first.

    If two interrupt requests, at different priority levels, arrive at the same timethen the higher priority interrupt is serviced first.If the both interrupt requests, at the same priority level, occur one afteranother, the one which came later has to wait until routine being in progressends.If two interrupt requests of equal priority arrive at the same time then theinterrupt to be serviced is selected according to the following priority list:

    1. External interrupt INT02. Timer 0 interrupt3. External Interrupt INT1

    4. Timer 1 interrupt5. Serial Communication Interrupt

  • 8/9/2019 Timers Counters

    13/25

    Page | 13

    IP Register (Interrupt Priority)

    The IP register bits specify the priority level of each interrupt (high or low priority).

    PS - Serial Port Interrupt priority bito Priority 0o Priority 1

    PT1 - Timer 1 interrupt priorityo Priority 0o Priority 1

    PX1 - External Interrupt INT1 priorityo Priority 0o Priority 1

    PT0 - Timer 0 Interrupt Priorityo Priority 0o Priority 1

    PX0 - External Interrupt INT0 Priorityo Priority 0o Priority 1

    Handling Interrupt

    When an interrupt request arrives the following occurs:

    1. Instruction in progress is ended.2. The address of the next instruction to execute is pushed on the stack.3. Depending on which interrupt is requested, one of 5 vectors (addresses) is

    written to the program counter in accordance to the table below:

    Interrupt Source Vector (address)

    IE0 3 h

    TF0 B h

    TF1 1B h

    RI, TI 23 h

    All addresses are in hexadecimal format

  • 8/9/2019 Timers Counters

    14/25

    Page | 14

    4. These addresses store appropriate subroutines processing interrupts. Instead ofthem, there are usually jump instructions specifying locations on which thesesubroutines reside.

    5. When an interrupt routine is executed, the address of the next instruction toexecute is poped from the stack to the program counter and interrupted

    program resumes operation from where it left off.

    Serial communication

    One of the 8051s many powerful features is its integrated UART , otherwiseknown as a serial port. The fact that the 8051 has an integrated serial port means thatyou may very easily read and write values to the serial port. If it were not for theintegrated serial port, writing a byte to a serial line would be a rather tedious processrequiring turning on and off one of the I/O lines in rapid succession to properly "clockout" each individual bit, including start bits, stop bits, and parity bits.

    Setting the Serial Port Mode

    The first thing we must do when using the 8051s integrated serial port is, obviously,configure it. This lets us tell the 8051 how many data bits we want, the baud rate wewill be using, and how the baud rate will be determined. First, lets present the "SerialControl" (SCON) SFR and define what each bit of the SFR represents:

    Bit Name BitAddress Explanation of Function

    7 SM0 9Fh Serial port mode bit 0

    6 SM1 9Eh Serial port mode bit 1.5 SM2 9Dh Multiprocessor Communications Enable (explained later)

    4 REN 9Ch Receiver Enable. This bit must be set in order to receivecharacters.

    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.

    1 TI 99h Transmit Flag. Set when a byte has been completelytransmitted.

    0 RI 98h Receive Flag. Set when a byte has been completely received.

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

    SM0 SM1 Serial Mode Explanation Baud Rate

    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 (*)

  • 8/9/2019 Timers Counters

    15/25

    Page | 15

    (*) Note: The baud rate indicated in this table is doubled if PCON.7 (SMOD) is set.

    The SCON SFR allows us to configure the Serial Port. Thus, well go through each bit and review its function.

    The first four bits (bits 4 through 7) are configuration bits.

    Bits SM0 and SM1 let us set the serial mode to a value between 0 and 3, inclusive.The four modes are defined in the chart immediately above. As you can see, selectingthe 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 baudrate is fixed based on the oscillators frequency. In modes 1 and 3 the baud rate isvariable based on how often Timer 1 overflows. Well talk more about the variousSerial Modes in a moment.

    The next bit, SM2 , is a flag for "Multiprocessor communication." Generally,whenever a byte has been received the 8051 will set the "RI" (Receive Interrupt) flag.This lets 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". That is to say, if SM2 is set and a byte is received whose 9th bit is clear, the RI flag will never be set. This can be useful in certain advanced serialapplications. For now it is safe to say that you will almost always want to clear this bitso that the flag is set upon reception of any character.

    The next bit, REN , is "Receiver Enable." This bit is very straightforward: If you wantto receive data via the serial port, set this bit. You will almost always want to set this

    bit.

    The last four bits (bits 0 through 3) are operational bits. They are used when actuallysending 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 aretransmitted. The first 8 data bits are the 8 bits of the main value, and the ninth bit istaken from TB8. If TB8 is set and a value is written to the serial port, the datas bitswill 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 3 and functions essentially the same way asTB8, but on the reception side. When a byte is received in modes 2 or 3, a total ofnine 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 RB8.

    TI means "Transmit Interrupt." When a program writes a value to the serial port, acertain amount of time will pass before the individual bits of the byte are "clockedout" the serial port. If the program were to write another byte to the serial port beforethe 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.

  • 8/9/2019 Timers Counters

    16/25

    Page | 16

    Finally, the RI bit means "Receive Interrupt." It funcions similarly to the "TI" bit, butit indicates that a byte has been received. That is to say, whenever the 8051 hasreceived a complete byte it will trigger the RI bit to let the program know that it needsto read the value quickly, before another byte is read.

    Setting the Serial Port Baud Rate

    Once the Serial Port Mode has been configured, as explained above, the programmust configure the serial ports baud rate. This only applies to Serial Port modes 1 and3. The Baud Rate is determined based on the oscillators frequency when in mode 0and 2. In mode 0, the baud rate is always the oscillator frequency divided by 12. Thismeans if youre crystal is 11.059Mhz, 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 a11.059Mhz crystal speed will yield a baud rate of 172,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 waysone can cause timer 1 to overflow at a rate that determines a baud rate, but the mostcommon method is to put timer 1 in 8-bit auto-reload mode (timer mode 2) and set areload value (TH1) that causes Timer 1 to overflow at a frequency appropriate togenerate a baud rate.

    To determine the value that must be placed in TH1 to generate a given baud rate, wemay use the following equation (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)For example, if we have an 11.059Mhz crystal and we want to configure the serial

    port to 19,200 baud we try plugging it in the first equation:TH1 = 256 - ((Crystal / 384) / Baud)TH1 = 256 - ((11059000 / 384) / 19200 )TH1 = 256 - ((28,799) / 19200)TH1 = 256 - 1.5 = 254.5

    As you can see, to obtain 19,200 baud on a 11.059Mhz crystal wed have to set TH1 to254.5. If we set it to 254 we will have achieved 14,400 baud and if we set it to 255 wewill have achieved 28,800 baud. Thus were stuck...

    But not quite... to achieve 19,200 baud we simply need to set PCON.7 (SMOD).When we do this we double the baud rate and utilize the second equation mentionedabove. Thus we have:

    TH1 = 256 - ((Crystal / 192) / Baud)TH1 = 256 - ((11059000 / 192) / 19200)TH1 = 256 - ((57699) / 19200)TH1 = 256 - 3 = 253

    Here we are able to calculate a nice, even TH1 value. Therefore, to obtain 19,200 baud with an 11.059MHz crystal we must:

    1. Configure Serial Port mode 1 or 3.2. Configure Timer 1 to timer mode 2 (8-bit auto-reload).

  • 8/9/2019 Timers Counters

    17/25

    Page | 17

    3. Set TH1 to 253 to reflect the correct frequency for 19,200 baud.4. Set PCON.7 (SMOD) to double the baud rate.

    Writing to the Serial Port

    Once the Serial Port has been propertly configured as explained above, the serial port

    is ready to be used to send data and receive data. If you thought that configuring theserial port was simple, using the serial port will be a breeze.

    To write a byte to the serial port one must simply write the value to the SBUF (99h)SFR. For example, if you wanted to send the letter "A" to the serial port, it could beaccomplished as easily as:

    MOV SBUF,#A Upon execution of the above instruction the 8051 will begin transmitting the charactervia the serial port. Obviously transmission is not instantaneous--it takes a measureableamount of time to transmit. And since the 8051 does not have a serial output bufferwe need to be sure that a character is completely transmitted before we try to transmitthe next character.

    The 8051 lets us know when it is done transmitting a character by setting the TI bit inSCON. When this bit is set we know that the last character has been transmitted andthat we may send the next character, if any. Consider the following code segment:

    CLR TI ;Be sure the bit is initially clearMOV SBUF,#A ;Send the letter A to the serial portJNB TI,$ ;Pause until the TI bit is set.

    The above three instructions will successfully transmit a character and wait for the TI bit to be set before continuing. The last instruction says "Jump if the TI bit is not setto $"--$, in most assemblers, means "the same address of the current instruction."Thus the 8051 will pause on the JNB instruction until the TI bit is set by the 8051upon successful transmission of the character.

    Reading the Serial Port

    Reading data received by the serial port is equally easy. To read a byte from the serial port one just needs to read the value stored in the SBUF (99h) SFR after the 8051 hasautomatically set the RI flag in SCON.

    For example, if your program wants to wait for a character to be received andsubsequently read it into the Accumulator, the following code segment may be used:

    JNB RI,$ ;Wait for the 8051 to set the RI flagMOV A,SBUF ;Read the character from the serial port

    The first line of the above code segment waits for the 8051 to set the RI flag; again,the 8051 sets the RI flag automatically when it receives a character via the serial port.So as long as the bit is not set the program repeats the "JNB" instruction continuously.

    Once the RI bit is set upon character reception the above condition automatically fails

    and program flow falls through to the "MOV" instruction which reads the value.

  • 8/9/2019 Timers Counters

    18/25

    Page | 18

    Interfacing LCD to 8051

    Liquid Crystal Display also called as LCD is very helpful in providing user interface aswell as for debugging purpose. The most common type of LCD controller is HITACHI44780 which provides a simple interface between the controller & an LCD. TheseLCD's are very simple to interface with the controller as well as are cost effective.

    The most commonly used ALPHANUMERIC displays are 1x16 (Single Line & 16characters), 2x16 (Double Line & 16 character per line) & 4x20 (four lines & Twentycharacters per line).

    The LCD requires 3 control lines (RS, R/W & EN) & 8 (or 4) data lines. The number ondata lines depends on the mode of operation. If operated in 8-bit mode then 8 datalines + 3 control lines i.e. total 11 lines are required. And if operated in 4-bit modethen 4 data lines + 3 control lines i.e. 7 lines are required. How do we decide which

    mode to use? Its simple if you have sufficient data lines you can go for 8 bit mode &if there is a time constrain i.e. display should be faster then we have to use 8-bitmode because basically 4-bit mode takes twice as more time as compared to 8-bitmode.

    Pin Symbol Function

    1 Vss Ground

    2 Vdd Supply Voltage

    3 Vo Contrast Setting

    4 RS Register Select

    5 R/W Read/Write Select

    6 En Chip Enable Signal

    7-14 DB0-DB7 Data Lines

    15 A/Vee Gnd for the backlight

    16 K Vcc for backlight

  • 8/9/2019 Timers Counters

    19/25

  • 8/9/2019 Timers Counters

    20/25

    Page | 20

    MOV P1,A //Character to be displayed is in Acc

    SETB EN

    CLR EN //High to Low pulse on EN to latch the data

    CALL DELAY //Delay so that LCD finishes its internal operations

    ret

    Command or Special Instruction.

    lcd_command:

    CLR RS //Telling the LCD that the data which is being send is acommand

    MOV P1,A //Character to be displayed is in Acc

    SETB EN

    CLR EN //High to Low pulse on EN to latch the data

    CALL DELAY //Delay so that LCD finishes its internal operations

    ret

    Here I have used delay at the end of both the subroutines this is done to wait untilthe instruction is completely executed by the LCD. This will assure that our programgives the LCD the time it needs to execute instructions and also makes our programcompatible with any LCD, regardless of how fast or slow it is.

    "*" - Not Used/Ignored. This bit can be either "1" or "0"

  • 8/9/2019 Timers Counters

    21/25

    Page | 21

    Keyboard Interfacing

    The key board here we are interfacing is a matrix keyboard. This key board isdesigned with a particular rows and columns. These rows and columns are connectedto 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 rowsand columns of the key board.

    When ever 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 inthe port goes high. Which indicates microcontroller that the key is pressed. By thishigh 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 toidentify that key. To do this we firstly check for particular row and then we check thecorresponding column the key board.

    To check the row of the pressed key in the keyboard, one of the row is madehigh by making one of bit in the output port of 8051 high . This is done until the rowis found out. Once we get the row next out 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 acounter. The content of the input port is rotated with carry until the carry bit is set.

    The contents of the counter is then compared and displayed in the display. Thisdisplay is designed using a seven segment display and a BCD to seven segmentdecoder IC 7447.

    The BCD equivalent number of counter is sent through output part of 8051displays the number of pressed key.

    Circuit diagram of INTERFACING KEY BOARD TO 8051 .

    The programming algorithm, program and the circuit diagram is as follows. Here program is explained with comments.

  • 8/9/2019 Timers Counters

    22/25

    Page | 22

    Circuit diagram of INTERFACING KEY BOARD TO 8051.

    Keyboard is organized in a matrix of rows and columns as shown in the figure. Themicrocontroller accesses both rows and columns through the port.

    1. The 8051 has 4 I/O ports P0 to P3 each with 8 I/O pins, P0.0 toP0.7,P1.0 to P1.7, P2.0 to P2.7, P3.0 to P3.7. The one of the port P1(it understood that P1 means P1.0 to P1.7) as an I/P port formicrocontroller 8051, port P0 as an O/P port of microcontroller8051 and port P2 is used for displaying the number of pressed key.

    2. Make all rows of port P0 high so that it gives high signal when keyis pressed.

    3. See if any key is pressed by scanning the port P1 by checking allcolumns for non zero condition.

    4. If any key is pressed, to identify which key is pressed make onerow high at a time.

    5. Initiate a counter to hold the count so that each key is counted. 6. Check port P1 for nonzero condition. If any nonzero number is

    there in [accumulator], start column scanning by following step 9. 7. Otherwise make next row high in port P1. 8. Add a count of 08h to the counter to move to the next row by

    repeating steps from step 6. 9. If any key pressed is found, the [accumulator] content is rotated

    right through the carry until carry bit sets, while doing thisincrement the count in the counter till carry is found.

    10. Move the content in the counter to display in data field or tomemory location

    11. To repeat the procedures go to step 2.

  • 8/9/2019 Timers Counters

    23/25

  • 8/9/2019 Timers Counters

    24/25

    Page | 24

    ADC 0804 Interfacing:

    As shown in the typical circuit, ADC0804 can be interfaced with any microcontroller.You need a minimum of 11 pins to interface ADC0804, eight for data pins and 3 forcontrol pins. As shown in the typical circuit the chip select pin can be made low if youare not using the microcontroller port for any other peripheral (multiplexing).

    .

    The above timing diagrams are from ADC0804 datasheet. The first diagram showshow to start a conversion. Also you can see which signals are to be asserted and atwhat time to start a conversion. So looking into the timing diagram FIGURE 10A. We

    note down the steps or say the order in which signals are to be asserted to start aconversion of ADC. As we have decided to make Chip select pin as low so we need

  • 8/9/2019 Timers Counters

    25/25

    not to bother about the CS signal in the timing diagram. Below steps are for startingan ADC conversion. I am also including CS signal to give you a clear picture. While

    programming we will not use this signal.

    1. Make chip select (CS) signal low.

    2. Make write (WR) signal low.3. Make chip select (CS) high.4. Wait for INTR pin to go low (means conversion ends).

    Once the conversion in ADC is done, the data is available in the output latch of theADC. Looking at the FIGURE 10B which shows the timing diagram of how to readthe converted value from the output latch of the ADC. Data of the new conversion isonly avalable for reading after ADC0804 made INTR pin low or say when theconversion is over. Below are the stepts to read output from the ADC0804.

    1. Make chip select (CS) pin low.2. Make read (RD) signal low.3. Read the data from port where ADC is connected.4. Make read (RD) signal high.5. Make chip select (CS) high.

    Programming 8051 Microcontroller CODE:

    rd equ P1 . 0 ;Read signal P1.0 wr equ P1 . 1 ;Write signal P1.1 cs equ P1 . 2 ;Chip Select P1.2 intr equ P1 . 3 ;INTR signal P1.3

    adc_port equ P2 ;ADC data pins P2 adc_val equ 30H ;ADC read value stored here

    org 0H start : ;Start of Program

    acall conv ;Start ADC conversion acall read ;Read converted value mov P3 , adc_val ;Move the value to Port 3 sjmp start ;Do it again

    conv : ;Start of Conversion clr cs ;Make CS low clr wr ;Make WR Low nop setb wr ;Make WR High setb cs ;Make CS high

    wait : jb intr , wait ;Wait for INTR signal ret ;Conversion done

    read : ;Read ADC value clr cs ;Make CS Low clr rd ;Make RD Low mov a , adc_port ;Read the converted value mov adc_val , a ;Store it in local variable setb rd ;Make RD High setb cs ;Make CS High ret ;Reading done