08.601 MBSD Module 2

86
08.601 Microcontroller Based System Design Module 2 Programming Timer /Counter Two 16 bit timers SFRs for programming timer/counter are: 1. TCON 2. TMOD 3. T0 (as TH0 and TL0) 4. T1 (as TH1 and TL1) TCON To control timer/counter operation Byte and Bit addressable, where 88H is byte address and 88H (TCON.0), 89H (TCON.1), 8AH (TCON.2), …….are bit address Bit orientation: Department of ECE, VKCET Page 1

Transcript of 08.601 MBSD Module 2

Page 1: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Module 2Programming Timer /Counter

• Two 16 bit timers• SFRs for programming timer/counter are:

1. TCON2. TMOD3. T0 (as TH0 and TL0)4. T1 (as TH1 and TL1)

TCON• To control timer/counter operation• Byte and Bit addressable, where 88H is byte address and 88H (TCON.0), 89H

(TCON.1), 8AH (TCON.2), …….are bit address• Bit orientation:

Department of ECE, VKCET Page 1

Page 2: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

TMOD• Timer Mode control SFR• 8-bit register, byte address is 89H• Bit orientation:

• Upper nibble for timer 1 and lower nibble for timer 0

8051 Timer modes: 1. Mode 1 programming

• 16 bit timer/counter• TLx hold lower byte of timer/count value (00H to FFH)• THx hold upper byte of timer/count value (00H to FFH)• Allows 0000H to FFFFH values• TLx acts as 8-bit prescaler

Department of ECE, VKCET Page 2

Page 3: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Steps to program:1. Select timer by TMOD register2. Load THx and TLx values3. Run timer by setting TRx bit in TCON4. Overflows occur TFx becomes high and monitoring it get the delay by timer or count

value5. Stop the timer by TRx = 06. Clear the flag TFx = 07. For continuous operation repeat the process from loading values to THx and TLx

Department of ECE, VKCET Page 3

Page 4: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

To design count value for delay in mode 1 operation• If f is Xtal frequency, then ft = f / 12 is timer frequency• Timer operation is based on time period Tt = 1/ft seconds • Let f = 12MHz , ft = 1MHz and Tt = 1us• If THx and TLx hold XXYYH (16 bit ) count value, then overflow occurs

when it incremented from FFFFH to 0000H• Then delay Td = (FFFFH – XXYYH + 1) Tt

In decimal Td = (65535 – N + 1) Tt, where N is the count value in decimal

Example:Count value for delay 1ms with 12MHz Xtal frequency.

From the above equation, N = 65536 – (Td /Tt) = 65536 – (1m / 1µ)N = 64536 = FC18HThen THx = FCH and TLx = 18H are the initial count values to provide

1ms delay.Program 1:

Program to generate square wave of 10kHz at pin P1.7 using timer 0 (Xtal frequency to 8051 is 11.0592MHz)

Solution:Design for count value :– For 10kHz square wave, time period

T = 1/10k = 100µsAnd Ton = Toff = T/2 = 50µs

Then desired delay Td = 50µsFor timer in mode 1, count value N = 65536 – (50µs / 1.0851µs)

[Xtal frequency f = 11.0592MHz, timer frequency ft = 0.922MHz and Tt = 1.0851µs]N = 65489.9 ≈ 65489 = FFD1HInitial count value to THx = FFH and TLx = D1H

Department of ECE, VKCET Page 4

Page 5: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Program:ORG 0MOV TMOD, #00000001B ; Timer 0 , sw controlled , and mode 1

REPEAT: MOV TH0, #FFH ; Higher byte of 16-bit initial countMOV TL0, #D1H ; Lower byte of 16-bit initial countCPL P1.7ACALL DELAY ; 50µs delayCPL P1.7ACALL DELAYSJMP REPEAT

DELAY: SETB TR0WAIT: JNB TF0, WAIT

CLR TR0CLR TR0RETEND

Department of ECE, VKCET Page 5

Page 6: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

2. Mode 0 programming• Similar to mode 1, but 13-bit timer operation• Least five bit of TLx as 5-bit prescaler timer and THx as 8-bit register

• 0000 to 1FFFH count values • Count value N = 8192 – (Td / Tt)• Let N = 8182 = 1FF6H = 0001 1111 111 1 0110 b

Then load TLx = 0001 0110b = 16H and THx = 1111 1111b = FFH• All other operations are similar to mode 1

3. Mode 2 programming• 8-bit auto reload mode, values ranges from 00H to FFH and THx hold it

• Count value N = 256 – (Td/Tt)

Steps to program:• Select timer by TMOD• Load count value to THx and TLx • Start timer by TRx = 1• When overflows in TLx results TFx set to 1 and THx value reloaded to TLx • Stop timer by setting TRx = 0 and reset flag TFx = 0• For continuous operation, start timer again

Department of ECE, VKCET Page 6

Page 7: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Program 2:Program to generate square wave 100 kHz at P1.0 (Xtal frequency to 8051 is 11.0592MHz)

Solution:Design for count value:Required delay Td = 5µs, timer time period Tt = 1.0851 µsCount value N = 256 – (5/1.0851) = 251.39 ≈ 251 = FBH

Program:ORG 0MOV TMOD,#00100000B ; Timer 1, sw controlled and mode 2MOV TH1,#0FBH ; Count value for 5µsMOV TL1,TH1

RESTART: CPL P1.0ACALL DELAYSJMP RESTART

DELAY: SETB TR1 WAIT: JNB TF1, WAIT

CLR TR1CLR TF1RETEND

4. Mode 3 programming• Split timer mode• Timer 0 is split into two 8-bit timers• TL0 to hold count value for timer 0 with over flow setting in TF0• TH0 to hold count value for timer 1 (Timer 1 stopped from other mode, but

can be switched into mode 0, 1 or 2) with overflow setting in TF1

Department of ECE, VKCET Page 7

Page 8: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Counter programming• Timer as event counter• Pulse outside from the microcontroller is source of frequency• Modes, THx and TLx registers are same as timer operation• C/T bit in TMOD is set as 1 activate timer as counter

Counter applications:• To count objects, measure unknown frequency etc.• P3.4 (T0) and P3.5 (T1) pins are used

Program 3:System to measure unknown frequency and display it to LCD:

Solution:Circuit diagram:

(Xtal and RST connections are not shown)Department of ECE, VKCET Page 8

Page 9: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Program:INPUT BIT P3.4RS BIT P2.0RW BIT P2.1E BIT P2.2LCD_DATA EQU P1

ORG 0MAIN: MOV TMOD,#00010101B ; Timer 1 as mode 1 timer & timer 0 as

;counter in mode 1SETB INPUTACALL LCD_INITACALL DELAY

CONTINUE: MOV A,#80H ; DDRAM address of LCDLCALL CMD_WRITELCALL DELAYMOV TL0,#00 ;Lower byte initial count value MOV TH0,#00 ;Higher byte initial count valueSETB TR0 ;Start counterACALL DELAY_1S ;Wait 1 secondMOV A,TL0 ;Load lower byte count value to AACALL HEX_2_BCD ;Convert count value to BCDMOV A,R7 ;3rd digit of BCD to AACALL BCD_2_ASCII ;Convert BCD to ASCIIACALL LCD_DISPLAY ;Display 3rd digit to LCDMOV A,R6 ; 2nd digit of BCD to AACALL BCD_2_ASCII ;Convert BCD to ASCIIACALL LCD_DISPLAY ;Display 2nd digit to LCDMOV A,R5 ; 1st digit of BCD to AACALL BCD_2_ASCII ;Convert BCD to ASCII

ACALL LCD_DISPLAY ;Display 1st digit to LCDCLR TR0 ;Stop counterCLR TF0 ;Clear counter flagACALL DELAY ;Wait a short timeSJMP CONTINUE ;Repeat the process

DELAY: MOV TH1,#0F8H ; 2ms delay programDepartment of ECE, VKCET Page 9

Page 10: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

MOV TL1,#0CDHSETB TR1

WAIT_2m: JNB TF1,WAIT_2mCLR TR1CLR TF1RET

DELAY_1S: MOV R0,#0FH ;1 second delay programNEXT: MOV TH1,#00

MOV TL1,#00SETB TR1

