You are on page 1of 20

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller

TOPIC 1
89C51 MICROCONTROLLER ARCHITECTURE

89c51 Microcontroller Power Supply Clocking the Microcontroller 89c51 89c51 Microcontroller Reset Ports of 89c51 Microcontroller Registers of 89c51 Microcontroller Memory Organization of 89c51 Microcontroller ALU & Boolean Processor TOPIC 2 TOPIC 3
IDENTIFYING THE PINS OF 89C51 MICROCONTROLLER PROGRAMMING 89C51 MICROCONTROLLER

Page Page Page Page Page Page Page Page Page Page Page Page Page Page Page

Instructions Addressing Modes Directives Program Architecture Subroutine TOPIC 4


INTERFACING SWITCH AND LED

Simple Subroutines

89C51 MICROCONTROLLER ARCHITECTURE


Microcontroller Architecture refers to the organization of different components like processor, memory, timer, data converters and input-output ports inside the microcontroller.

A. 89c51 Microcontroller Power Supply


The c in 89c51 denotes that it is a CMOS device. As usual, it supports a voltage range of +2.7V to +6 V for VCC and 0V for ground. However, in most cases it is operated in accordance with TTL logic level of 0V-5V. It is sensible not to use a 5 V DC adapter to supply power to the microcontroller. This is to reduce the effects of noise and voltage fluctuations. Rather, it is safer to generate a local 5V supply on board. This is done with the use of a voltage regulator IC 7805. Often, we use filter capacitors to filter the propagation noise when a number of devices are connected to the same power supply bus. However, it is better to design the system with separate power supply rails feeding the more sensitive devices on board.

B. Clocking the Microcontroller 89c51


Atmel Microcontrollers can work with a maximum clock frequency of 24 MHz and a minimum of 0 frequency! (Often this feature is utilized in IDLE or POWER DOWN mode).This is termed as fully static operation.
Page 1 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
A clock signal is basically a uniform pulse train applied to sequential logic circuits (circuits capable to store information) for timing control. Now, clock signals or timing signals can be generated by a Crystal Oscillator or a Ceramic Resonator. a) A ceramic resonator is a piezoelectric ceramic material of lead zirconium titanade that produce mechanical vibrations on application of voltage. This is a three pin device and works at a maximum frequency of 10 MHz. b) Whereas, a quartz crystal oscillator supports a much larger range of frequency and produces stable resonance for clocking. 89c51 has an in-built oscillator and only addition of a crystal completes the connection. However take care to connect two 33 pF capacitors as shown in the connection diagram. 89c51 also supports external clocking, especially in case of cascaded microcontroller systems working with the same clock signal. In this case, pin 18 (XTAL2) is kept floating while an inverted clock is applied to pin19 (XTAL1). This method brings in noise and therefore must be avoided.

C. 89c51 Microcontroller Reset


A reset operation (just like the reset switch of your computer) is required to avoid any unusual condition that may arise during the execution of a program. When the microcontroller is reset, all the internal registers, & the program counter are cleared and the stack pointer is initialized at the default value 07H. However, it should be remembered that the RAM remains unaltered. The different types of reset operations are listed below. a) Power-On Reset - The programmer needs to ensure that when the power supply is turned on, the microcontroller must start executing the program from its initial location and avoid working upon some garbage value. When the microcontroller is in normal operation, the reset pin (pin9) has logic 0 and when it turns receives a clock transition, the microcontroller is reset. Thereby, for normal operation, the Reset pin is pulled down to ground by a resistor of typical value 8.2K. In addition, a 10F capacitor is pulled up to +VCC. When the device is in normal operation, the capacitor does not charge up with +VCC dc voltage. However, during a reset period of two machine cycles, 2 s (for a 12 MHz clock) the pin turns high momentarily and the capacitor charges up quickly providing the required voltage level for reset. Remember: With Power-On reset, the register bank0 is selected by default and the stack pointer in initialized right after the bank0, i.e. at 07H. So when a data is pushed onto a stack, it is stored in location 08H. H denotes a hex number (data/address). Concept of stack will be elucidated further later. b) Manual Reset - Reliability is increased with the use of a manual reset circuitry in addition to the power-on reset. A momentary push switch can be connected parallel to the power-on reset
Page 2 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
capacitor to make sure that current does flow from +VCC to ground momentarily when the switch is pressed , thus resuming the normal operating state.

