Вы находитесь на странице: 1из 45

A Six week training and project report on

8051 Microcontroller and Embedded Systems

Submitted in the partial fulfillment for the award of the degree of the BACHELOR OF TECHNOLOGY In ELECTRONICS AND COMMUNICATION ENGINEERING By YOUR NAME




It was highly educative and interactive to take training at YOUR TRAINING INSTITUTE NAME, PLACE A person technically lacks without having practical knowledge but here it was a good chance for learning and practicing new things to update our self. In a fully equipped environment and well experienced trainers, it was a qualitative program for being known with engineering requirements. Trainers guided me very well and updated me with all the valuable information regarding my course and latest technology. I am highly thankful to the respected Training and Placement Officer and respected Head of Department of Electronics and Communication Department Ms. Nancy Kaur for allowing me to join YOUR TRAINING INST. and motivating me to do the right things. I also take the opportunity to thanks to Mr.Akshay and Mr. Preetfor his precious guidance in field of microcontrollers and interfacing circuits and devices and also sorting out our problems.


Topic 1-Company Profile Topic 2-Introduction to embedded systems Topic 3-Characteristics of Embedded Systems Topic 4-Processors in Embedded System
4.1 Microcontroller vs. Microprocessor 4.2 Microcontroller Families 6

7 8-9 8 9 10-12 10 11 11-12 13-15 13 14 15 15 16-33 16 17 17 19 25 25 26

Topic 5-8051 microcontroller

5.1 AT 89C51 5.2 Pin Diagram of AT89C51 5.3 Pin Description of 8051

Topic 6- Architecture of 8051 microcontroller

6.1 Block Diagram of 8051 6.2 Memory and Registers 6.2.1 SFRs 6.2.2 DPTR

Topic 7- 8051 Assembly Language Programming 7.1 How to Program an 8051 microcontroller
7.2 Instruction Set of 8051 7.2.1 Addressing Modes 7.2.2 Instruction Types 7.3 Flags and PSW (Program Status Word) Register in 8051 7.4 Instructions that affects Flags 7.5 I/O PROGRAMMING

7.6 TIMERS AND COUNTERS 7.7 Serial Port Communication in 8051 microcontroller 7.8 INTERUPTS

27 30 31 34-37 34 35 36 38 39-44 39 39 41 42 45

Topic 8-Interfacing Devices