WAIT_1S: JNB TF1,WAIT_1SCLR TR1CLR TF1DJNZ R0,NEXTRET

;LCD initializingLCD_INIT: CLR E ;E = 0

MOV A,#38H ;8-bit, 2 line and 5 x 7 dot functionLCALL CMD_WRITELCALL DELAYMOV A,#01H ;Clear displayLCALL CMD_WRITELCALL DELAYMOV A,#0CH ;Display on, Cursor offLCALL CMD_WRITELCALL DELAYMOV A,#06H ;Increment (Left entry)LCALL CMD_WRITELCALL DELAYRET

CMD_WRITE: MOV LCD_DATA,A ;Command to LCD data busCLR RW ;RW = 0CLR RS ;RS = 0SETB E ;E = 1Department of ECE, VKCET Page 10

Page 11: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

LCALL DELAYCLR E ;E = 0SETB RW ;RW = 1SETB RS ;RS = 1RET

DATA_WRITE: MOV LCD_DATA,A ;Data to LCD data busSETB RS ;RS = 1CLR RW ;RW = 0SETB E ;E = 1LCALL DELAYCLR E ;E = 0CLR RS ;RS = 0SETB RW ;RW = 1RET

LCD_DISPLAY: ACALL DATA_WRITERET

HEX_2_BCD: MOV R1,AMOV B,#64HDIV AB ;Hex number divided by 100MOV R7,A ;3rd digit of BCD to R7MOV A,B ;Reminder to AMOV B,#0AHDIV AB ;Reminder divided by 10

MOV R6,A ; 2nd digit of BCD to R6MOV R5,B ;Reminder is 1st digit of BCD and move to R5RET

BCD_2_ASCII: ADD A,#30H ;Add BCD to 30HRETEND

Department of ECE, VKCET Page 11

Page 12: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Program 4Program to display count value of 1Hz pulse up to 60 pulses:Circuit diagram is similar to previous example

RS BIT P2.0RW BIT P2.1E BIT P2.2INPUT BIT P3.4LCD_DATA EQU P1

ORG 0MAIN: SETB INPUT

MOV TMOD,#00010110B ; Timer 0 as counter in mode 2 & timer 1 as ;timer in mode 1

MOV TH0,#0C4H ; Initial count to timer 0, 256 – 60 = 196 = C4H MOV TL0,TH0LCALL LCD_INIT

CONTINUE: SETB TR0 ;Start counterNEXT: MOV R3,TL0 ;Current count value to R3

MOV A,#88H ; DDRAM addressACALL CMD_WRITEACALL DELAYMOV A,R3 ;Current count value to AADD A,#3CH ;Current count + 60ACALL HEX_2_BCDMOV A,R6 ;2nd digit of BCDACALL BCD_2_ASCIIACALL LCD_DISPLAYACALL DELAYMOV A,R5 ; 1st digit of BCDACALL BCD_2_ASCIIACALL LCD_DISPLAYACALL DELAYJNB TF0,NEXT ;If count ≠ 60 go to label NEXTCLR TR0 ; Stop counterCLR TF0 ; Clear counter flagSJMP CONTINUE ; Continue the process

All subroutines are similar to previous example.Department of ECE, VKCET Page 12

Page 13: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Hardware control of timers• By setting GATE = 1 bit in TCON

• Set TRx = 1 and timer starts or stop according to the pulse by the switch connected to INTx pins

Department of ECE, VKCET Page 13

Page 14: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

8051 interrupts• To serve several tasks or devices at a time by single microcontroller• Conventional to polling: microcontroller continuously monitor the status of device/task,

when the status condition is met, the microcontroller performs the service. An example is:

WAIT: JNB TF0, WAIT• Interrupt : microcontroller interrupted by device/task causes execution of program

associated with the interrupt called Interrupt Service Routine (ISR)

Advantages of interrupts:• Microcontroller can serve many devices/tasks• Priority to the devices/tasks can assign• Masking (ignoring) interrupt request of devices/tasks is possible• Doesn’t waste the time to check the status of devices/tasks

Interrupt Service Routine:• All interrupts must have an ISR or interrupt handler• There is a fixed location in code memory that holds the ISR• Group of memory location addresses of ISRs is called Interrupt Vector Table (IVT)

Interrupt Vector Table of 8051

Interrupt ROM location (ISR address) Pin Flag clearing

Reset 0000H RESET (9) AutoINT0 (External h/w interrupt 0) 0003H P3.2 (12) IE0 - Auto

TF0(Timer 0 interrupt) 000BH TF0 - Auto

INT1 (External h/w interrupt 1) 0013H P3.3 (13) IE1 - Auto

TF1 (Timer 1 interrupt) 001BH TF1 - Auto

RI and TI (Serial port interrupt) 0023H

RI/TI - Programmer

clears it

Department of ECE, VKCET Page 14

Page 15: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

• Steps in executing an interrupt1. Finishes the instruction executing and save the address of next instruction on the

stack2. Saves the current status of all interrupts internally (not on stack)3. Jumps to fixed location in memory in IVT, that holds the address of ISR4. Starts execution of ISR until it reaches last instruction of subroutine, which must

be RETI5. Returns to place where microcontroller is interrupted, continue the process from

saved address and status

Department of ECE, VKCET Page 15

Page 16: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

8051 interrupt handling registers1. IE (Interrupt Enable) Register:• 8-bit, bit addressable• SFR byte address : A8H

or A8H, A9H, .. to AFHBit orientation:

• EA – Global interrupt enable bit, set to 1 to enable all interrupts• ET2 – Enable Timer 2 interrupt (only in 8052)• ES – Enable Serial port interrupt, set to 1 to enable serial port interrupt• ET1 –Timer 1 overflow interrupt• EX1 – Enable External interrupt 1 (INT1 )• ET0 – Enable Timer 0 overflow interrupt • EX0 – Enable External interrupt 0 (INT0)

2. IP (Interrupt Priority) Register• 8-bit, bit addressable• SFR byte address: B8H

• or B8H, B9H,.. to BFH• Bit orientation:

•• PT2 – Priority Timer 2 (only in 8052)• PS – Priority of Serial port interrupt , set to 1 for highest priority , else default priority• PT1 – Priority of timer 1 interrupt, set to 1 for highest priority , else default priority• PX1 – Priority of external interrupt 1 (INT1), set to 1 for highest priority , else default priority• PT0 – Priority of timer 0 interrupt, set to 1 for highest priority , else default priority• PX0 – Priority of external interrupt 0 (INT0), set to 1 for highest priority , else default priority

Department of ECE, VKCET Page 16

Page 17: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Interrupt priorityHighest to lowest priority

External interrupt 0 INT0Timer 0 interrupt TF0External interrupt 1 INT1Timer 1 interrupt TF1Serial port RI and TI

• If any two or more interrupt priority bit is set to 1, then the priority of all interrupts are default priority

Programming Timer InterruptsSteps:

1. Select timer by TMOD, load THx and TLx2. Enable timer interrupt by IE3. Run timer by TRx bit in TCON4. Wait

ISR (000BH or 001BH) of timer must contain the program for taskNote: 1. Must avoid the memory space allocated to IVT for main program

2. If ISR is more size than allocated space (maximum 8 bytes), use jump instructions to point somewhere else in program memory

Department of ECE, VKCET Page 17

Page 18: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Program 1:Program to generate square wave of 3kHz using timer 1 interrupt (11.0592MHz

Xtal frequency)ORG 0LJMP MAIN

ORG 001BHISR_T1: CPL P0.0

RETI

ORG 0030HMAIN: MOV TMOD,#00100000B ; TIMER 1, MODE 2, AUTO RELOAD

MOV TH1,#66H ; COUNT VALUE FOR 0.1666mSMOV TL1,TH1MOV IE,#10001000B ; EA =1 and ET1 = 1SETB TR1

WAIT: SJMP WAITEND

Program 2:Program to generate a square pulse of 9 kHz at pin P0.0 and toggle pin P2.0 for every 1

second.ORG 0LJMP MAIN

ORG 000BHISR_T0: CPL P0.0

RETIORG 001BH

ISR_T1: LJMP WAIT_1S

ORG 0030HMAIN: MOV TMOD,#00010010B ; TIMER 1 & 2, MODE 2