c) Brown-Out Reset - 89c51 is a CMOS device and we all know that CMOS logic allows operation over the range of 3V to 6V. However, the microcontroller may drive TTL logic devices that operate over 0V -5V. Due to supply voltage fluctuations, the TTL devices may fail to obtain the voltage specified for the logic levels while the microcontroller may still be working. In order to avoid such conditions, the Brown-Out reset is used. A power supply voltage sensing circuitry resets the microcontroller if the supply voltage level falls below +5V and retains this condition until the voltage is restored. d) Watchdog Reset - This reset operation is required to prevent the microcontroller from endless loop hanging condition. Watchdog is a timer which checks the continuous functioning of the system at a definite time interval. The microcontroller must reset the watchdog timer periodically before the timer timeout occurs. Under a faulty condition, the microcontroller fails to reset the watchdog before it expires and the watchdog resets the microcontroller. A simple monostable multivibrator can act as a watchdog.

D. Ports of 89c51 Microcontroller


A port is a gateway for transfer of data or address or control signals in and out of the microcontroller. 89c51 has four 8-bit ports which can also be used as 32 individual input/output lines, if required. It is therefore clear that all the 32 input/output lines are bit addressable. Each port has a latch for, an input buffer for temporary storage of received bits and an output driver for sending bits out. Port0 also functions as a multiplexed data bus and lower order address bus (AD0-AD7). Port 2 also functions as higher order address Bus (A8-A15). Port 3 pins have several multiplexed functions apart from I/O functions

PIN P3.0 P3.1 P3.2 P3.3 P3.4 P3.5 P3.6 P3.7

FUNCTION Serial Data Receive Serial Data Transmit External interrupt Internal interrupt External input of Timer/Counter0 External input of Timer/Counter1 Write Strobe for external data memory Read Strobe for external data memory

Page 3 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
All the ports are bidirectional in the sense that they can be configured both for receiving input data and for sending out data. However, ports 1, 2, 3 are called quasi-bidirectional ports and port 0 is the only true bidirectional port. a) Quasi-bidirectional port Port 1, 2, 3 are quasi-bi-directional ports. They have a fixed weak internal pull up resistance. When a logic1 is written onto these ports by some external device the weak pull up turns the status of the port pin high. When a logic0 is to be read, the port pin is pulled down to ground strongly and the status of the port pin turns low. b) True-bidirectional port Port0 is the only true bidirectional port and does not have any internal pull up. When a logic0 is to be read, the port pin is pulled down to ground strongly and the status of the port pin turns low. When a logic1 is to be read in, the status of the port is floating, which is the property of a true bidirectional bus operating according to open collector logic. An external pull up resistance of 10K must be connected to Port0. In open collector logic, the device that intends to send data should send a logic0 to the shared bus and other devices which are idle at that moment must remain floating.

E. Registers of 89c51 Microcontroller


Registers are temporary storage elements for data/address. However, there is a general misconception that registers are separate from the RAM. Registers do occupy a distinct location inside the RAM. Registers can be 8 bits or 16 bits wide. The different registers of 89c51 are listed below. a) General Purpose registers These registers can be used for general operations as sought by the programmer. These include Accumulator Also called register A, 8 bits wide, can be used for general purposes like arithmetic or logical operations, but also included in SFRs due to some special functions. Located at address 0E0H in the upper 128 bytes of internal data memory (SFR) Register B - Yet again another general purpose 8 bit register, but also has special functions for which it is included in the SFRs. Located at address 0F0H in the upper 128 bytes of internal data memory (SFR) Scratch Pad registers There are 8 registers, each 8 bits wide. These registers are named R0 R7. There is a unique concept of Register Bank. There are four register banks, each containing 8 registers R0- R7. At a time only one bank of registers can be selected. Selection of any of the four banks requires only 2 bits. Bit 3 and 4 of a special function register called the program status word act as the register bank select bits. One important point to note, these banks are located on the on-chip RAM.

Page 4 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
Bank0: 00H 07H (R0=00H, R1=01H.R7=07H) Bank1: 80H 0FH (R0=80H, R1=81H.R7=0FH) Bank2: 10H 17H (R0=10H, R1=11H.R7=17H) Bank3: 18H 1FH (R0=18H, R1=19H.R7=1FH) On reset, by default the register bank0 is selected. The registers can also be referred by their direct addresses. Direct address indicates the absolute memory location on on-chip RAM. b) Program Counter It is a special register that holds the memory location or the address of the next instruction to be executed. After an instruction is executed, the PC increments itself automatically and points to the next instruction. More appropriately, it can be called a pointer to the memory location from where the instruction is fetched. PC does not have any address on the on-chip RAM; it is separate from the internal memory. PC is 16 bits wide and therefore can address 64 Kb of memory. c) Special Function Registers The upper 128 bytes of internal memory in 89c51 is reserved for some special function registers and cannot be used as user RAM. They have on-chip address ranging from 80H to 0FFH. These registers can be accessed, i.e. read from and written into by direct addressing only. Some Commonly Used SFR s i. Accumulator - Used for some special operations which cannot use any other register, e.g. ii. B Register - Used for some special operations which cannot use any other register, e.g. multiplication, division iii. Ports Registers 0-3 Data to be sent out is written into these registers and data to be received are read from these registers. These are 8 bit registers. iv. Program Status Word- This register consists of different flags which reflect the status of data manipulation after an instruction is executed. It is an 8 bit register. The PSW format is