Topic 1 Company Profile (*replace it with your companys profile

Labs N Racks is the first and only professional CISCO training institute around Haryana, Punjab, Uttaranchal, HP, J & K,and Rajasthan which is providing CCIE training, led by a team of highly qualified CISCO trainers. Labs N Racks was born when experts from the field of internetworking who had significant experience both in industry as well as educational training came together to start their own institute. Labs N Racks is providing CISCO training from the basic level to the advanced level, so the students who want to enter into the field of IT do not find any difficulty in acquiring and developing the required expertise. The leadership of Labs N Racks possesses sound technical knowledge to ensure that Labs N Racks trainers are masters in the internetworking technologies in general and are SMEs (Subject Matter Experts) for the courses they deliver. It is the only institute in the region which has CCIE trainers having a past experience of more than 8 years in the training industry. Labs N Racks aims to strategize relations with global IT majors which set the trends and raise our bar to internationally acclaimed IT power house. Association with the standard setters will facilitate the students getting hands on experience and ready resources for complete all round IT training to excel in any of the large list of fields the ITindustry has. Apart from the networking, Labs N Racks is also an Embedded And Robotic Training Institute certified from Vibe Tech Solutions Limited.

Topic 2 Introduction to Embedded Systems

An embedded system is a special-purpose system in which the computer is completely encapsulated by the device it controls. Unlike a general-purpose computer, such as a personal computer, an embedded system performs pre-defined tasks, usually with very specific requirements. Since the system is dedicated to a specific task, design engineers can optimize it, reducing the size and cost of the product. Embedded systems are often mass-produced, so the cost savings may be multiplied by millions of items. Handheld computers or PDAs are generally considered embedded devices because of the nature of their hardware design, even though they are more expandable in software terms. This line of definition continues to blur as devices expand. Physically, embedded systems range from portable devices such as digital watches and MP3 players, to large stationary installations like traffic lights, factory controllers. Complexity varies from low, with a single microcontroller chip, to very high with multiple units, peripheralsand networks mounted inside a large chassis or enclosure. Embedded systems contain processing cores that are either microcontrollers or digital signal processors (DSP). The key characteristic, however, is being dedicated to handle a particular task. Since the embedded system is dedicated to specific tasks, design engineers can optimize it to reduce the size and cost of the product and increase the reliability and performance. Some embedded systems are mass-produced, benefiting from economies of scale. Robotics and automation are a part of embedded systems itself. Robot development and automation needs study of embedded systems.

Examples of Embedded System are

I. II. III. IV. V. VI. VII. VIII. IX. X. XI. automatic teller machines (ATMs) avionics, such as inertial guidance systems, flight control hardware/software and other integrated systems in aircraft and missiles cellular telephones and telephone switches computer equipment such as routers and printers engine controllers and antilock brake controllers for automobiles home automation products, like thermostats, air conditioners, sprinklers, and security monitoring systems handheld calculators household appliances, including microwave ovens, washing machines, television sets medical equipment handheld computers videogame consoles

Topic 3 Characteristics of Embedded Systems

1. Embedded systems are designed to do some specific task, rather than be a generalpurpose computer for multiple tasks. Some also have real-timeperformance constraints that must be met, for reasons such as safety and usability; others may have low or no performance requirements, allowing the system hardware to be simplified to reduce costs. 2. The program instructions written for embedded systems are referred to as firmware, and are stored in read-only memory or Flash memory chips. They run with limited computer hardware resources: little memory, small or non-existent keyboard or screen. 3. Many embedded systems consist of small, computerized parts within a larger device that serves a more general purpose. For example- a line follower autonomous robot which follows a specific path and moves accordingly to the path. 4. The embedded systems are special purpose computer systems designed to perform only the specific purposes. For Example- a system designed to display numbers cannot be used to operate motors. 5. Embedded systems range from no user interface at all dedicated only to one task to complex graphical user interfaces that resemble modern computer desktop operating systems. Simple embedded devices use buttons, LEDs, graphic or character LCDs (for example popular HD44780 LCD) with a simple menu system.

Topic 4 Processors in Embedded Systems

Embedded processors can be broken into two broad categories. Ordinary microprocessors (P) use separate integrated circuits for memory and peripherals. Microcontrollers (C) have many more peripherals on chip, reducing power consumption, size and cost. In contrast to the personal computer market, many different basic CPU architectures are used, since software is customdeveloped for an application and is not a commodity product installed by the end user. RISC as well as non-RISC processors are found. Word lengths vary from 4-bit to 64-bits and beyond, although the most typical remain 8/16-bit.

3.1 Microcontrollers and Microprocessors

1. A Microcontroller (sometimes abbreviated C, uC or MCU) is a small computer on a single integrated circuit containing a processor core, memory, and programmable input/output peripherals. 2. Microcontrollers are designed to perform specific tasks. Specific means applications where the relationship of input and output is defined. Depending on the input, some processing needs to be done and output is delivered. For example, keyboards, mouse, washing machine, digicam, pen drive, remote, microwave, cars, bikes, telephone, mobiles, watches, etc. 3. Since the applications are very specific, they need small resources like RAM, ROM, I/O ports etc. and hence can be embedded on a single chip.

1. A Microprocessor is an IC which has only the CPU inside them i.e. only the processing powers such as Intels Pentium 1,2,3,4, core 2 duo, i3, i5 etc. 2. Microprocessor find applications where tasks are unspecific like developing software, games, websites, photo editing, creating documents etc.

4. The microcontrollers operate from a few MHz to 30 to 50 MHz 5.The microcontroller is designed for embedded applications. Microcontrollers are used in automatically controlled products and devices, such as automobile engine control systems, implantable medical devices, remote controls, office machines, appliances, power tools, toys and other embedded systems. Table 4.1

3. In such cases the relationship between input and output is not defined. They need high amount of resources like RAM, ROM, I/O ports etc. So needs external RAM, ROM and Memory. 4. Themicroprocessor operates above 1GHz as they perform complex tasks. 5.The microprocessors are used in personal computers or other general purpose applications such as for laptops and heavy applications where complexity is more and memory requirements are high.

So microcontrollers are more preferred over microprocessors for embedded applications because of the simplicity in design and cheaper availability. The system design using microcontroller cost much cheaper than the microprocessors design because memory, RAM, and ROM is built-in in a microcontroller as compared to microprocessor in which external memory and RAM and ROM are to interfaced with it.

4.2 Microcontroller Families

8051- These microcontrollers are old but still trendy and most of the companies fabricate these microcontrollers. The older types of 8051 have 12 clocks per instruction that make it sluggish whereas the recent 8051 have 6 clocks per instruction. The 8051 microcontroller does not have an in built memory bus and A/D converters. In 1980, Intel fabricated the single chip microcontroller 8051 with Harvard architecture.

PIC- Programmable Interface Controller is usually referred as PIC. They are slightly older than 8051 microcontrollers but excel cause of their small low pin count devices. They perform well and are affordable. The Microchip technology fabricated the single chip microcontroller PIC with Harvard architecture. The programming part is very tedious and hence it is not recommended for beginners.

AVR(Advanced Version RISC) - In 1996, Atmel fabricated this single chip microcontroller with a modified Harvard Architecture. This chip is loaded with C- compiler, Free IDE and many more features. This microcontroller is a bit difficult for the starters to handle.

Topic 5 8051 Microcontroller

The most commonly used microcontroller is 8051 families AT89C51 microcontroller which is produced by Atmel. It is widely used in most of the application for having an advantage of simple programming and low cost.

5.1 AT89C51
AT89C51 is an 8-bit, 40 pin microcontroller that belongs to Atmel's 8051 family. ATMEL 89C51 has 4KB of Flash programmable and erasable read only memory (PEROM) and 128 bytes of RAM. It can be erased and program to a maximum of 1000 times. In 40 pin AT89C51, there are four ports designated as P1, P2, P3 and P0. All these ports are 8-bit bi-directional ports, i.e., they can be used as both input and output ports. Except P0 which needs external pull-ups, rest of the ports have internal pull-ups. When 1s are written to these port pins, they are pulled high by the internal pull-ups and can be used as inputs. These ports are also bit addressable and so their bits can also be accessed individually.
5.1.1 Salient Features of AT89C51-

4K Bytes of In-System Reprogrammable Flash Memory Fully Static Operation: 0 Hz to 24 MHz Three-level Program Memory Lock 28 x 8-bit Internal RAM 32 Programmable I/O Lines Two 16-bit Timer/Counters Six Interrupt Sources Programmable Serial Channel Low-power Idle and Power-down Modes 40-pin DIP


5.1.2 Pin Diagram of AT89C51

Figure 5.1

5.1.3 Pin Description of AT89C51 Pins 1-8 (Port 1) - Each of these pins can be configured as an input or an output. Pin 9 (Reset) - A logic one on this pin disables the microcontroller and clears the contents of most registers. In other words, the positive voltage on this pin resets the microcontroller. By applying logic zero to this pin, the program starts execution from the beginning. Pins 10- 17 (Port 3) -Similar to port 1, each of these pins can serve as general input or output. Besides, all of them have alternative functions: Pin 10 (RXD) - Serial asynchronous communication input or Serial synchronous communication output.


Pin 11(TXD) - Serial asynchronous communication output or Serial synchronous communication clock output. Pin 12 (INT 0) - Interrupt 0 input. Pin 13(INT 1) - Interrupt 1 input. Pin 14(T0) - Counter 0 clock input. Pin 15(T1) - Counter 1 clock input. Pin 16(WR) -Write to external (additional) RAM. Pin 17 (RD) -Read from external RAM. Pin 18 and 19(X1, X2) - Internal oscillator input and output. A quartz crystal which specifies operating frequency is usually connected to these pins. Instead of it, miniature ceramics resonators can also be used for frequency stability. Later versions of microcontrollers operate at a frequency of 0 Hz up to over 50 Hz. Pin 20 (GND) - Ground. Pin 21-28 (Port 2) - If there is no intention to use external memory then these port pins are configured as general inputs/outputs. In case external memory is used, the higher address byte, i.e. addresses A8-A15 will appear on this port. Even though memory with capacity of 64Kb is not used, which means that not all eight port bits are used for its addressing, the rest of them are not available as inputs/outputs. Pin 29 (PSEN) - If external ROM is used for storing program then a logic zero (0) appears on it every time the microcontroller reads a byte from memory. Pin 30 (ALE) - Prior to reading from external memory, the microcontroller puts the lower address byte (A0-A7) on P0 and activates the ALE output. After receiving signal from the ALE pin, the external register memorizes the state of P0 and uses it as a memory chip address. Immediately after that, the ALU pin is returned its previous logic state and P0 is now used as a Data Bus. As seen, port data multiplexing is performed by means of only one additional (and cheap) integrated circuit. In other words, this port is used for both data and address transmission. Pin 31 (EA) - By applying logic zero to this pin, P2 and P3 are used for data and address transmission with no regard to whether there is internal memory or not. It means that even there is a program written to the microcontroller, it will not be executed. Instead, the program written to external ROM will be executed. By applying logic one to the EA pin, the microcontroller will use both memories, first internal then external (if exists). Pin 32-39 (Port 0) - Similar to P2, if external memory is not used, these pins can be used as general inputs/outputs. Otherwise, P0 is configured as address output (A0-A7) when the ALE pin is driven high (1) or as data output (Data Bus) when the ALE pin is driven low (0). Pin 40 (Vcc) - +5V power supply.


Topic6 Architecture of 8051 Microcontroller

6.1 Block Diagram of 8051 Microcontroller

Figure 6.1 Address bus-For a device (memory or I/O) to be recognized by the CPU, it must beassigned an address. The address assigned to a given device must be unique. The CPU puts the address on the address bus, and the decoding circuitry finds the device. Data bus-The CPU either gets data from the deviceor sends data to it. Control bus-Provides read or write signals to the device to indicate if the CPU is asking for information or sending it information .


6.2 Memory and Registers

The 8051 microcontroller has a total of 256 bytes of RAM in which 128 is visible or useraccessible and extra 128 is for special function registers. The useraccessible RAM is used for temporary data storage. The user accessible RAM is from the address range 00 to 7Fh. From the user accessible RAM, 32 bytes of RAM is used for registers and rest for Stack operations. The 32 Bytes of RAM is divided into four register Banks i.e. Bank0, Bank 1, Bank 2, Bank3. Each of these banks have 8 Registers i.e. R0 to R7 each. RAMlocations from 0 to 7 are set aside for bank 0 of R0 R7 where R0 is RAM location 0, Rl is RAM location 1, and R2 is location 2, and so on, until memory location 7, which belongs to R7 of bank 0. The second bank of registers R0 R7 starts at RAM location 08 and goes to location 0FH. The third bank of R0 R7 starts at memory location 10H and goes to location 17H. Finally, RAM locations 18H to 1FH are set aside for the fourth bank of R0 R7.

Figure 6.2 Generally for normal operations, Register bank Bank0 is set by default. But we can switch to other banks by using PSW Commands.

Figure 6.3


6.2.1 SFRs (Special Function Register) - These Registers are in extra 128 bytes of the memory. This part of memory is not user accessible and these registers are used for special purposes. These registers range from 80h to FFh. There are a total of only 21 SFRs in this range and all other addresses from 80h to FFh are invalid and there use can cause errors and not valuable results. Some of the SFRs are TCON, SBUF, ACC, B, SCON, TMOD SP, P0, PSW, TL0, and TL1. These all the registers have some specific function that has to be performed after they are programmed. (i) Byte Addressable SFR with byte address SP Stack printer 81H DPTR Data pointer 2 bytes DPL Low byte 82H DPH High byte 83H TMOD Timer mode control 89H TH0 Timer 0 Higher order bytes 8CH TL0 Timer 0 Low order bytes 8AH TH1 Timer 1 High bytes = 80H TL1 Timer 1 Low order byte = 86H SBUF Serial data buffer = 99H PCON Power control 87H. 6.2.2 DPTR - Data Pointer in 8051 16 bit register; it is divided into two parts DPH and DPL. DPH for Higher order 8 bits, DPL for lower order 8 bits. DPTR, DPH, DPL these all are SFRs in 8051.


Topic7 8051 Assembly Language Programming

7.1 How to Program an 8051 microcontroller
[Label:] mnemonic [operands] [; comment] Mnemonics -Assembly level instructions are called mnemonic like MOV R5 Operands -On which the operation is performed. Example: Loop: MOVR1, #25H; transfer 25H into R1 Label mnemonics operand comments The Two instructions which are used to start and terminate program are ORG -This instruction indicate the origin of program, Example- ORG 3000H means program starts from 3000H location. this instruction hasnt take any memory space. It is used to show the starting address of program. END - This instruction show the END of program or it is used to terminate the program. Example: ORG 0H; start compiler from 0h address Again: MOV R5, # 25H; transfer 25H to R5 ADD A, R5; Add the R5 with Accumulator SJMP Again; - jump to the location again END; end the program.

7.2 Instruction Set of 8051

7.2.1 Addressing Modes Addressing modes Register Direct Indirect Immediate Relative Absolute Long Indexed Table 7.1 Instructions MOV A, B MOV 30H,A MOV A,@R0 MOV A,#80H SJMP +127/-128 of PC AJMP within 2K LJMP FAR MOVC A,@A+PC


Register Addressing Mode-The register addressing instruction involves information transfer between registers Example: MOV R0, A The instruction transfers the accumulator content into the R0register. The register bank (Bank 0, 1, 2 or 3) must be specified prior to this instruction. In the Register Addressing mode, the instruction involves transfer of information between registers. The accumulator is referred to as the A register. Direct Addressing Mode- This mode allows you to specify the operand by giving its actual memory address (typically specified in hexadecimal format) or by giving its abbreviated name (e.g. P3).Used for SFR accesses Example: MOV A, P3; Transfer the contents of Port 3 to the accumulator MOV A, 020H; Transfer the contents of RAM location 20H to the accumulator. Indirect Addressing Mode-In the Indirect Addressing mode, a register is used to hold the effective address of the operand. This register, which holds the address, is called the pointer register and is said to point to the operand. Only registers R0, R1 and DPTR can be used as pointer registers. R0 and R1 registers can hold an 8-bit address whereas DPTR can hold a 16-bit address. DPTR is useful in accessing operands which are in the external memory. Examples: MOV @R0, A; Store the content of accumulator into the memory location pointed to by the contents of register R0. R0 could have an 8-bit address, such as 60H. MOVX A, @DPTR; Transfer the contents from the memory location pointed to by DPTR into the accumulator. DPTR could have a 16-bit address, such as 1234H. Immediate Addressing Mode-In the Immediate Constant Addressing mode, the source operand is an 8- or 16-bit constant value. This constant is specified in the instruction itself (rather than in a register or a memory location). The destination register should hold the same data size which is specified by the source operand. Examples: ADD A, #030H; Add 8-bit value of 30H to the accumulator register (which is an 8-bit register). MOV DPTR, #0FE00H; Move 16-bit data constant FE00H into the 16-bit Data Pointer Register. Relative Addressing Mode- The Relative Addressing mode is used with some type of jump instructions like SJMP (short jump) and conditional jumps like JNZ. This instruction transfers control from one part of a program to another. Example: Go Back: DEC A;Decrement A JNZ Go Back;if A is not zero, loop back


Absolute Addressing Mode-In Absolute Addressing mode, the absolute address, to which the control is transferred, is specified by a label. Two instructions associated with this mode of addressing are ACALL and AJMP instructions. These are 2-byte instructions. Example: ACALL PORT_INIT; PORT_INIT should be located within 2k bytes. PORT_INIT: MOV P0, #0FH; PORT_INIT subroutine

Long Addressing Mode-This mode of addressing is used with the LCALL and LJMP instructions. It is a 3-byte instruction and the last 2 bytes specify a 16-bit destination location where the program branches to. It allows use of the full 64K code space. Example: LCALL TIMER_INIT; TIMER_INIT address (16-bits long) is specified as the operand; In C, this will be a function call: Timer_Init (). TIMER_INIT: ORL TMOD, #01H; TIMER_INIT subroutine

Indexed Addressing Mode-The Indexed addressing is useful when there is a need to retrieve data from a look-up table (LUT). A 16-bit register (data pointer) holds the base address and the accumulator holds an 8-bit displacement or index value. The sum of these two registers forms the effective address for a JMP or MOVC instruction. Example: MOV A, #08H; Offset from table start MOV DPTR, #01F00H; Table start address MOVC A, @A+DPTR; Gets target value from the table starts address + offset and puts it in A.

7.2.2 Instruction Types

The 8051 instructions are divided into five functionalgroups: Arithmetic operations Logical operations Data transfer operations Boolean variable operations Program branching operations Arithmetic Instructions-This group of operators perform arithmetic operations. Arithmetic operations affect the flags, such as Carry Flag (CY), Overflow Flag (OV) etc., in the PSW register. The appropriate status bits in the PSW are set when specific conditions are met, which allows the user software to manage the different data formats (carry, overflow etc)


Arithmetic Instructions of 8051 are shown as follows [@ RI] implies contents of memory location pointed to by R0 or R1. Rn refers to registers R0-R7 of the currently selected register bank.

Table 7.2


Logical Instructions-Logical instructions perform standard Boolean operations such as AND, OR, XOR, NOT (compliment). Other logical operations are clear accumulator, rotate accumulator left and right, and swap nibbles in accumulator. Examples: ANL A, #02H; Mask bit 1 ORL TCON, A; TCON=TCON OR A

Table 7.3

Data Transfer Instructions- Data transfer instructions can be used to transfer data between an internal RAM location and an SFR location without going through the accumulator.


It is also possible to transfer databetween the internal and externalRAM by using indirect addressing. The upper 128 bytes of data RAMare accessed only by indirectaddressing and the SFRs areaccessed only by direct addressing.

Figure 7.1 The following is the table for instructions for Data Transfer-

Table 7.4


Boolean Variable Instructions-The Boolean Variable operations include set, clear, as well as and, or and complement instructions. Also included are bitlevel moves or conditional jump instructions. All bit accesses use direct addressing. Examples: SETB TR0; Start Timer0. POLL: JNB TR0, POLL; Wait until timer overflows. The following table contains all the Boolean Variable Instructions of 8051 microcontroller.

Table 7.5


Program Branching Instructions- Program branching instructions are used to control the flow of program execution. Some instructions provide decision making capabilities before transferring control to other parts of the program e.g. conditional and unconditional branches.

the following table contains all the branching instructions

Table 7.6


7.3 Flags and PSW (Program Status Word) Register in 8051

The program status word (PSW)register, also referred to as the flag register, is an 8 bit register. Only 6 bits are used These four are CY (carry), AC (auxiliary carry), P(parity), and OV (overflow) They are called conditional flags, meaning that they indicate some conditions thatresulted after an instruction was execute. The PSW3 and PSW4 are designed as RS0 and RS1, and are used to change the bank. The two unused bits are user-definable. PSW 6 PSW 5 PSW 4 PSW 3 PSW 2 PSW 1 PSW 0






--------- P

Figure 7.2 CY- PSW.7- Carry flag. AC- PSW.6- Auxiliary Carry flag. F0 (-----) - PSW.5- Available to the user for general purpose RS1 -PSW.4 - Register Bank selector bit 1. RS0- PSW.3 -Register Bank selector bit 0. OV -PSW.2 -Overflow flag. F0 (-----) - PSW.1- User definable bit. P- PSW.0 -Parity flag. Set/cleared by hardware each.

7.4 Instructions that affects Flags

Instructions ADD ADDC SUBB MUL DIV DA RPC PLC SETB C CLR C CPL C ANL C, bit ANL C, /bit ORL C,/bit ORL C, bit MOV C,bit CJNE CY X X X 0 0 X X X 1 0 X X X X X X X OV X X X X X AC X X X

Table 7.7



The four 8-bit I/O ports P0, P1, P2 and P3 each use 8 pins. All the ports upon RESET are configured as input, ready to be used as input ports. When the first 0 is written to a port, it becomes an output. To reconfigure it as an input, a 1 must be sent to the port. To use any of these ports as an input port, it must be programmed. 7.5.1 Port 0 It can be used for input or output; each pin must be connected externally to a 10K ohm pull-up resistor. This is due to the fact that P0 is an open drain, unlike P1, P2, and P3. Open drain is a term used for MOS chips in the same way that open collector is used for TTL chips.

Figure 7.3 In order to make port 0 an input, the port must be programmed by writing 1 to all the bits. Port 0 is also designated as AD0-AD7, allowing it to be used for both address and data.

7.5.2 Port 1 Port 1 can be used as input or output. In contrast to port 0, this port does not need any pull-up resistors since it already has pullup resistors internally. Upon reset, port 1 is configured as an input port. To make port 1 an input port, it must be programmed as such by writing 1 to all its bits. 7.5.3 Port 2 Port 2 can be used as input or output. Just like P1, port 2 does not need any pull-up resistors since it already has pull-up resistors internally. Upon reset, port 2 is configured as an input portP0.4. Port 2 is also designated as A8 A15,indicating its dual function.Port 0 provides the lower 8 bits via A0 A7. 7.5.3 Port 3 Port 3 can be used as input or output. Port 3 does not need any pull-up resistors.


Port 3 is configured as an input port upon reset; this is not the way it is most commonly used. Port 3 has the additional function of providing some extremely important signals P3 Function Pin P3.0 P3.1 P3.2 Int0 P3.3 P3.4 P3.5 P3.6 Wr P3.7 Rd Table 7.8 17 Int1 T0 T1 13 14 15 16 Read/ Write Signals Timers External Interrupts Rxd Txd 10 11 12 Serial Communication

7.6 TIMERS AND COUNTERS 7.6.1 Timers

The 8051 comes equipped with two timers, both of which may be controlled, set, read, and configured individually. The 8051 timers have three general functions: 1) Keeping time and/or calculating the amount of time between events, 2) Counting the events themselves, 3) Generating baud rates for the serial port. 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. One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs (TMOD and TCON) which control the timers, and each timer also has two SFRs dedicated to itself (TH0/TL0 and TH1/TL1). The upper higher bits are TH0 and TH1 and the lower bits are TL0 AND TL1 The TMOD and TCON are two control registers for the two timers.