MOV TH0,#0CCH ; COUNT VALUE FOR 55usMOV TL0,TH0MOV TH1,#4CH ; COUNT VALUE FOR 50msMOV TL1,#00HMOV R0,#00HDepartment of ECE, VKCET Page 18

Page 19: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

MOV IE,#10001010B ; EI = 1, ET1 & ET0 = 1SETB TR0SETB TR1

WAIT: SJMP WAIT

WAIT_1S: CJNE R0,#20,RETURNCPL P2.0MOV R0,#00HMOV TH1,#4CHMOV TL1,#00HRETI

RETURN: INC R0MOV TH1,#4CHMOV TL1,#00HRETI

Programming External Hardware Interrupts• INT0 (P3.2) and INT1 (P3.3)• Activating these interrupts, 8051 execution jumps to the ISRs of IVT location

0003H and 0013H respectively• Enabled by IE register• Two type triggering:

– Level triggered

– Edge triggered

Department of ECE, VKCET Page 19

Page 20: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

SFR to select triggering: TCON

Lower nibble– IEx : set to 1 by microcontroller when external interrupt edge (H to L) is detected,

cleared by microcontroller when the interrupt is processed– ITx : Interrupt type control bit, set to 1 specify falling edge triggering

external interrupt, cleared to 0 specify low level triggered external interrupt

• Minimum duration for low level triggering signal is 4 Machine cycles• Minimum pulse duration to detect edge triggered interrupt is 1 Machine cycle HIGH and

1 Machine cycle LOW

Difference between RET and RETI instructions– Both return to main program– RETI clears ISR flags, indicates the service is over– If RET is used all other lower priority interrupts are blocked

Department of ECE, VKCET Page 20

Page 21: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Program 1:Program for up/down counter and display the count. Switch SW1 on P3.2 for up

count and SW2 on P3.3 for down count. Display is a seven segment display on port 1.

Circuit diagram:

Program:ORG 0LJMP MAIN

ORG 0003HLJMP UP

ORG 0013HLJMP DOWN

MAIN: MOV R1,#00MOV DPTR,#SEG_CODE

CONTINUE: CLR AADD A,R1Department of ECE, VKCET Page 21

Page 22: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

MOVC A,@A+DPTRMOV P1,AMOV IE,#10000101B ; EA = 1, EX1 = 1 & EX0 =1SETB IT0 ; Edge triggering INT0SETB IT1 ; Edge triggering INT1SJMP CONTINUE

UP: CJNE R1,#09,INCRRETI

INCR: INC R1RETI

DOWN: CJNE R1,#0,DECRRETI

DECR: DEC R1RETI

SEG_CODE: DB 11000000B ;’0’ , ASCII for 0DB 11111001B ;’1’, ASCII for 1DB 10100100B ;’2’, ASCII for 2DB 10110000B ;’3’, ASCII for 3DB 10011001B ;’4’, ASCII for 4DB 10010010B ;’5’, ASCII for 5DB 10000010B ;’6’, ASCII for 6DB 11111000B ;’7’, ASCII for 7DB 10000000B ;’8’, ASCII for 8DB 10011000B ;’9’, ASCII for 9END

Department of ECE, VKCET Page 22

Page 23: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Serial data communication• Parallel Communication (Printer)

– Fast, but distance cannot be great. – Expensive

• Serial Communication (Telephone line)– Long distance – Cheaper

• Serial communication uses single or pair of data line instead of 8-bit data line of parallel communication

• For long distance transmission serial data is converted/de-converted into tones by modem

Department of ECE, VKCET Page 23

Page 24: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Asynchronous or synchronous methods of serial data transmission: • Asynchronous transmission transfers one byte at a time• Synchronous transmission transfers a block of data at a time. • They are commonly referred as UART (Universal Asynchronous Receiver-

Transmitter) and USART (Universal Synchronous Asynchronous Receiver-Transmitter)

Types of communication:1. Simplex (only transmit)

2. Duplex

Department of ECE, VKCET Page 24

Page 25: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

8051 has full-duplex, asynchronous serial port, ie two lines and one byte transmission at a time

Asynchronous serial communication data framing:• Character oriented data transmission• Each character is placed between a start and stop bits and is called framing

• Mark is ‘1’ signal to indicate no transfer• Space is ‘0’ signal indicates transfer is over

Framing for ASCII of character ‘A’ASCII for ‘A’ is 41H

• Transmissions begins from start bit ‘0’ followed by D0 (LSB) and ends at stop bit ‘1’ after D7 (MSB) for 8-bit UART

• For 7-bit mode (older system), transmission end at D6 and 2 stop bits are used• Other system have Parity bit with 7 or 8 bit character bits and start/stop bits are also

included for data integrity

Department of ECE, VKCET Page 25

Page 26: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Data Transfer Rate• Bits per second (bps) is also called Baud rate (the number of signals changes per

second, MODEM terminology) • IBM PC/XT 100 to 9600 bps• Pentium PC 56k bps (recent MODEM)• Asynchronous serial data communication, the baud rate is limited to 100,000 bps.

RS232 Standard• To allow compatibility between different data communication equipments from

different manufacturers• Set by EIA (Electronics Industries Association) in 1960• Modified versions are: 1963 - RS232A, 1965- RS232B, 1969 - RS232C• RS232 is serial I/O interfacing standard, but the input and output lines are not

compatible with TTL/CMOS family• RS232 logic:– 0 bit is +3V to +25V– 1 bit is -3V to -25V

MAX232: Line driver Voltage converter Convert TTL logic to RS232 logic and vice versa

Pin out diagram and circuit diagram:

Department of ECE, VKCET Page 26

Page 27: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

RS232 Connectors : DB25 Connector (25 pin)

DB25P – Plug connector (Male)DB25S – Socket connector (Female)

Pin 1 – GND Pin 2 – TxD (transmitted data) Pin 3 – RxD (Received data) Other pins for USART connections

DB9 Connector (9 pin)DB9P (Male) and DB9S (Female)

Pin 2– RxD (Received data) Pin 3 – TxD (Transmitted data) Pin 5 – GND Other pins for USART

Department of ECE, VKCET Page 27

Page 28: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

8051 connection to RS232

8051 serial port programmingSFRs for serial port programming:

• SBUF: To hold the byte of data for Txr or Rxr • SCON: For select serial port mode, serial interrupt flags, receiver enable etc• TH1, TMOD and TCON: To set baud rate using timer 1.

TH1: Hold baud rate information, TMOD: To select timer 1 in auto-reload mode(Mode 2), TCON: To run the timer 1

• IE and IP: If program is in ISR of serial port• PCON: To double the selected baud rate

SBUF: Serial buffer • 8-bit register to hold serial data for txn or rxn • Physically two register with one address 99H, one register only have write

operation (for Txn) and other for read operation (for Rxn)

Department of ECE, VKCET Page 28

Page 29: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

SCON: Serial Control Register• 8-bit, bit addressable• Byte address: 98H, Bit addresses 98H, 99H,….or SCON.0, SCON.1, …• Bit orientation:

• SM0 & SM1: Serial port Mode bits• SM2: Multiprocessing communication enable bit, 1 to enable & 0 to disable • REN: Receiver Enable bit, 1 to enable & 0 to disable• TB8: Transmitted bit 8 (9th bit), 1 or 0 by program• RB8: Received bit 8 (9th bit)• TI: Transmit Interrupt Flag bit, 1 if transmission is over & cleared by sw • RI: Receive Interrupt Flag bit, 1 if receiving is over & cleared by sw

Serial port modes :

Mode 0: Shift register mode• SBUF configures to receive/transmit 8 data bits using RxD pin (P3.0) for both

functions.• TxD serves as clock, where it serve a clock frequency of f/12 to external

circuitsTiming diagram:

Department of ECE, VKCET Page 29

Page 30: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

• Not used for data communication between PC• Only used for special high speed data communication devices

Mode 1: 8-bit UART, variable baud rate mode• SBUF configures to receive 8-bit data, one start bit and a stop bit for full-

duplex UART• The format (framing) of data is:

• After transmission (stop bit) TI flag (SCON.1) set to 1• Receiving bits at the center of bit time (inverse of baud rate), to avoid false

triggering (cause noise)• For receiving, RxD pin bits are shifted into SBUF at programmed baud rate