Carry

Auxiliary Carry

F0

RegisterSelect1 RegisterSelect0 Overflow

Parity

Carry This flag is set when there is a carry out of the MSB of a number (this number must be formed as a result of arithmetic or logical operation). Auxiliary Carry This flag is set when there is a carry out from the lower nibble and the carry has to be added to the upper nibble of the number (this number must be a BCD number and must be generated due to addition or subtraction). A set of four bits in a byte is called a nibble. A byte therefore contains an upper and a lower nibble. F0 is a user defined flag and can be used for general purposes as sought by the programmer. RS0 & RS1 These flags are used to select the register banks and are cleared due to power on reset. By default they select Bank0.
Page 5 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
Overflow - This flag is set when the carry in to the MSB of a number ( this number must be formed as a result of arithmetic operation) is not equal to the carry out of the MSB Parity A parity bit is a special bit used to check if a data received has some error or not. The number of 1s in a data is used to define the parity of that data. If there is even number of 1s, it is called an even parity, otherwise an odd parity. A received data is again checked for parity at the receiver side. If the parity bit transmitted and the one calculated at the receiver match, the data received is free from error. If the data in the accumulator has odd parity, the parity flag is set, and if the data has even parity, the parity flag is cleared. v. Data pointer- The Data pointer is a 16 bit register used to address external data and code memory. It can address at most 64 Kb memory. The upper byte is called DPH and the lower byte is called DPL. The upper and lower bytes have on chip address 83H AND 82H respectively. It can also be used as a general purpose register. Note, contents of DPTR can be incremented but decrement is not supported. vi. Stack Pointer - Stack is a queue, whose one side is closed. The data which is inserted inside a stack last, has to be retrieved first and vice versa. This method of data retrieval is called Last In First Out. A stack pointer is a register which points to the last data on the stack and has an address 81H. If a data is Pushed In, the stack pointer increases and if a data is Popped Out, it decreases. SP is 8 bits wide and by default is initialized at 07H right after the register bank0.This means that if a data is pushed into the stack it is stored in location starting from 08H. vii. Interrupt Control Registers viii. Timer/Counter Control Registers These registers will be explained in relevant ix. Serial data control registers discussions. x. Power control registers xi. Capture Registers

F. Memory Organization of 89c51 Microcontroller


1. Data & Program Program is a sequence of instructions given to the microcontroller for execution upon some information to obtain a specific result. The information which the instruction works on is the data. For an example, say we have to add two numbers 2 & 3. The instructions we give to the microcontroller is READ NUMBER1 (2) READ NUMBER2 (3) ADD NUMBER1 & NUMBER2 DISPLAY RESULT So this is our program while 2 and 3 are the data.
Page 6 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller

2. Data & Program Memory Von Neumann Architecture - Most of the microprocessors have a single physical memory for storing both program and data and data and address share the same bus on a time-sharing basis (time division multiplexing). This architecture is called the Von Neumann architecture and suffers from Bottle-neck problem. Harvard Architecture - Microcontrollers have a separate data memory and a program memory and independent address and data buses. This kind of architecture is called Harvard architecture. We do not need to change our code very often, so the program memory is essentially a ROM (read only, you cannot write into a ROM). Whereas, the data need to be configured frequently, so the data memory is a RAM (you can read and write in a RAM). 3. Memory Structure Inside the 89c51 microcontroller, we have Internal Program Memory of 4 Kb Internal Data Memory of 256 bytes Apart from this, we can attach if required External Program Memory of 64 Kb External Data Memory of 64 Kb a) Program Memory - The status of the EA pin decides whether external or internal program memory is in use. If the EA pin is high, the internal program memory is in use until all its locations have been read. After that, the instructions are automatically fetched from the external program memory, if EA pin is low, the program executes from the external memory only. b) Data Memory - Out of 256 bytes of internal RAM, lower 128 bytes are user RAM. The upper 128 bytes are not accessible in 89c51 and are used for control of certain peripheral devices like timer, serial communication etc. These 128 bytes therefore comprise of the Special Function Registers. In 89c52, however, the upper 128 bytes are also available as user RAM but is only indirectly addressable. That is, both SFRs and upper 128 bytes of user RAM share same address space, but they have separate physical locations and can be accessed by separate addressing modes only. Addressing modes are techniques to access information stored in RAM /ROM and are discussed later. 4. Internal User RAM Space Utilization a) The first 32 bits or 4 bytes are dedicated for the General Purpose Registers R0 R7 through Bank0 - Bank3