Figure 7.9

(i) TMOD Register

It is used to set the various timer operation mode. TMOD is an 8-bit register where the lower 4 bits are set aside for timer 0 and the upper 4 bits are set aside for timer 1. MSB LSB









Timer 1
Figure 7.10

Timer 0

GATE: To start and stop the timer GATE=1 _HW control: is enabled only while INTx pin is 1and TRx control pin (in TCON) is set. GATE=0 _SW control (used frequently) C/T: Timer or counter selection C/T = 0 _Timer (input from internal system clock) the crystal (1/12) is used to trigger the timer. C/T = 1 _Counter (input from Tx input pin) M1 and M0: Mode selection for timer and counter Mode M1 M0 0 0 0 13-bit timer/counter mode 101 16-bit timer/counter mode 210 8-bit auto reload timer/counter mode 31 1 split timer/counter mode


(ii) TCON Register










TIMER 0 TIMER1 Figure 7.11

TF1: Timer 1 overflows flag TF1=1: Timer/counter 1 overflows. TF1=0: processor vectors to the interrupt services. TR1: Timer 1 run control bit TR1=1: turn Timer 1 ON TR1=0: turn Timer 1 OFF IE1: External interrupt 1 edge flag IE1=1: external interrupt is detected. IE1=0: when interrupt is processed. IT1: Interrupt 1 type control bit IT1=1: falling edge. IT1=0: low level triggered external interrupt. Gate=0, SETB TR1 _Run Timer 1 SETB TR0 _Run Timer 0 Gate=0, CLR TR1 _OFF Timer 1 CLR TR0 _OFF Timer 0