only if: RI = 0 and SM2 = 0• After discarding start bit, 8 data bit go to SBUF, stop bit saved to RB8

(SCON.2) and RI = 1, indicates receiving data is overMode 1 Baud rate:

• Timer 1 in its auto-reload mode (mode 2) is used to generate baud rate• Timer 1 overflow flag TF1 determine baud frequency • Baud frequency generated by timer 1:

Where SMOD is PCON.7 bit, double baud rate bit; if it is 0,

else

f is Xtal frequency and TH1 is 8-bit value to program different baud rateDepartment of ECE, VKCET Page 30

Page 31: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

• Standard baud rate for data communication between PCs are:1. 110 bps2. 150 bps3. 300 bps4. 600 bps5. 1200 bps6. 2400 bps7. 4800 bps8. 9600 bps9. 19200 bps

Q: With Xtal frequency 11.0592MHz, find the TH1 value for getting baud frequencies a) 1200 bps b) 9600 bps

Solution:For 2400 bps:

Similarly for 9600 bps:

Mode 2: 9-bit UART, fixed baud rate mode• Similar to mode 1, but 11 bits are transmitted: (1 start bit, 9 data bit and 1 stop bit). 9 th

data bit is from TB8 bit of SCON register• Baud rate can be programmed as:

• Data format:

Department of ECE, VKCET Page 31

Page 32: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Mode 3: 9-bit UART, variable baud rate mode • Similar to mode 2, but baud frequency is similar to mode 1 and is:

Note:Commonly used mode is mode 1: 8-bit UART variable baud rate, because of its simplicity and versatility with other data communication devices

Program 1:Send a string of message to 8051 TxD pin (P3.1)

ORG 0LJMP MAIN

ORG 30HMAIN: MOV TMOD,#00100000B ; Timer 1, mode2

MOV TH1,#0FDH ; Baud rate 9600bpsMOV TL1,TH1SETB TR1 ; Start timerMOV SCON,#01000000B ;Serial mode 1MOV DPTR,#MESSAGE ;Pointer for message string

NEXT: CLR AMOVC A,@A+DPTR ; Access code memory for messageCJNE A,#00,SEND ;If null character, stop txn.

STOP: SJMP STOP

SEND: MOV SBUF,A ; SBUF = A, data to Txr WAIT: JNB TI,WAIT ; Wait for Txn Flag = 1

CLR TI ; Clear Txn Flag for next txn INC DPTR ;For next character SJMP NEXT

MESSAGE: DB “Hello world”,0END

Department of ECE, VKCET Page 32

Page 33: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Program 2:Receive a string of message (end of message is Carriage Return - ASCII is 0DH) from RxD (P3.0) and send it to TxD (P3.1)

ORG 0LJMP MAIN

ORG 30HMAIN: MOV TMOD,#00100000B

MOV TH1,#0FDHMOV TL1,TH1SETB TR1MOV SCON,#01010000B ; SM 1 & REN = 1

CONTINUE: MOV R0,#40H ; RAM address to store messageNEXT_RXR: ACALL RECEIVE

MOV A,R7MOV @R0,AINC R0CJNE A,#0DH,NEXT_RXR ;0DH is ASCII for CR MOV R0,#40H

NEXT_TXR: MOV A,@R0ACALL SENDCJNE A,#0DH,SEND_CHARSJMP CONTINUE

SEND_CHAR: INC R0SJMP NEXT_TXR

RECEIVE: JNB RI,RECEIVECLR RIMOV R7,SBUFRET

SEND: MOV SBUF,AWAIT: JNB TI,WAIT

CLR TIRETEND Department of ECE, VKCET Page 33

Page 34: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

ADC interfacing• Analog to digital converters are widely used for data acquisition• Physical signals like temperature, velocity, pressure, light etc. are converted into

electrical signals using transducers and these signals are processed by digital system by converting to digital data using ADC

• ADC with n-bit resolution has 8, 10, 12, 16 or 24 bit digital data output• Resolution determines step-size of the signal to convert• Conversion time of ADC is defined as the time taken to convert one instant

analog input to its corresponding digital data• Different type ADCs; parallel and serial – where parallel, data output is in parallel

form and in serial type data in serial form• ADC0800 series is common type ADC from National semiconductors, 8-bit

parallel type ADC with 100µs conversion timeADC0804 Chip

Pin out diagram:

Department of ECE, VKCET Page 34

Page 35: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Functions of pins:Pins FunctionsCS Active low input, if low chip is active else chip is offRD Active low input also called output enable (OE), if it is low converted

digital output is available in data bus D7 to D0WR Active low input, if it is high to low ADC initialize for conversion and

if it is low to high ADC starts conversion. So this pin is also called start of conversion (SOC)

INTR Active low output, this will be high after ADC initialize and becomes low after conversion time of ADC. This pin can be use to interrupt microcontroller to read digital data from ADC. This pin is also called end of conversion (EOC)

CLKin Input pin to apply external clock source. To use internal clock source, this and CLK R pins are used to connect frequency determining elements R an C

CLK R To use internal clock source R is connected across this and CLK in pin, the clock frequency is f = 1/ (1.1 RC). If external clock is using this pin is at floating

Vin(+) and Vin(-)

Differential analog inputs. To connect single ended input, Vin(-) = 0V

AGND Analog groundVcc and DGND

Power supply and digital ground

Vref/2 Reference voltage, it determines the range of input analog voltage and also stepsize

D7 to D0 Digital data output and output digit value is Dout = Vin / step size

Department of ECE, VKCET Page 35

Page 36: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Relation between Vref and step size:Vref/2 (V) Vin (V) Step size (mV)

No connection 0 to 5V 5/256 = 19.532 0 to 4V 4/255 = 15.62

1.5 0 to 3V 3/256 = 11.711.28 0 to 2.56V 2.56/256 = 10

ADC0804 timing diagram:

Department of ECE, VKCET Page 36

Page 37: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Timing and electrical characteristics:

ADC0804 interfacing• Interfacing circuit

Department of ECE, VKCET Page 37

Page 38: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Programs:Prrogram to convert analog signal to digital data and display the data on LEDs connected

to port 0Solution:Circuit diagram:

(Xtal and RST connections are not shown)

Algorithm:1. Start2. Set Port 1 as input3. Set EOC (INTR) pin as 14. Set SOC (WR) pin as 15. Set OE (RD) pin as 16. Clear SOC (WR) pin to 07. Wait 150ns 8. Set SOC (WR) pin as 19. If EOC (INTR) pin is high, wait in this step, else go to next step10. Clear OE (RD) signal11. Read digital data from Port 112. Write digital data to Port 013. Go to step 6 for repeat the process

(Assume crystal frequency to 8051 is 12 MHz) Department of ECE, VKCET Page 38

Page 39: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

OE BIT P2.7SOC BIT P2.6EOC BIT P2.5IN_DATA EQU P1OUT_DATA EQU P0

ORG 0LJMP MAIN

ORG 30HMAIN: MOV P1, #FFH

SETB EOCSETB SOCSETB OE

CONTINUE: CLR SOCNOPNOPSETB SOC

WAIT: JB EOC, WAITCLR OEMOV A, IN_DATAMOV OUT_DATA, ASJMP CONTINUE

Department of ECE, VKCET Page 39

Page 40: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

DAC interfacing• Counter part of ADC• Digital to analog converter converts digital data to analog voltage/current signal• Basically two types: binary weighted and R/2R ladder• Most familiar is R/2R ladder type DAC0808

DAC0808 chipSome features:

• 8-bit monolithic • Full scale output current settling time of 150 ns • No reference current (IREF) trimming is required for most applications since the

full scale output current is typically ±1 LSB of 255 IREF/256. • Interface directly with popular TTL, DTL or CMOS logic levels• Low power consumption: 33 mW @ ±5V

Pin out diagram:

Functions of pins:Pins Functions

Vcc & GND Power supply pinsVEE -ve power supply (-12V)Io- Analog current output

A1(MSB) to A8(LSB)

Digital input data lines

Vref(+) and Vref(-)

Reference voltage to provide reference current Iref

Compensation Compensation capacitor for –ve power supply

Department of ECE, VKCET Page 40

Page 41: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Output current

Where R14 is the resistance connected to pin 14