Page 7 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
b) Next 16 bits are bit addressable memory, that is, each of the 128 bits can be treated as a single bit variable. Such variable are often required for storing sensor status or as a flag variable. c) The stack is initialized normally right after the first bank of registers. In case the other banks are used , the stack is removed to a different location d) The rest of the internal RAM can be used as usual. However, care should be taken so that no conflict arises with the stack. e) Internal data memory is accessed by 8 bit address bus, not 16 bit address bus. The reason is self explanatory. 128 bytes require only 8 bits for addressing (28 = 128) 5. Internal Program Memory Access Note, internal code memory is only 4 kb in 89c51. Therefore 16 bit address bus is not required to access internal code memory. Depending on the memory size, required numbers of address lines are used. 6. External Program & Data Memory Access As already known to us, 64 Kb data memory and 64 Kb of program memory can be connected externally to the 89c51 microcontroller, i.e. 16 bit address bus is used for data access.. However, accessing data or code from external RAM/ROM is done with separate commands MOVX & MOVC respectively which we will deal with later. However, direct memory access is not possible from external code or data memory because direct addressing mode does not support 16 bit address. External memory is accessed generally by base + index register addressing mode.

7. Bit Addressable Memory


The locations on on-chip RAM which are bit addressable are In upper 128 bytes (SFR) Accumulator - 0E0H B Register 0F0H Port0 80H Port1 90H Port2 A0H Port3 B0H Interrupt Enable Control register 0A8H Timer/Counter control register 88H Serial Data Control register 98H Program Status Word 0D0H

In lower 128 bytes (user RAM)

Page 8 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
16 bits from 20H to 2FH

H. ALU & Boolean Processor


The Arithmetic & Logic Unit performs the arithmetic operations like addition, subtraction, multiplication etc., and the logic operations like AND, OR etc. 89c51 has a separate Boolean processor other than the normal processor for processing the bit wise operations. Bit manipulation operations have separate instructions and the role of accumulator in such operations is played by the carry flag.

IDENTIFYING THE PINS OF 89C51 MICROCONTROLLER


89c51 is a 40 pin device. External connections of the microcontroller include power supply, clock, reset, I/O ports, data and buses, Read/Write lines, control signal lines and interrupt lines Microcontroller needs power supply. So 2 pins are reserved for +VCC and Ground. Pin 40 is +VCC and pin20 is ground. Microcontroller needs clock signal. 2 pins are reserved for the crystal, pin 18 and pin19 89c51 must have a reset facility. Pin 9 is kept aside for power on / manual reset. Pin1 to pin8 correspond to port1, pin10 to pin17 is port3, pin32 to pin39 is port0 and pin21 to pin 28 is port2. Note that adequate number of pins are not left for data and address bus. A bus is actually a collection of wires used collectively for the same purpose. Port0 has another function apart from being used as an I/O port. It is used as a data bus 8 bits wide. That is why 89c51 is called an 8-bit microcontroller. Basically this means that 89c51 can handle 8 bits of data at a time. However, address bus of 89c51 is 16 bits wide. This means that 89c51 can access 216 memory locations (216 memory locations = 64 kb memory). Port2 has another function other than being used as an I/O port. These 8 bits form the upper byte of the 16 bit address. But, the lower 8 bits of address is again multiplexed with port0. See, so far we have used up 32 I/O lines, 2 power lines, 2 clock lines, 1 reset line, i.e. 37 pins have been used up. 3 pins, pin29 to pin 31 lying between port0 and port2 are control signal lines. Pin29 is PSEN bar - Program store enable is an output control signal used during access of external program memory. When the microcontroller has finished reading an instruction from the external code memory it must send a signal (called the read strobe) to the external program memory to indicate that the microcontroller is ready to read another instruction. To send this signal, PSEN bar is kept at logic0. This pin is pulsed every 6 oscillator period or 6 s.