Timer Mode 0
Mode 0: 13-bit Timer/counter mode 0000 ~ 1FFFH

Timer Mode 2
Mode 2: 8-bit auto reload Timer/counter mode (00 ~ FFH). In auto reload, TH is loaded with the initial count and a copy of it is given to TL. This reloading leaves TH unchanged still holding a copy of original values. This mode has many applications, including setting the baud rate in serial communication. Mode 2 Programming 8 bit - 00 ~FFH TH copy to TL Start SETB TR0, or TR1 TL increased FFH (OV monitoring) TH reloads to TL.


7.6.2 Counters
Counter is used to count input pulses. C/T=0: As Time, using 8051s crystal as the source ofthe frequency. C/T=1: As counter, a pulse outside of the 8051 that increments the TH and TL register. When the C/T=1, the counter counts up as pulses are fed from Pins P3.4 (for counter 0) or P3.5 (for counter 1).

7.7Serial Port Communication in 8051 microcontroller

The 8051 microcontroller transmits data serially as well as parallel communication is also done. For serial communication, the microcontroller comes with serial communication pin TXD and RXD. Normally TXD is used for transmitting serial data which is in SBUF register, RXD is used for receiving the serial data. SCON register is used for controlling the operation. The two registers used for controlling the communication are SCON and SBUF. Serial Communication Parallel Communication