DAC0808 interfacing circuit:• The output of DAC0808 is current and have ripples • Output require I-V converter followed by LPF

Circuit diagram:

• Vout = Io Rf

• For LPF RC value can be determined by either the maximum frequency of the required analog output or by the data transfer rate of 8051

Department of ECE, VKCET Page 41

Page 42: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Square wave and rectangular wave generation:• By sending a data corresponding to peak amplitude and zero continuously• Frequency of wave depends on delay program

Program:ORG 0

MAIN: MOV P1, #00ACALL DELAYMOV P1, #FFHACALL DELAYSJMP MAIN

DELAY: MOV R0, #2CHWAIT: DJNZ R0, WAIT

RETEND

The peak amplitude of the signal is ≈ Io Rf * 255/256 = 9.96VTon = Toff = 100µs, then frequency of the square wave is 5 kHz

Using different delay programs rectangular wave can be generated.

Saw tooth and triangular wave generation: By sending data from 00H to FFH continuously with one step size. The frequency and peak amplitude of the signal are maximum value if there is no

delay introduced between each step Frequency can be changed by including required delay between each step. Peak voltage of the wave is reduced by changing the maximum data. To generate triangular wave send data from 00H to FFH for rising and FFH to

00H for falling with one step size. Similar to other waves, the frequency and amplitude can change.

Department of ECE, VKCET Page 42

Page 43: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Programs:a) Saw tooth wave

ORG 0MAIN : CLR A

REPEAT: MOV P1, A INC A SJMP REPEAT

ENDb) Triangular wave:

ORG 0MAIN: CLR AINCREMENT : MOV P1, A

INC A CJNE A, #FF, INCREMENT

DECREMENT: MOV P1, ADEC ACJNE A, #00, DECREMENTSJMP INCREMENTEND

Applications:Temperature measurement system:

The basic block diagram of temperature measurement system is:

• Sensor are thermostats, thermisters or any other temperature sensors• Usually LM34/35 IC temperature sensors are used; whose output voltage is directly

proportional to the temperature as given below:For LM35 temperature range -55 to 150oC, 10mV/oC sensitivity

• Signal conditioner is either amplifier, I-V or V-I converter etc. to provide suitable input signal to ADC

• ADC converts analog signal corresponding to temperature into digital data• Microcontroller controls ADC and acquire digital data corresponding to temperature and

process it to get a suitable signal to displayDepartment of ECE, VKCET Page 43

Page 44: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

• LED (either LEDs or 7 segment display) or LCD are used to display the measure quantity of temperature

Circuit diagram:

• Signal conditioning is not used• Program to read data corresponding to temp and display its BCD data. (Assume that

calibrated output is available at ADC output: ie for 0oC data is 0000 0000, for 10oC data is 0000 1010, for 50oC data is 0011 0010, and so on…..)

OE BIT P2.0SOC BIT P2.1EOC BIT P2.2

ORG 0MAIN: MOV P1, #FFH

SETB EOCCONTINUE: ACALL ADC_START

ACALL ADC_READMOV R0, AACALL HEX_BCD ; Hex to BCD conversion MOV P3, A ; DisplayCONTINUEDepartment of ECE, VKCET Page 44

Page 45: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

ADC_START: SETB SOCSETB OECLR SOCSETB SOCRET

ADC_READ: JB EOC, ADC_READCLR OEMOV A, P1RET

HEX_BCD: MOV B, #0AHDIV ABMOV R7, B ; Lower digitMOV B, #0AHDIV ABMOV A, B ; Upper byteSWAP AORL A, R7 ; Packing BCDRET

Department of ECE, VKCET Page 45

Page 46: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Stepper motor interfacing• Stepper motor translates electrical pulses into mechanical motion• Possible to precise control speed and position without feedback sensors• Applications:

Computer peripherals (Hard disk, CD, FD, Printer, Plotter etc.) Business machines (Card reader, Type writer, Copy machine, etc.) Control system Machine tools (Milling machines, drilling machines, etc)

Constructional details:• Consists rotor (Permanent magnet) surrounded by stator

Different views:

Department of ECE, VKCET Page 46

Page 47: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

• Four stator motor also called four-phase or uni-polar stepper motor• Total 6 leads: 4 leads for stator windings and 2 for center tapped common

windings

• As the sequence of pulse is applied to each stator winding, the rotor will switch to next step due to the flux linkage across the stator and rotor

• Rotor of conventional motors runs freely, but stepper motor’s rotor moves in a fixed repeatable increment, allows a precise position

• The most common stepper motors have four stator windings that are paired with a center-tapped common. This type of stepper motor is commonly referred to as a four-phase stepper motor

• The center tap allows a change of current direction in each of two coils when a winding is grounded, thereby resulting in a polarity change of the stator.

Department of ECE, VKCET Page 47

Page 48: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Direction of motion and position of rotor:• Full step 4 step motion (Wave drive)

• Full step 4-step motion (Normal or 2-phase)

• Half step 8-step motion (mixed)

• Step sequences are different with different degree of precision

Department of ECE, VKCET Page 48

Page 49: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Step angle• Depends on internal construction; number of teeth on the stator and the

rotor.

• Consider a motor; Stator with 8 teeth and rotor with 6 teeth, have 15o step angle• Step angle is minimum degree of rotation associated with a single step• Different motor have different step angle

Standard angles and steps per revolution (or 360 degree) are:0.72 - 5001.8 - 2002.0 - 1805.0 - 727.5 - 4815 - 24

– Steps per second and rpm relationship is:

– After completing every four steps, the rotor moves only one tooth pitch– The smaller the step-angle, the more teeth the motor passes– Eg. In a stepper motor with 200 steps per revolution, its rotor has 50 teeth since

4 x 50 = 200 steps are needed– To allow for finer resolutions, all stepper motors allow what is called an 8-step

switching sequence. It’s also called half-stepping, since each step is half of the normal step angle Department of ECE, VKCET Page 49

Page 50: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Full step 4-step sequence (clock wise)

Step Winding A

Winding B

Winding C

Winding D

1 1 0 0 12 0 1 0 13 0 1 1 04 1 0 1 0

Full step 4-step wave drive sequence (clock wise)

Step Winding A

Winding B

Winding C

Winding D

1 1 0 0 02 0 0 0 13 0 1 0 04 0 0 1 0

Department of ECE, VKCET Page 50

Page 51: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Half step 8-step sequence (clock wise)– Combination of normal and wave step sequence– Have finer resolution

Step Winding A

Winding B

Winding C

Winding D

1 1 0 0 02 1 0 0 13 0 0 0 14 0 1 0 15 0 1 0 06 0 1 1 07 0 0 1 08 1 0 1 0

Motor speed– Measure in steps per second; function of switching rate– Determined by delay introduced between each step– Eg. Let step angle of motor is 7.5 degree. If required RPM is 20,

then steps per second = 20 x 48 /60 = 16

– Therefore for one step 1/16 = 62.5ms is required– Then pulse duration of a step sequence signal is 62.5msDepartment of ECE, VKCET Page 51

Page 52: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Holding torque– Motor shaft at zero rpm, amount of torque from an external source to break away the

shaft from the position and it is function of applied power

Types of stepper motor– Universal (eight leads)– Unipolar (6 leads)– Bipolar (4 leads)

Motor drivers – To avoid back emf from motor winding– To provide higher current to drive motor– Either by Darlington pair transistors or driver ICs ULN2003, ULN2803, L298 etc.

8051 and stepper motor interfacing circuit and programming

Xtal and RST connections are not shown

Department of ECE, VKCET Page 52

Page 53: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Program to rotate the stepper motor continuously in clock-wise direction (full step 4-step wave drive sequence)

Solution:Step sequence as per the connection on circuit diagram

Step Winding A (P2.3)

Winding B (P2.2)

Winding C (P2.1)

Winding D (P2.0)

1 0 0 0 12 0 0 1 03 0 1 0 04 1 0 0 0

Program: ORG 0

MAIN: MOV TMOD,#01HMOV DPTR,#FS_WAVEMOV R0,#04H

REPEAT: CLR AMOVC A,@A+DPTRMOV P2,AACALL DELAY_1SINC DPTRDJNZ R0,REPEATSJMP MAIN

DELAY_1S: MOV R7,#14H ;50ms x 20 = 1sec delayWAIT_1S: LCALL DELAY