Page 9 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
Pin30 is ALE - We know that port0 is also used as a multiplexed data and address bus where these 8 bits form the lower byte address of the address bus. Now, an external memory (data or program memory) can use these 8 bits as a data bus and also as address bus. In order to understand whether it is currently used as a data bus or an address bus, ALE is used It latches the low order address when port0 is used as address bus. For external program memory ALE pin is pulsed every 1/6 oscillator period or 0.16 s. For external data memory one external pulse is skipped. Pin31 is EA bar - This pin indicates whether the external program memory or the internal program memory is in use. When this pin is kept high, instructions are executed from internal program memory until all locations of 4 kb program memory (89c51) has been read. After that instructions are automatically fetched from external program memory. If this pin is held low, instructions are executed from external program memory only. 8 bits of Port3 have other multiplexed functions too apart from being used as an I/O port. a) b) c) d) e) f) g) h) Pin10 is RXD Receiver line for serial data (input) Pin11 is TXD Transmitter line for serial data (output) Pin12 is INT0 bar external interrupt 0 (input) Pin13 is INT1 bar- external interrupt 1 (input) Pin14 is T0 timer/counter 0 external interrupt (input) Pin15 is T1 timer/counter 1 external interrupt (input) Pin16 is WR bar write signal for external data memory (output) Pin17 is RD bar read signal for external data memory (input)

PROGRAMMING THE 89C51 MICROCONTROLLER A. Instructions


Instructions are commands given to the microcontroller to fetch, process and store data. Microcontroller understands only binary commands and therefore an instruction in a typical machine language is a string of 1s and 0s. This string of bits (binary digits) has two parts the opcode and the operand(s). The opcode indicates the actual operation that has to be done. The operand(s) may be data or address or even a register. When an instruction is written in assembly language, a symbolic name corresponding to the opcode is written and this is called a mnemonic. The mnemonic is followed by the operand(s).The typical format is MNEMONIC DESTINATION OPERAND SOURCE OPERAND

B. Addressing Modes

Page 10 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
Addressing Modes refer to the methods of accessing the operands. There can be five types of access a) Immediate Addressing - When the operand is purely a data, i.e. more specifically a number, it is called an immediate data. An immediate data is denoted by a # preceding it. For e.g., #32H indicates it is a hexadecimal number 32 (whose decimal equivalent is 50). In immediate addressing mode, one of the operands is an immediate data. The other operand may be a register or an address. Remember, address or a RAM location can be accessed directly or indirectly. b) Example of Immediate Addressing: MOV A, #45H.

c) Direct Addressing

- A direct address is one which refers to the absolute RAM location. For example, 50H is an absolute or direct address in user RAM of 128 bytes that starts from 00H to 7FH. In direct addressing mode one of the operands is a direct address and the other may be a register or an immediate data or even another direct or indirect address. E.g. MOV A, 54H Remember: Direct Addressing is the only method of access for the SFRs

d) Register Addressing

- This is now clear that register addressing uses one of its operands a register, but the other operand cannot be a register too unless it is the Accumulator or register B. Registers that are used in this mode of addressing are the general purpose registers A, B, the carry bit or C of the PSW register, the data pointer register DPTR and the scratch pad registers R0 to R7 of all the banks0-3. However, MOV A, 36H is not a register addressing mode. If A is one of the operands, it is a register addressing mode only if the other operand is another register only. For e.g. MOV A, R3.It is often used to create counters and delay routines. Remember: MOV R0, R3 is not allowed

e) Register Indirect Addressing - An Indirect address is one in which the immediate data content of a specified register is the absolute address on user RAM. For e.g. MOV A, @ R1. Let us assume R1 contains an immediate data 54H. So this addressing mode indicates that 54H is an absolute memory location and the data stored in that location is copied into A. Say, the absolute address 54H contains #20H. So in short, the instruction means immediate data 20H is copied into A. An indirect address is indicated by the symbol@ preceding the register. The registers used are R0 and R1 of any bank and the DPTR. The other operand can be an immediate data or A or a direct address. Remember: This addressing mode can access operands only from lower 128 bytes of on-chip RAM in 89c51 and the lower 256 bytes of external RAM Only R0, R1 and DPTR can be used MOV R0,@R1 is not allowed

f) Base Register + Index Register Addressing - This is the only mode which makes use of a 16 bit register which is mostly the DPTR and rarely the PC. Note that in this mode one of the
Page 11 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
operands is a compound address evaluated from both the Base and Index register. The other operand is essentially the Accumulator. Let us take an example. MOV A, @A+DPTR. Say, A contains an immediate 8 bit data 20H and the DPTR contains a 16 bit address 0050H. So the compound address now becomes 0070H. So the instruction now copies the contents of the calculated address 0070H into A. It is often used to access look-up tables. Remember: MOV A, @DPTR is not base + index register addressing; it is register indirect addressing mode.

C. More About Instructions