Figure 7.12

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

It is possible to write software to useeither of these methods, but the programs can be tedious and long There are special IC chips made by manymanufacturers for serial communications UART (universal asynchronous Receiver transmitter) USART (universal synchronous-asynchronous Receiver-transmitter) 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.

7.7.1 SCON

Figure 7.13 RI(Receive Interrupt Flag)-Set by hardware on receiving. Must be cleared by software


TI (Transmit Interrupt Flag) -Set by hardware on transmitted, must clear by hardware RB8 (Receive bit 8) Mode 2,3 : copy of bit 8 Mode 1 & SM2 clear : copy of stop bit TB8 Transmit bit 8- The 9th data bit of mode 2, 3. Set or clear by software REN Receive Enable- Set by software to enable reception, if is cleared reception will be blocked. SM2 Serial Mode (bit 2) -Use in mode 2,3 for multiprocessor communications. SM1 & SM0 Serial Mode (bit 6 & 7) Operating modes Mode 0- 8-bit shift register, f/12 1Mbit with 12 MHz Oscillator Frequency Mode 1- 8-bit UART, variable baud rate Mode 2 -9-bit UART, f/64 or f/32 187.5K and 375K with 12MHz Oscillator Frequency Mode 3- 9-bit UART, variable baud rate.

7.7.2 SBUF
These are two separate data buffers for transmit and receive. The register SBUF is used to hold both the transmitter and receiver serial port data. To transmit the data, load SBUF register with data. MOV SBUF, source When transmission is complete the TI bit will be set in the SCONregister. When a data frame is received the RI bit in SCON is set high. The received data may then be loaded from SBUF MOV destination, SBUF Data reception is double buffered.