DJNZ R7,WAIT_1SRET

DELAY: MOV TH0,#4CH ;Higher byte count value for 50msMOV TL0,#01H ;Lower byte count value for 50msSETB TR0

WAIT: JNB TF0,WAITCLR TR0CLR TF0RET

FS_WAVE: DB 01H,02H,04H,08H ;Step sequenceEND Department of ECE, VKCET Page 53

Page 54: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Program to rotate stepper motor in anti-clock wise direction when P1.0 is 0, else rotate in clock wise direction (use half step 8-step sequence)

Solution:Sequence as per the connection in circuit diagram:

Step Winding A

Winding B

Winding C

Winding D

1 1 0 0 12 0 0 0 13 0 0 1 14 0 0 1 05 0 1 1 06 0 1 0 07 1 1 0 08 1 0 0 0

Program:ORG 0

MAIN: SETB P1.0 ;P1.0 as inputMOV TMOD,#01 ;Timer 0 for delay

CONTINUE: MOV C,P1.0 ;Status of P1.0 to CYJC C_WISE ;If P1.0 is 1, go to label C_WISE for CW

;rotationMOV DPTR,#ACW ;Pointer for ACW step sequenceSJMP STRT

C_WISE: MOV DPTR,#CW ;Pointer for CW step sequenceSTRT: MOV R0,#08H ;Counter for half-step sequence

REPEAT: CLR A

MOVC A,@A+DPTRMOV P2,AACALL DELAY_1SJNC DECR ;If CY =0 go to label DECRINC DPTR

NEXT: DJNZ R0,REPEATSJMP CONTINUE

DECR: DEC DPLSJMP NEXT

Department of ECE, VKCET Page 54

Page 55: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

DELAY_1S: MOV R7,#14HWAIT_1S: LCALL DELAY

DJNZ R7,WAIT_1SRET

DELAY: MOV TH0,#4CHMOV TL0,#01HSETB TR0

WAIT: JNB TF0,WAITCLR TR0CLR TF0RET

;Step sequenceCW: DB 09H, 01H, 03H, 02H, 06H, 04H, 0CH ACW: DB 08H

END

Program to rotate stepper motor with 1.8o step angle, at a speed of 6 RPM in 360o clockwise for 2 times and 11 RPM in 360o anti-clock wise direction for 4 times continuously (Xtal frequency of 8051 is 11.0592MHz )

Solution:Step sequence for normal drive as per the connection shown in the circuit is:

For clockwise rotation:

Step Winding A (P2.3)

Winding B (P2.2)

Winding C (P2.1)

Winding D (P2.0)

1 1 0 0 12 0 0 1 13 0 1 1 04 1 1 0 0 For RPM = 6, Step angle = 1.8o

Steps/sec = 6 x 200/60 = 20For one step 1/20 = 50ms Design 50ms delay program

After full step pulses 1.8 x 4 = 7.2 degree rotation takes place, then for 360 degree, repeat the process for 360/7.2 = 50 times

• Continue the above process for two timesDepartment of ECE, VKCET Page 55

Page 56: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Anti-clock wise rotationFor anti-clockwise rotation (Half step):

Step Winding A

Winding B

Winding C

Winding D

1 1 1 0 02 0 1 0 03 0 1 1 04 0 0 1 05 0 0 1 16 0 0 0 17 1 0 0 18 1 0 0 0

• For RPM = 11, Step angle = 1.8o Steps/sec = 11 x 200/60 = 36.66For one step 1/36.66 = 27.27ms (use 25ms) Design 25ms delay program

• After half step pulses 1.8 x 8 = 14.4 degree rotation takes place and for 360 degree repeat the process for 360/14.4 = 25 times

• Continue the above process for 4 times Program:

ORG 0MAIN: MOV TMOD,#01

MOV R2,#02H ;counter for 2 times cw rotationCONTINUE: MOV R1,#32H ;counter for 50 times to rotate 360o REPEAT: MOV R0,#04H

MOV DPTR,#FS_CWNEXT: CLR A

MOVC A,@A+DPTRMOV P2,AACALL DELAY ;25ms delayACALL DELAY ;25ms delayINC DPTRDJNZ R0,NEXTDJNZ R1,REPEATDJNZ R2,CONTINUE MOV R2,#04 ;Count for 4 times acw rotation

CONTINUE1: MOV R1,#19H ;count for 25 times to rotate 360o

Department of ECE, VKCET Page 56

Page 57: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

REPEAT1: MOV R0,#08H ;half step sequence countMOV DPTR,#FS_ACW

NEXT1: CLR AMOVC A,@A+DPTRMOV P2,AACALL DELAY ;25msINC DPTRDJNZ R0,NEXT1DJNZ R1,REPEAT1DJNZ R2,CONTINUE1SJMP MAIN

DELAY: MOV TH0,#0A6H ;Count value for 25msMOV TL0,#00HSETB TR0

WAIT: JNB TF0,WAITCLR TR0CLR TF0RET

;SequencesFS_CW: DB 09H,03H,06H,0CHFS_ACW: DB 0CH,04H,06H,02H,03H,01H,09H,08H

END

Department of ECE, VKCET Page 57

Page 58: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

LCD InterfacingLCD is wide spreading display conventional to LEDs, due to:

a) Low costb) Ability to display numbers, characters and graphicsc) Display refreshing task is not requiredd) Easy to program for characters and graphics

The pins and its functions of 16 x 2 character LCD module:

Timing diagram:

Department of ECE, VKCET Page 58

Page 59: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Timing characteristics:

Note: DDRAM – Display Data RAM

WhereI/D = 1, increment DDRAM address, cursor moves to rightI/D = 0, decrement DDRAM address, cursor moves to leftSH = 1, shift entire display according to I/DDepartment of ECE, VKCET Page 59

Page 60: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

SH = 1, no shift of entire displayCGRAM – Character Generator RAMD = 1, entire display turn onD = 0, display turn off, but display data remains in DDRAMC = 1, cursor turn onC = 0, cursor disappear, but I/D preserves its dataB = 1, cursor blink onB = 0, cursor blink off

AC – Address Counter

DL = 1, 8-bit bus modeDL = 0, 4 bit bus modeN = 1, 2 line display modeN = 0, 1 line display modeF = 1, 5 x 10 dots fontF = 0, 5 x 7 dots font

Address for DDRAM:AC6 to AC0 are:

The for position 1 in line 1 the command byte is 1000 0000 = 80H, for position 2 : 1000 0001 = 81H ….Department of ECE, VKCET Page 60

Page 61: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Program 1Interface 16 x 2 LCD and display a message (maximum length of the message should be

less than 32) Solution:

Circuit diagram

Xtal, RST and Power supply connection are not shownProgram:

Algorithm:Main programSteps:

1. Start2. Write command byte to LCD for function setting. Command byte: 0011 1000 = 38H3. Wait minimum 40µs4. Write command byte to LCD for function setting. Command byte: 0000 0001 = 01H5. Wait minimum 1.64ms6. Write command byte to LCD for display on and cursor blinking. Command byte:

0000 1111 = 0FH7. Wait minimum 40µs

Department of ECE, VKCET Page 61

Page 62: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

8. Write command byte to LCD for entry mode: left entry (increment cursor to right). Command byte: 0000 0110 = 06H

9. Write command byte to LCD for DDRAM address. Command byte: 1000 0000 = 80H

10. Wait minimum 40 µs11. Point starting address of LUT by DPTR, Counter R0 = 0 for getting the length of

message12. A ← [DPTR], ASCII of character for message to A13. If A = 0 (ASCII of NULL character) go to step 20, else next step14. If R0 =16 go to next step, else go to step 1615. Write command byte to LCD for DDRAM address. Command byte: 1100 0000 =

C0H16. Write data byte (ASCII) to LCD17. Wait minimum 40µs18. DPTR = DPTR +1, R0=R0+119. Go to step 1220. Stop

LCD command writeSteps:

1. Clear E2. Move command byte to DB0-DB73. Clear RS and RW4. Set E to 15. Wait 40 µs6. Clear E7. Set RS and RW8. Return to main program

Department of ECE, VKCET Page 62

Page 63: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

LCD data writeSteps:

1. Move data byte to DB0-DB72. Set RS to 1 and clear RW3. Set E to 14. Wait 40 µs5. Clear E6. Clear RS and set RW to 17. Return to main program

Program:RS BIT P2.0RW BIT P2.1E BIT P2.2LCD_BUS EQU P1

ORG 0MAIN: MOV TMOD,#01H

MOV A,#38HLCALL CMD_WRITELCALL DELAY_40uMOV A,#01HLCALL CMD_WRITELCALL DELAY_2mMOV A,#0FHLCALL CMD_WRITELCALL DELAY_40uMOV A,#06HLCALL CMD_WRITELCALL DELAY_40uMOV A,#80HLCALL CMD_WRITELCALL DELAY_40uMOV R0,#00HMOV DPTR,#MESSAGE

NEXT: CLR AMOVC A,@A+DPTRCJNE A,#0, DISPLAYDepartment of ECE, VKCET Page 63

Page 64: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

STOP: SJMP STOPDISPLAY: CJNE R0,#10H,LINE_1LINE_2: MOV R1,A

MOV A,#0C0HLCALL CMD_WRITELCALL DELAY_40uMOV A,R1

LINE_1: LCALL DATA_WRITELCALL DELAY_40uINC R0INC DPTRSJMP NEXT

CMD_WRITE: CLR EMOV LCD_BUS,ACLR RWCLR RSSETB ELCALL DELAY_40uCLR ESETB RWSETB RSRET

DATA_WRITE: MOV LCD_BUS,ASETB RSCLR RWSETB ELCALL DELAY_40uCLR ECLR RSSETB RWRET

DELAY_40u: MOV TH0,#0FFHMOV TL0,#0DBHSETB TR0Department of ECE, VKCET Page 64

Page 65: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

WAIT_40u: JNB TF0,WAIT_40uCLR TR0CLR TF0RET

Department of ECE, VKCET Page 65

Page 66: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

DELAY_2m: MOV TH0,#0F8HMOV TL0,#0CCHSETB TR0

WAIT_2m: JNB TF0,WAIT_2mCLR TR0CLR TF0RET

MESSAGE: DB"ECE Department, VKCET",0END

Keyboard Interfacing• Keyboard is widely used input device along with output devices like LCD, seven segment

displays etc• To interface keyboard, understanding keyboard mechanism, key pressing and detecting is

essential Interfacing keyboard to 8051

• Interfacing program must guard against two factors:a. Human factors:

1. More than one key pressed2. Key pressed and held3. Rapid key press and release

b. Key factorsBouncing of key contacts

Key configurations• Commercially available key configurations are:

1. Lead per keyboard

16 input lines are required to read the keys

Department of ECE, VKCET Page 66

Page 67: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

2. Matrix keyboard

4 input and 4 output lines are required to read the keys

3. Coded key board

Expensive, but better to read multiple key press

Department of ECE, VKCET Page 67

Page 68: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Scanning and identify the key– Consider the connection of 4x4 matrix keyboard with 8051

• Scanning and identifying steps– Ground all rows , P1.3 – P1.0 =0000– Read all columns, if data read P2.3 – P2.0 = 1111, no key is pressed– Continue above process until a key is pressed– If P2.3 – P2.0 = 1101, one of the key in column 1 is pressed– To identify the key in the column, ground row 0 only, P1.3 – P1.0 = 1110– Read columns, if P2.3 – P2.0 = 1111 , no key in the row 0 is pressed– Continue the above process until pressed is detected– If key 5 is pressed, then read data during scanning is P2.3 – P2.0 = 1101– Identifying step; grounding P1.3 – P1.0 = 1101, read data becomes P2.3 – P2.0 =

1101 •

Department of ECE, VKCET Page 68

Page 69: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

ProgramsProgram to read a key from 4 x 4 matrix keyboard and display its value to seven segment display

ORG 0LJMP MAINORG 30H

MAIN: MOV TMOD,#00000001BMOV P2,#0FFH

K1: MOV P1,#0MOV A,P2ANL A,#00001111BCJNE A,#00001111B,K1

K2: ACALL DELAYMOV A,P2ANL A,#00001111BCJNE A,#00001111B,OVERSJMP K2

OVER: ACALL DELAYMOV A,P2ANL A,#00001111BCJNE A,#00001111B,OVER1SJMP K2

OVER1: MOV P1,#00001110BMOV A,P2ANL A,#00001111BCJNE A,#00001111B,ROW_0 MOV P1,#00001101BMOV A,P2ANL A,#00001111BCJNE A,#00001111B,ROW_1MOV P1,#00001011BMOV A,P2ANL A,#00001111BCJNE A,#00001111B,ROW_2MOV P1,#00000111BDepartment of ECE, VKCET Page 69

Page 70: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

MOV A,P2ANL A,#00001111BCJNE A,#00001111B,ROW_3SJMP K2 MOV P1,#00001101BMOV A,P2ANL A,#00001111BCJNE A,#00001111B,ROW_1MOV P1,#00001011BMOV A,P2ANL A,#00001111BCJNE A,#00001111B,ROW_2MOV P1,#00000111BMOV A,P2ANL A,#00001111BCJNE A,#00001111B,ROW_3SJMP K2

KEYCODE_0: DB 11000000B,11111001B,10100100B,10110000BKEYCODE_1: DB 10011001B,10010010B,10000010B,11111000BKEYCODE_2: DB 10000000B,10011000B,10001000B,10000011BKEYCODE_3: DB 11000110B,10100001B,10000110B,10001110BDELAY: MOV TH0,#4CH

MOV TL0,#01HSETB TR0

WAIT: JNB TF0,WAITCLR TR0CLR TF0RET

END

Department of ECE, VKCET Page 70

Page 71: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

PIC Microcontrollers

Different 8 bit microcontrollers:• 1970s: Motorola’s 6800• 1980s: Intel’s 8051• 1990s: Microchip’s PIC

Cheap, small and practical microcontroller which was both easy to use and program

PIC – Peripheral Interface ControllerWhy PIC popular?

• Low cost• Wide availability• Large user base• Extensive collection of application notes• Availability of low cost or free development tools• Serial programming capability.

.Different PIC core architecture 1. Baseline Core Devices (ex:PIC12C50x, PIC16C5x)

• 12 bit wide code memory, • Tiny two level deep call stack.• 33 instructions• PIC10, PIC12 & PIC16 devices• 6 pin to 40 pin packages.

2. Mid-Range Core Devices (ex:PIC12C50x, PIC16C5x)• 14 bit wide code memory• Improved 8 level deep call stack• 35 instructions• Increased opcode width allows• Addressing of more memory• PIC12 and PIC16 devices.

3. PIC17 High End Core Devices (Ex:PIC17C4x,PIC17C7xx)• Never became popular and superseded by the PIC18 architecture.• 16 bit wide opcodes (allowing many new instructions) : 58 instructions• 16 level deep call stack.• Packages of 40 to 68 pins. • A memory mapped accumulator• Read access to code memory (table reads) • Direct register to register moves• An external program memory interface to expand the code space• An 8bit x 8bit hardware multiplierDepartment of ECE, VKCET Page 71

Page 72: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

• Auto-increment/decrement addressing.4. PIC18 High End Core Devices (ex:PIC18Cxxx)

• New high end PIC architecture• It inherits most of the features and instructions of the 17 series,• 77 instructions, much deeper call stack (31 levels deep) • The call stack may be read and written• Offset addressing mode• A new indexed addressing mode in some devices

5. PIC24 and dsPIC 16 bit Microcontrollers• Architectures differ significantly from prior models.• dsPICs are Microchip's newest family (started in 2004)• Digital signal processing capabilities. • Microchip's first inherent 16-bit (data) microcontrollers. • Hardware MAC (multiply-accumulate)• Barrel shifting• Bit reversal• (16x16)-bit multiplication• Other digital signal processing operations. • Can be efficiently programmed in C

.

.PIC16F87X Microcontrollers • Mid range core• 28/40-Pin 8-Bit CMOS FLASH Microcontrollers• PIC16F873, PIC16F874• (28 pin ICs)• PIC16F876 and PIC16F877 devices• (40 pin ICs)

Microcontroller Core Features:• High performance RISC CPU• Only 35 single word instructions • All single cycle instructions except for program branches which are two cycle• Operating speed: DC - 20 MHz clock input