The instructions supported by 89c51 can be classified as a) Data Transfer Instructions The data transfer instructions do not affect any flag. MOV, the most common data transfer instruction has two other variations MOVC and MOVX for data transfer from external data memory and code memory respectively. MOVX and MOVC always use register indirect or base +index register addressing. Two other data transfer instructions are the Exchange (XCH) and the Exchange Digit (XCHD) instructions. XCH exchanges the content of a register with the accumulator and XCHD exchanges the lower nibble of the content of a register with the lower nibble of the accumulator. Stack operations like Push and Pop are also data transfer instructions. PUSH and POP take only direct addresses as operands. During PUSH operation, the Stack pointer is incremented first, and then the data is pushed onto stack. During POP operation, the data are retrieved first, and then the stack pointer is decremented. b) Arithmetic Instructions Common arithmetic instructions are Add (ADD), Add with Carry (ADDC), Subtract (SUB), Subtract with Borrow (SUBB), Increment (INC), decrement (DEC) , multiplication (MUL), division (DIV). All of these instructions must have A register as one of the operands and MUL and DIV takes only Registers A and B as the operands. Arithmetic instructions affect the carry, auxiliary carry, zero and the overflow flags. Another arithmetic instruction is the Decimal Adjust and is operable only on the accumulator for adjusting a hex number into its respective decimal equivalent. c) Logical Instructions The logical instructions affect the carry and the zero flag. Common logical instructions are, And (ANL), Or (ORL), and Xor (XRL). Clear (CLR) and Complement (CPL) and Swap (SWAP) are the other logical instructions. Another category of logical operation is Rotate. Relevant commands are Rotate Right (RR), Rotate Right through carry (RRC), Rotate Left (RL), and Rotate Left through carry (RLC). Rotating an 8-bit data right shifts the bits by one place to the
Page 12 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
right and the least significant bit assumes the position of the most significant bit. Rotate right through carry indicates that the carry bit moves to the MSB position while the LSB moves into the carry bit. Similar concept applies for rotate left operations. All logical instructions must involve the accumulator. d) Boolean Variable Manipulation Instructions These instructions are used for processing bit type of variables and they affect the carry and the zero flags. These instructions are, data transfer instructions like MOV, logical instructions like ANL, ORL, CLR, CPL etc. Another bit manipulation instruction is SETB to set any bit. Besides, it also supports conditional branching instructions like Jump if Bit (JB), Jump if not bit (JNB), Jump if carry (JC), Jump if no Carry (JNC), Jump if bit is set and clear the bit (JBC). e) Branching Instructions These can be of two types, conditional and unconditional. Unconditional branching can be of two types Call and Jump. CALL and RET (return) instructions are used in conjunction. It is similar to a function call. When a subroutine is called, the present address is stored in the stack and the program counter loads the address of the subroutine. After the subroutine execution is completed, the control is returned to the location from where it had been called. This is done by the return instruction. In case this is an Interrupt Service Routine, RETI (return from interrupt) is used for return. CALL is of two types, ACALL and LCALL. ACALL is used to call a subroutine within a 2Kilo Byes memory page and LCALL is used to call a subroutine within 64 Kilo bytes of memory. Unconditional Jump - By using a jump instruction, the control simply moves to a branched location and continues to execute instructions thereof. Jump instructions do not use Stack. Unconditional Jump Instructions are short jump (SJMP), absolute jump (AJMP), long jump (LJMP). Short jump is the only relative jump where the control can jump from -128 bytes to 127 bytes relative to the location of the instruction. AJMP is an 11 bit jump, i.e. the control can jump to an absolute location within a 2K byte memory page. LJMP is a 16 bit jump, i.e. the control can jump to an absolute location anywhere in the total memory of 64 kilo bytes. Conditional Jump When these instructions are used, the control jumps to a specified location only if the condition is satisfied. Two important instructions under this category are DJNZ (Decrement & Jump if Not Zero) decrements the value of an operand and jumps to the specified location if the value of the operand is non zero. It behaves similar to a for loop. Syntax is DJNZ R0, ADDR16 (16 bit jump address) R0=10; for (; R0>0;R0--) { Statement1; } MOV R0,#10 CONT_LOOP: Statement1 DJNZ R0, CONT_LOOP

Page 13 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
CJNE (Compare & Jump If not Equal To) compares the value of an operand with that of another operand and jumps to a specified location if they are unequal. It behaves like if-else branching. Syntax is CJNE R0, #5H, 0063H if (R0==5) { Statement1; } else { Statement2; }

CJNE R0,#5H, NOT_5 Statement1 NOT_5: Statement2

Other conditional Jumps are jump if zero (JZ), jump if not zero (JNZ), jump if bit (JB), jump if not bit (JNB), jump if carry (JC), jump if no carry (JNC), Jump if bit and clear the bit (JBC).