7.7.3 SMOD
Addition bit to double baud speed.

An interrupt is an external or internal event that interrupts the microcontroller to inform it that a device needs its service. The advantage of interrupts is that the microcontroller can serve many devices. Each device can get the attention of the microcontroller based on the assigned priority. The microcontroller can also ignore (mask) a device request for service.

7.8.1 Hardware and Software interrupt The interrupts in a controller can be either hardware or software. If the interrupts are generated by the controllers inbuilt devices, like timer interrupts; or by the interfaced devices, they are called the hardware interrupts. If the interrupts are generated by a piece of code, they are termed as software interrupts. The 8051 controller has six hardware interrupts of which five are available to the programmer. 1. RESET Interrupt - This is also known as Power on Reset (POR). When the RESET interrupt is received, the controller restarts executing code from 0000H location. This is an interrupt which is not available to or, better to say, need not be available to the programmer. 2. Timer interrupts - Each Timer is associated with a Timer interrupt. A timer interrupt notifies the microcontroller that the corresponding Timer has finished counting. Therefore these are two interrupts for the timers. 3. External interrupts - There are two external interrupts EX0 and EX1 to serve external devices. Both these interrupts are active low. In AT89C51, P3.2 (INT0) and P3.3 (INT1) pins are available for external interrupts 0 and 1 respectively. An external interrupt notifies the microcontroller that an external device needs its service. 4. Serial interrupt - This interrupt is used for serial communication. When enabled, it notifies the controller whether a byte has been received or transmitted.