DC - 200 ns instruction cycle• Up to 8K x 14 words of FLASH Program Memory,

Up to 368 x 8 bytes of Data Memory (RAM)Up to 256 x 8 bytes of EEPROM Data Memory

• Pin out compatible to the PIC16C73B/74B/76/77

Department of ECE, VKCET Page 72

Page 73: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

• Interrupt capability (up to 14 sources)• Eight level deep hardware stack• Direct, indirect and relative addressing modes• Power-on Reset (POR)• Power-up Timer (PWRT) and• Oscillator Start-up Timer (OST) • Watchdog Timer (WDT) with its own on-chip RC oscillator for reliable operation• Programmable code protection• Power saving SLEEP mode• Selectable oscillator options• Low power, high speed CMOS FLASH/EEPROM technology• Fully static design• In-Circuit Serial Programming (ICSP) via two pins• Single 5V In-Circuit Serial Programming capability• In-Circuit Debugging via two pins• Processor read/write access to program memory• Wide operating voltage range: 2.0V to 5.5V• High Sink/Source Current: 25 mA• Commercial, Industrial and Extended temperature ranges• Low-power consumption:

< 0.6 mA typical @ 3V, 4 MHz20 µA typical @ 3V, 32 kHz< 1 µA typical standby current

.Peripheral Features:• Timer0: 8-bit timer/counter with 8-bit prescaler• Timer1: 16-bit timer/counter with prescaler, can be incremented during SLEEP via

external crystal/clock• Timer2: 8-bit timer/counter with 8-bit period register, prescaler and postscaler • 5 IO ports• Two Capture, Compare, PWM modules

• Capture is 16-bit, max. resolution is 12.5 ns• Compare is 16-bit, max. resolution is 200 ns• PWM max. resolution is 10-bit

• 10-bit multi-channel Analog-to-Digital converter• Synchronous Serial Port (SSP) with SPI (Mastermode) and I2C (Master/Slave)• Universal Synchronous Asynchronous Receiver Transmitter (USART/SCI) with 9-bit

address detection

Department of ECE, VKCET Page 73

Page 74: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

• Parallel Slave Port (PSP) 8-bits wide, with external RD, WR and CS controls (40/44-pin only)

• Brown-out detection circuitry for Brown-out Reset (BOR).

Department of ECE, VKCET Page 74

Page 75: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Pin out diagram of PIC16F877

.Pin details:

Department of ECE, VKCET Page 75

Page 76: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Department of ECE, VKCET Page 76

Page 77: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Department of ECE, VKCET Page 77

Page 78: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

.Architecture of PIC16F877

.

Department of ECE, VKCET Page 78

Page 79: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

CPUALU• 8 bit• Perform operation with temporary working register (W) and any other register fileW register• 8 bit register which hold one operand and result after an ALU operation

Status register

• 8 bit• Contains the arithmetic status of ALU • To select register bankFile Selection Register (FSR)• Data pointer, used for indirect addressing in the whole register file• IO ports Memory organization• Three memory blocks:

1. Program memory (Flash)2. Data memory (RAM) (Separate bus for both memory)3. Data EEPROM

Program memory mapping• 8k x 14 word ROM (Flash or EEPROM)

Department of ECE, VKCET Page 79

Page 80: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Program Counter (PC) .Keeps track of the program execution by holding the address of the current instruction.PCL and PCLATH

SFRs for accessing 13 bit PC

PCL (8 bit) is readable and writablePCH (5 bit) not readable, but indirectly writable by PCLATH least 5 bits

Stack memory• The stack space is not part of either program or data space and the stack pointer (SP) is

not readable or writable.• Stack is a special block of RAM memory • The PC is PUSHed onto the stack when a CALL instruction is executed, or an interrupt

causes a branch.

Department of ECE, VKCET Page 80

Page 81: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

• The stack is POPed in the event of a RETURN, RETLW or a RETFIE instruction execution.

• The stack operates as a circular buffer. This means that after the stack has been PUSHed eight times, the ninth push overwrites the value that was stored from the first push. The tenth push overwrites the second push (and so on).

Reset vector• Each time the main program execution starts at address 0000 - Reset Vector. Interrupt vector• The address 0004 is “reserved” for the “interrupt service routine” (ISR).

Department of ECE, VKCET Page 81

Page 82: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Data memory mapping• 368 byte RAM is partitioned to 4 register banks and contains GPRs and SFRs

Bank 2 GPRs and SFRs

Department of ECE, VKCET Page 82

Page 83: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Bank 3 GPRs and SFRs

Summary of Data memory

• By RP0 and RP1 bits in STATUS register any one bank can be selected• Using IRP bit in STATUS register direct or indirect

Department of ECE, VKCET Page 83

Page 84: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

Data EEPROM (256 bytes)– Similar to Program flash, but r/w operation is byte , where in program memory it

is word r/w operation– Write operation can be performed during normal power source Vdd – SFRs for accessing Data EEPROM

EEADR :Hold data EEPROM addressEEDATA : Hold the data from/to the data EEPROMEEDATA : EEDATH Hold 14 bit data from flash memoryEEADRH:EEADR hold 13 bit flash memory addressEECON1 & EECON2 : Control registers for configure

IO Ports1. Port A and TRISA Registers

– PORTA is a 6-bit wide, bi-directional port– 5 analog inputs and timer 0 clock input are multiplexed with this pins – The corresponding data direction register is TRISA.– Setting a TRISA bit (= 1) will make the corresponding PORTA pin an input – Clearing a TRISA bit (= 0) will make the corresponding PORTA pin an output

2. Port B and TRISB registers– PORTB is an 8-bit wide, bi-directional port.– The corresponding data direction register is TRISB. – Setting a TRISB bit (= 1) will make the corresponding PORTB pin an input – Clearing a TRISB bit (= 0) will make the corresponding PORTB pin an output Department of ECE, VKCET Page 84

Page 85: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

– Three pins of PORTB are multiplexed with the Low– Voltage Programming function: PGM, PGC and PGD– Each of the PORTB pins has a weak internal pull-up and can be turn on or off

3. PORTC and the TRISC Register– PORTC is an 8-bit wide, bi-directional port. – The corresponding data direction register is TRISC. – Setting a TRISC bit (= 1) will make the corresponding PORTC pin an – Clearing a TRISC bit (= 0) will make the corresponding PORTC pin an output– The multiplexed pins to this port are:

4. Port D and TRISD– PORTD is an 8-bit port with Schmitt Trigger input buffers. – Each pin is individually configurable as an input o– output.– PORTD can be configured as an 8-bit wide microprocessor port (parallel slave

port) by setting to PSPMODE. In this mode, the input buffers are TTL. 5. PORTE and TRISE Register

– PORTE has three pins which are individually configurable as inputs or outputs.– These pins have Schmitt Trigger input buffers.– The PORTE pins become the I/O control inputs for the microprocessor port – Three analog inputs are multiplexed with this pins

TIMER0 MODULE• The Timer0 module timer/counter has the following features:

— 8-bit timer/counter— Readable and writable

Department of ECE, VKCET Page 85

Page 86: 08.601 MBSD Module 2

08.601 Microcontroller Based System Design

— 8-bit software programmable prescaler — Internal or external clock select— Interrupt on overflow from FFh to 00h— Edge select for external clock

TIMER1 MODULE– The Timer1 module is a 16-bit timer/counter consisting– of two 8-bit registers (TMR1H and TMR1L), which are– readable and writable.– The TMR1 Register pair (TMR1H:TMR1L) increments from 0000h to FFFFh

and rolls over to 0000h. – The TMR1 Interrupt, if enabled, is generated on overflow, which is latched in

interrupt flag bit TMR1IF (PIR1<0>). – Timer1 can operate in one of two modes:

o As a timero As a counter

TIMER2 MODULE• Timer2 is an 8-bit timer with a prescaler and apostscaler. • It can be used as the PWM time-base for the PWM mode of the CCP module(s). • The TMR2 register is readable and writable, and is cleared on any device RESET• The Timer2 module has an 8-bit period register, PR2 Timer2 increments from 00h until it matches PR2 and then resets to 00h on the next increment cycle. PR2 is a readable and writable register. The PR2 register is initialized to FFH upon RESET.

Department of ECE, VKCET Page 86