D. Directives
We know that corresponding to each command issued to the microcontroller a string of binary code (machine language) is generated by the assembler. However, in an assembly language program there are certain commands whose corresponding machine code is not generated. These are called pseudocodes i.e. not true codes. These are the Assembler Directives. They are not part of the actual program and are only auxiliary instructions, but nonetheless important. These instructions indicate the start and end of a program. Functions like defining a constant can also be implemented by the Assembler Directives. a) ORG (origin) - This directive takes a single operand, a direct address and indicates that the source program starts from the address specified. E.g. ORG 0050H b) END (end) - This directive does not take any operand and denotes the end of the source program file. c) DB (define byte) This directive is used to define a variable of 1 byte. The variable can be a decimal/hex/binary number and specified by D/H/B respectively just after the number. The variable can also be a string or ASCII number. For strings and ASCII numbers, they must be written within Quotes. The corresponding ASCII value of the byte defined this way is stored in the locations following the instruction. E.g. DB 32B, DB ABCDE, DB A d) EQU (equate) This directive is used to define a constant, just like macros in C language. A label is given to a constant and varying the value of the constant changes the values of all instances of that label in the program. E.g. TEMP EQU #39H. The assembler replaces all instances of TEMP with the immediate hex number 39.Often used to define the SFR addresses and ports. For e.g. P0 EQU 080H
Page 14 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
MOV P0, #FFH e) BIT (bit type variable) - This directive takes a single operand, and functions similar to equate directive, but for a bit type variable. For e.g. LED_RED BIT P0.1

E. Bitwise Instructions
Conditional jump, data transfer, logical operations, complement and set/reset of bit operations can be done with bit manipulation instructions. Carry flag acts as the accumulator. Some common instructions are shown below Instruction CLR BIT/C SETB BIT/C CPL BIT/C ANL C, BIT ORL C, BIT MOV C, BIT JB BIT, XXH JNC XXH JBC BIT, XXH Function Clears bit/carry Set bit/carry Complement bit/carry Logical AND of carry and bit Logical OR of carry and bit Move content of bit to carry If bit is set, jump to location XXH If carry is not set, jump to location XXH If bit is set, jump to location XXH & then clear bit

F. Program Architecture
Writing an efficient assembly language program requires the concept of structured programming. A program is said to be structured when the entire task is divided into smaller subtasks and each subtask is written and tested independent of other. This is also called maintaining modularity of the code. This not only helps debugging but also makes it easy to modify the program. Besides, it is essential to include relevant comments for easy interpretation of the code. By program architecture we mean the structural components of a program. The Program Flow can be shown with the help of a flow diagram. A sample program structure is shown below.

; ******************************** ; OBJECTIVE OF THE CODE ; ******************************** ; ///////////SYSTEM REGISTERS DEFINITION///////////


Page 15 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
IE SP EQU 0A8H EQU 081H

; ///////////LOCAL BYTE VARIABLE DEFINITION///////////// PTR EQU 07FH ; /////////BIT VARIABLE DEFINITION////////////// SENSOR2 EQU P1.1 LED_RED EQU P0.6 ; ////////PORT PIN DEFINITION/////////// P0 EQU 080H P1 EQU 090H ; //////////MAIN PROGRAM//////// 0050H START: ACALL INITIALISATION ACALL MAIN AJMP START MAIN: ACALL SUBROUTINE 1 ACALL SUBROUTINE 2 AJMP MAIN ; //////////INITIALISATION////////// MOV COUNTER, #0FFH MOV SP, #06FH RET ; //////////SUBROUTINE 1////////// LABEL: MOV A, #054H DJNZ A, LABEL RET ; /////////SUBROUTINE 2/////////// MOV A, #023H RET END
Page 16 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller G. Subroutines
Subroutine is a chunk of code that carries out a subtask independent of the main program. A subroutine may refer to or call another routine for executing its task. After a subroutine executes all its instructions it returns the control back to the portion of the main program or another subroutine from where it has been called.

INTERFACING SWITCH AND LED


Before we can start testing what we have learnt so far, one more thing is left interfacing input and output devices with the microcontroller. a) Interfacing Switch - An input device can be a switch or a sensor or another subsystem. For the time being let us restrict our discussion to pushbutton switches only. A pushbutton switch is one which closes momentarily when the switch is pressed and opens when the switch is released. While connecting a switch to a microcontroller, two points must be kept in mind Key Debounce has to be implemented - When a key is pressed, instead of a single pulse, as desired, the microcontroller receives multiple pulses due to mechanical vibration. This may affect the following objectives to be performed by the microcontroller. To reduce this bouncing effect a suitable delay is introduced in the program assuming that the user cannot make a second key press within that duration, once a key has already been pressed. External pull up resistor must be connected if Port 0 is used. Again, remember while programming, Remember: When the switch is not pressed, status of the pin is HIGH When the switch is pressed, status of the pin is LOW b) Interfacing LED - An output device can be a motor, or a relay or a display. For the time being let us discuss only about interfacing a LED.A Light Emitting Diode is a semiconductor device which emits visible light when a voltage is applied across its terminals. While connecting an LED to a microcontroller, again few things should be remembered Sourcing & Sinking current in microcontroller is 20mA and 25mA respectively - when current flows from + VDD to a port pin it is called sourcing current and when current flows from a port pin to ground it is called sinking current. Microcontroller can sink current, cannot source current. A current limiting resistor must be used to limit the current flowing through the LED An LED cannot be connected between a port pin and ground, always it has to be between a port pin and +VCC. This is because a microcontroller port pin is normally at high logic level due to weak pull up. If a LED is connected between a port pin and ground, the LED will always glow even if no data is sent to that pin. So remember while programming, Remember: Send logic 0 to port pin to glow a LED
Page 17 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
Send logic 1 to port pin to turn off a LED