Figure 7.14

The interrupts must be enabled by software in order for the microcontroller to respond to them.


Interrupt Enable Register- There is a register called IE (interrupt enable) that is responsible for enabling(unmasking) and disabling (masking) theinterrupts. EA -------ET2 ES Figure 7.15 To enable any of the interrupts, first the EA bit must be set to 1. After that the bits corresponding to the desired interrupts are enabled. ET0, ET1 and ET2 bits are used to enable the Timer Interrupts 0, 1 and 2, respectively. In AT89C51, there are only two timers, so ET2 is not used. EX0 and EX1 are used to enable the external interrupts 0 and 1. ES is used for serial interrupt. ET1 EX1 ET0 EX0

EA bit acts as a lock bit. If any of the interrupt bits are enabled but EA bit is not set, the interrupt will not function. By default all the interrupts are in disabled mode.



Interfacing an LED with 8051 is easy. The I/O pins are used as output pins. When any of the bit is set to 1, the LED glows if LED n side is connected to ground and p side with bit. And if p side is connected to power and n side to bit, then on bit low, the LED glows. CodeORG 0000h loop: CLR P2.0 CALL DELAY SETB P2.0 CALL DELAY JMP loop delay: mov R7,#100 L1_delay: djnz r7, L1_delay Ret

Figure 8.1


A seven segment consists of eight LEDs which are aligned in a manner so as to display digits from 0 to 9 when proper combination of LED is switched on. Seven segment uses seven LEDs to display digits from 0 to 9 and the eighth LED is used for the dot. A typical seven segment looks like as shown in the figure below.




Figure 8.3


A 16x2 LCD means it can display 16 characters per line and there are 2 such lines. In this LCD each character is displayed in 5x7 pixel matrix. This LCD has two registers. 1. Command/Instruction Register - stores the command instructions given to the LCD. A command is an instruction given to LCD to do a predefined task like initializing, clearing the screen, setting the cursor position, controlling display etc. 2.Data Register - stores the data to be displayed on the LCD. The data is the ASCII value of the character to be displayed on the LCD.



Figure 8.4

Figure 8.5


Interfacing DC motor to 8051 forms an essential part in designing embedded robotic projects. A well designed 8051-DC motor system has essentially two parts. Firstly an 8051 with the required software to control the motor and secondly a suitable driver circuit. L293D-L293 is a dedicated quadruple half H bridge motor driver IC available in 16 pin package. The L293 is designed to provide bidirectional drive currents of up to 1 A at voltages from 4.5 V to 36 V.

Figure 8.6 CodeORG 00H // initial starting address MAIN: MOV P1,#00000001B // motor runs clockwise ACALL DELAY // calls the 1S DELAY MOV P1,#00000010B // motor runs anti clockwise ACALL DELAY // calls the 1S DELAY SJMP MAIN // jumps to label MAIN for repaeting the cycle DELAY: MOV R4,#0FH WAIT1: MOV R3,#00H WAIT2: MOV R2,#00H WAIT3: DJNZ R2,WAIT3 DJNZ R3,WAIT2 DJNZ R4,WAIT1 RET END


TOPIC 9 LCD based digital clock using 8051 microcontroller (AT89C51)

(*you have to replace topic 9 with your project)

A digital clock is one that displays time digitally. The project explained here, displays time on a 16x2 LCD module. The LCD is interfaced with 8051 microcontroller (AT89C51). This circuit can be used in cars, houses, offices etc.

Figure 9.1

9.1 DESCRIPTION This clock works in 24 hour mode and is configured by programming the microcontroller AT89C51. The program uses a delay function for producing a delay of 1 second. The connections in the circuit are as following: port P2 of microcontroller is used as data input port which is connected to data pins (7-14) of LCD. P3^0, P3^1 and P3^6 pins of microcontroller are connected to control pins RS, RW and EN of LCD. P1^0, P1^1, P1^2 and P1^3 pins of microcontroller are connected to tactile switches to take manual inputs. On reset, the LCD prompts the user to set time. Only the hour and minute components can be set by pressing the corresponding switches, repeatedly. These switches are made active low and so they provide ground to the corresponding input pins of the controller. The am/pm mode is set by toggling the switch between ground and Vcc. Ground would set the clock in am mode while Vcc would set it in PM mode. The clock starts when start pin is connected to Vcc by pressing the switch. The set time is displayed on LCD screen and changes as the time passes on. Seconds are increased after every one second by making use of delay function. As second reaches 59, minute is incremented by one and second is reset to 0. Similarly, as minute reaches 59, hour is increased by one and minute is set to 0. After hour reaches 11, minute reaches 59 and second reaches 59, all of them are set to 0 and the AM/PM mode is changed accordingly.


Preset A preset is a three legged electronic component which can be made to offer varying resistance in a circuit. The resistance is varied by adjusting the rotary control over it. The adjustment can be