SIMPLE SUBROUTINES
1. To glow the RED LEDs and turn OFF GREEN LEDs MAIN: CLR REDLED_1 CLR REDLED_2 SETB GREEDLED_1 SETB GREENLED_2 HERE: AJMP HERE Note: Do not forget to define the port pins connected to LEDs and initialize their status to OFF condition 2. To glow RED LED when switch A is pressed and GREEN LED when switch B is pressed MAIN: MOV C, SWITCHA MOV REDLED, C MOV C, SWITCHB MOV GREENLED, C AJMP MAIN Note: Do not forget to define the port pins connected to LEDs & switches and initialize their status to OFF condition 3. When switch A is pressed, RED LED starts to glow and GREEN LED turns OFF; when switch B is pressed, GREEN LED starts to glow and RED LED turns OFF LOOP: JB SWITCHA, SKIP_RED CLR REDLED SETB GREENLED SKIP_RED: JB SWITCHB, LOOP SETB REDLED CLR GREENLED AJMP LOOP Note: Do not forget to define the port pins connected to LEDs & switches and initialize their status to OFF condition 4. When switch is pressed once, LED starts to glow; when pressed again, LED turns OFF LOOP: JB SWITCHA, LOOP CPL REDLED ACALL DELAY
Page 18 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
AJMP LOOP Note: Here, we have to incorporate a key Debounce routine in order to ensure that one key press generates a single pulse and not a train of redundant pulses that might trigger the LED a number of times. This is implemented by inserting a certain delay during which, key press is not possible for a second time by any human being. 5. Generating a delay of 1s Calculation of delay: Let, frequency of crystal =12 MHz & so time period = (1/12) s = length of 1 clock cycle Most of the instructions take 1 instruction cycle (1 instruction cycle =12 clock cycles) each. Therefore, time taken by 1 instruction = 12 X (1/12) = 1 s Eg 1 LOOP: MOV R0, # 255 DJNZ R0, LOOP DJNZ takes 2 instruction cycles and R0 being an 8 bit register can hold a maximum value of 255 in decimal. So delay produced as the loop continues for 255 times is (255 X 2) +1 s = 511 s Eg2 DELAY: MOV R0, #FFH MOV R1, #FFH LOOP1: DJNZ R0, LOOP1 MOV R0, #FFH DJNZ R1, LOOP1

Using a nested loop with 2 8 bit registers, we get a delay of [{(255 X 2) + 1+ 2} (255)]+ 2 = [(3 + 510) (255)] + 2 = (513 X 255) +2 = 130817 s = 0.13 s So, 2 registers are still not sufficient for 1 s delay generation. Therefore we use 3 registers in nested fashion loaded with values 255, 255 and 15 respectively. Here follows an example of delay generation of 1s by parameter passing. Eg3 MAIN: MOV R2, #15D ACALL DELAY1s . . .

DELAY1s: MOV R0, #FFH MOV R1, #FFH LOOP1: DJNZ R0, LOOP1 MOV R0, #FFH
Page 19 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

The Advanced Robotics and Electronics Laboratory BASIC COURSE ON ROBOTICS & EMBEDDED SYSTEMS SECTION 1 Introduction to Microcontroller
DJNZ R1, LOOP MOV R1, #FFH DJNZ R2, LOOP RET 6. Continuously blinking an LED LOOP: SETB REDLED ACALL DELAY CLR REDLED ACALL DELAY AJMP LOOP 7. To blink GREEN LED twice and then it turns OFF; then RED LED blinks thrice and then turns OFF. MAIN: MOV B, #06 LOOP1: CPL REDLED ACALL DELAY DJNZ B, LOOP1 MOV B, #04 LOOP2: CPL GREENLED ACALL DELAY DJNZ B, LOOP2 AJMP MAIN

Page 20 2008 The ARELAB. All Rights Reserved. Distributing this literature in any form without the written permission from The ARELAB is strictly prohibited

You might also like