done by using a small screw driver or a similar tool. The resistance does not vary linearly but rather varies in exponential or logarithmic manner. Such variable resistors are commonly used for adjusting sensitivity along with a sensor. The variable resistance is obtained across the single terminal at front and one of the two other terminals. The two legs at back offer fixed resistance which is divided by the front leg. So whenever only the back terminals are used, a preset acts as a fixed resistor. Presets are specified by their fixed value resistance.

Figure 9.2 AT89C51 Microcontroller AT89C51 is an 8-bit microcontroller and belongs to Atmel's 8051 family. ATMEL 89C51 has 4KB of Flash programmable and erasable read only memory (PEROM) and 128 bytes of RAM. It can be erased and program to a maximum of 1000 times. In 40 pin AT89C51, there are four ports designated as P1, P2, P3 and P0. All these ports are 8-bit bi-directional ports, i.e., they can be used as both input and output ports. Except P0 which needs external pull-ups, rest of the ports have internal pull-ups. When 1s are written to these port pins, they are pulled high by the internal pull-ups and can be used as inputs. These ports are also bit addressable and so their bits can also be accessed individually. Port P0 and P2 are also used to provide low byte and high byte addresses, respectively, when connected to an external memory. Port 3 has multiplexed pins for special functions like serial communication, hardware interrupts, timer inputs and read/write operation from external memory. AT89C51 has an inbuilt UART for serial communication. It can be programmed to operate at different baud rates. Including two timers & hardware interrupts, it has a total of six interrupts.

Figure 9.3

LCD-LCD (Liquid Crystal Display) screen is an electronic display module and find a wide range of applications. A 16x2 LCD display is very basic module and is very commonly used in various devices and circuits. These modules are preferred over seven segments and other multi segment LEDs. The reasons being: LCDs are economical; easily programmable; have no limitation of displaying special & even custom characters (unlike in seven segments), animations and so on. A 16x2 LCD means it can display 16 characters per line and there are 2 such lines. In this LCD each character is displayed in 5x7 pixel matrix. This LCD has two registers, namely, Command and Data. The command register stores the command instructions given to the LCD. A command is an instruction given to LCD to do a predefined task like initializing it, clearing its screen, setting the cursor position, controlling display etc. The data register stores the data to be displayed on the LCD. The data is the ASCII value of the character to be displayed on the LCD.

Figure 9.4


Figure 9.5


9.4 SOURCE CODE FOR DIGITAL CLOCK #include<reg51.h> #define cont_port P3 #define port P1 #define dataportP2 // Data port for LCD #define m_sec 10 sbitrs = cont_port^0; sbitrw = cont_port^1; sbit en = cont_port^6; sbit dig_hr1=port^0; sbit dig_min1=port^1; sbit start=port^2; sbitam_pm=port^3; inthr ,hr1=0; int min,min1=0; int sec,sec1=0,dig_am_pm=0; void delay(unsigned intmsec) // Time delay funtion { inti,j ; for(i=0;i<msec;i++) for(j=0;j<1275;j++); }

void lcd_cmd(unsigned char item) // Function to send command on LCD { dataport = item; rs= 0; rw=0; en=1; delay(1); en=0; return; } void lcd_data(unsigned char item) // Function to send data on LCD { dataport = item; rs= 1; rw=0; en=1; delay(1); en=0; return;

} void lcd_data_string(unsigned char *str) // Function to send string on LCD { int i=0; while(str[i]!='\0') { lcd_data(str[i]); i++; delay(1); } return; } lcd_data_int(inttime_val) // Function to send number on LCD { intint_amt; int_amt=time_val/10; lcd_data(int_amt+48); int_amt=time_val%10; lcd_data(int_amt+48); } void lcd(unsigned char str1[10]) // Function to initialize LCD { lcd_cmd(0x38); //2 LINE, 5X7 MATRIX lcd_cmd(0x0e); //DISPLAY ON, CURSOR BLINKING delay(m_sec); lcd_data_string(str1); } void set_hr1() // Function to set hour { hr1++; if(hr1>11) hr1=0; lcd_cmd(0xc3); lcd_data_int(hr1); lcd_data(':'); } void set_min1() // Function to set minute { min1++; if(min1>59) min1=0;


lcd_cmd(0xc6); lcd_data_int(min1); } void main() { int k; start=1; dig_hr1=1; dig_min1=1; lcd_cmd(0x01); lcd_cmd(0x83); lcd("SET TIMING"); lcd_cmd(0xc3); lcd_data_int(hr1); lcd_data(':'); lcd_data_int(min1); while(start==0) { delay(10); if(dig_hr1==0) set_hr1(); if(dig_min1==0) set_min1(); } if(am_pm==0) { lcd_cmd(0xc8); lcd_data_string("am"); dig_am_pm=0; } if(am_pm==1) { lcd_cmd(0xc8); lcd_data_string("pm"); dig_am_pm=1; } delay(200); lcd_cmd(0x01); while(1) { for(k=0;k<2;k++) { for(hr=hr1;hr<24;hr++) {


for(min=min1;min<60;min++) { for(sec=0;sec<60;sec++) { lcd_cmd(0x82); delay(1); lcd_data_int(hr); lcd_data(':'); lcd_data_int(min); lcd_data(':'); lcd_data_int(sec); if(dig_am_pm==0) { lcd("am"); } else { lcd("pm"); } lcd_data_string(" "); delay(100); } } min1=0; } if(dig_am_pm==0) dig_am_pm=1; else dig_am_pm=0; hr1=0; }}}