“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
R.N.SHETTY INSTITUTE OF TECHNOLOGY TECHNOLOGY Channasandra, Channasandra, Bangalore-560061 Bangalore-560061
MICROCONTROLLER LABORATORY MANUAL (06ESL47)
DEPARTMENT OF ELECTRONICS & COMMUNICATION ENGINEERING 2008
8051 MANUAL
RNSIT
1
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
VTU DRAFT SYLLABUS SUBJECT: MICROCONTROLLERS LAB EXAM HOURS: 3 (Common to EE, EC, IT, TC, BM and ML) EXAM MARKS: 50
I. PROGRAMMING 1. Data Transfer - Block move, Exchange, Sorting, Finding largest element in an array 2. Arithmetic Instructions - Addition/subtraction, multiplication and division, square, Cube – (16 bits Arithmetic operations – bit addressable) 3. Counters 4. Boolean & Logical Instructions (Bit manipulations) 5. Conditional CALL & RETURN 6. Code conversion: BCD – ASCII; ASCII – Decimal; Decimal - ASCII; HEX Decimal and Decimal - HEX 7. Programs to generate delay, Programs using serial port and on-Chip timer /counter
II. INTERFACING Write C programs to interface 8051 chip to interfacing modules to develop single chip solutions 8. Simple Calculator using 6 digit seven-segment display and Hex Keyboard interface to 8051 9. Alphanumeric LCD panel and Hex keypad input interface to 8051 10. External ADC and Temperature control interface to 8051 11. Generate different waveforms Sine, Square, Triangular, Ramp etc. using DAC interface to 8051; change the frequency and amplitude 12. Stepper and DC motor control interface to 8051 13. Elevator interface to 8051
Introduction
8051 MANUAL
RNSIT
2
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
PROCESSOR used is Atmel AT89C51ED2 - micro controller that has 64Kbytes of onchip program memory. It is a version of 8051 with enhanced features. AT 89C51ED2 89C51ED2 operates at 11.0592 11.0592 MHz MHz PROCESSOR FEATURES ON-CHIP MEMORY: CODE MEMORY: 64K Bytes of flash. DATA MEMORY: 256 Bytes of RAM, 1792 Bytes of XRAM, 2K Bytes of EEPROM. ON-CHIP PERIPHERALS Watch Dog Timer,Programmable Programmable Counter Array (PCA) on 3 16-bit Timers/Counters,Watch Port1 i.e. PWM and Capture & Compare, SPI (Serial Peripheral Interface) on Port1,Full Full duplex enhanced UART. INTERRUPTS Nine sources sources of interrupt (both external and internal). Two External interrupts INT0 and INT1 are provided with push button switches; these can also be used as general-purpose switches. I/O (Port) Lines Four 10-pin connectors for all the 32 I/O lines. P0, P1 and P2 Port lines are available on a 26-pin connector, 16X2 LCD & SERIAL I/O are also available.
Creating and compiling a μVision2 Vision2 project 8051 MANUAL
RNSIT
3
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
1. Double Click on the µ Vision3 Vision3 icon on the desktop. 2. Close any previous projects that were opened using – Project->Close. Project->Close. 3. Start Project – New Project, and select the CPU from the device database (DatabaseAtmel- AT89C51ED2). (Select AT89C51ED2 or AT89C51RD2 as per the board).On clicking ‘OK’, the following option is displayed. Choose Yes.
4. Create a source file (using File->New), type in the assembly or C program and save this (filename.asm/ (filename.asm/ filename.c) filename.c) and add this source file to the project using either one of the following two methods. (i) Project-Components,Environmentand Books->addfiles-> browse to the required file -> OK “OR” (ii) right click on the Source Group in the Project Window and the Add Files to Group
option. 5. Set the Target options using -> Project – Options for Target opens opens the Vision2 Vis ion2 Options for Target – Target configuration dialog. Set the Xtal frequency as 11.0592 Mhz, and also the Options for Target – Debug – use either Simulator / Keil Monitor- 51 driver.
If Keil Monitor- 51 driver is used click on Settings -> COM Port settings select the COM Port to which the board is connected and select the baud rate as 19200 or 9600 (recommended). Enable Serial Interrupt option if the user application is not using on-chip UART, to stop program execution. 6. Build the project; using Project -> Build Project. µ Vision Vision translates all the user application and links. Any errors in the code are indicated by – “Target not created” in the Build window, along with the error line. Debug the errors. After an error free build, goto Debug mode
8051 MANUAL
RNSIT
4
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
7. Now user can enter into Debug mode with Debug- Start / Stop Debug session dialog. Or by clicking in the icon. 8.The program is run using the Debug-Run command & halted using Debug-Stop Running. Also the
(reset, run, halt) icons can be used. Additional icons are
(step, step over, step into, run till cursor). 9. If it is an interface program the outputs can be seen on the LCD, CRO, motor, led status, etc. If it is a part A program, the appropriate memory window is opened using View -> memory window (for data RAM & XRAM locations), Watch window (for timer program), serial window, etc. Note: To access data RAM RAM area area type address as as D:0020h. Similarly to access the DPTR region (XRAM-present on chip in AT89C51ED2) say 9000h location type in X:09000H.
8051 MANUAL
RNSIT
5
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
1. DATA TRANSFER INSTRUCTIONS 1) Write an assembly language program to transfer n =10 bytes of data from location 8035h to location 8041h (without overlap). ORG 0000H SJMP 30H ORG 30H MOV DPH,#80H MOV R0,#35H //source address MOV R1,#41H //destination address MOV R3,#05H //count BACK: MOV DPL, r0 MOVX A,@dptr MOV DPL, R1 MOVX @dptr,A INC R0 INC R1 DJNZ R3, BACK HERE: SJMP HERE END RESULT: Before Execution: 10 locations X:8035h are filled up with data.
After Execution: 10 locations X:8041h are filled up with data from 8035h.
Algorithm 1. Initialize Initialize registe registers rs to hold count data data & also the source source & destinatio destination n addresses. addresses. 2. Get Get data data from from sour source ce loca locati tion on into into accu accumu mula lato torr and and tran transf sfer er to the the dest destin inat atio ion n location. 3. Decreme Decrement nt the count count registe registerr and repeat repeat step step 2 till count count is zero. zero. Note: For data transfer with overlap start transferring data from the last location of source array to the last location of the destination array.
8051 MANUAL
RNSIT
6
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
2) ASSEMBLY LANGUAGE PROGRAM TO EXCHANGE A BLOCK OF DATA. Write an assembly language program to exchange n = 5 bytes of data at location 0027h and at location 0041h.
ORG 00H SJMP 30H ORG 30H MOV R0,#27H //source address MOV R1,#41H //destination address MOV R3,#05H //count BACK: MOVX A,@r0 MOV r2,a MOVX a,@r1 MOVX @r0,a MOV a, r2 MOVX @r1,a INC R0 INC R1 DJNZ R3, BACK HERE: SJMP HERE END Aliter using XCH command. ORG 0000H SJMP 30H ORG 30H MOV R0,#27H //source address MOV R1,#41H //destination address MOV R3,#05H //count BACK: MOVX A,@r0 MOV r2,a MOVX a,@r1 XCH a, r2 MOVX @r1,a XCH a, r2 MOVX @r0,a INC R0 INC R1 DJNZ R3, BACK HERE: SJMP HERE END RESULT: Before Execution: 5 locations at X:0027h & X:0041h are filled up with data.
8051 MANUAL
RNSIT
7
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
After Execution: The data at X:8027h & X:8041h are exchanged.
Algorithm 1. Initia Initializ lizee registe registers rs to hold hold count count data (array (array size) size) & also the source source & destina destinatio tion n addresses. 2. Get data data from source source locatio location n into accumul accumulator ator and save save in a registe register. r. 3. Get data data from from the destina destination tion locat location ion into accum accumulat ulator. or. 4. Exchange Exchange the data data at at the two memory memory locat locations. ions. 5. Decreme Decrement nt the count regist register er and repeat repeat from from step 2 to 4 till till count is zero. zero. 3) ASSEMBLY LANGUAGE PROGRAM TO SORT NUMBERS. //BUBBLE SORT PROGRAM Write an assembly language program to sort an array of n= 6 bytes of data d ata in ascending order stored from location 8035h.(use bubble sort algorithm)
ORG 0000H SJMP 30H ORG 30H MOV R0,#0 ,#05 //c //count ount n-1 n-1 -AR -ARRAY SIZE IZE-n-n- Pass Count ounteer L1:: MOV L1 MOV dptr, dptr, #9000 #9000h h //arra //array y store stored d from from addre address ss 900 9000h 0h MOV A,R0 //initialize exchange counter MOV R1,A L2: MOVX OVX a, @dptr dptr //G //GET NUM NUMBER FRO FROM ARRAY MOV B, A //& //& STORE IN B INC dptr MOVX a, @dptr //next number in the array CLR C //reset borrow flag MOV R2, A //STORE IN R2 SUBB A, B //2nd - 1st no.—no compare instruction in 8051 JC NOEXCHG // JNC - FOR ASCENDING ORDER MOV A,B //EXHANGE THE 2 NOES IN THE ARRAY MOVX @dptr,a DEC DPL //DEC dptr-INSTRUCTION NOT PTRESENT MOV a,R2 MOVX @dptr,a INC DPTR NOEXCHG: NOEXCHG: DJNZ R1,L2 //decrement //decrement compare counter counter DJNZ R0,L1 //decrement pass counter here: SJMP here END Algorithm 1. Store Store the elem elements ents of the array array from from the the address address 9000h 9000h 2. Initialize Initialize a pass pass counter counter with with array size-1 size-1 count count (for numbe numberr of passes). passes). 8051 MANUAL
RNSIT
8
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
3. Load Load compare compare counter counter with with pass counter counter contents contents & initializ initializee DPTR DPTR to point to the start address of the array (here 9000h). 4. Store Store the current current and the the next array array element elementss pointed pointed by DPTR DPTR in register registerss B and r2 respectively. 5. Subtract Subtract the the next next element element from from the the current current eleme element. nt. 6. If the carry carry flag is set (for asce ascendi nding ng order) order) then exchang exchangee the 2 num numbe bers rs in the array. 7. Decreme Decrement nt the compare compare counter counter and repeat repeat through through step step 4 until the counter counter become becomess 0. 8. Decreme Decrement nt the pass counter counter and repeat repeat through through step 3 until until the counter counter becomes becomes 0. RESULT: Before Execution:Unsorted Array at 9000h
After Execution: Sorted Array (Descending order) at 9000h
4) Write an assembly language program to find the largest element in a given string of n = 6 bytes at location 4000h. Store the largest element at location 4062h. ORG 0000H SJMP 30H ORG 30H MOV R3,#6 //length of the array MOV DPTR,#4000H //starting address of of the array MOVX A,@DPTR MOV r1,a NEXTBYTE NEXTBYTE:: INC DPTR DPTR MOVX A,@DPTR CLR C //reset borrow flag MOV R2,A //next number in the array SUBB A,R1 //OTHER Num - PREVIOUS LARGEST no. JC skip // JNC for smallest element MOV A,r2 A,r2 //U //UPDATE larg larger er numb number er in r1 MOV R1,A skip:DJNZ R3,NEXTBYTE MOV DPL, #62H //LOCATION OF THE RESULT-4062H MOV A,R1 //LARGEST NUMBER MOVX @DPTR PTR,A //S //STORE AT AT #40 #4062 62H H OVER: SJMP OVER END
Algorithm 1. Store Store the the eleme elements nts of the array array from from the the addres addresss 4000h 4000h 2. Store Store the lengt length h of the array array in r3 and and set set it as counte counter. r. 8051 MANUAL
RNSIT
9
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
3. 4. 5. 6.
DPTR DPTR is loade loaded d with with starting starting addre address ss of the the array. array. Store Store the first first number number of the array array in r1 (r1 is assign assigned ed to hold the the largest largest number) number).. Incr Increm emen entt DPT DPTR. R. Subtract Subtract the number number pointed pointed by DPTR DPTR from the the contents contents of r1 (to compare compare whether whether the next array element is larger than the one in r1). 7. If the element element pointed pointed by by DPTR DPTR is larger larger then load load the larger larger number number into into r1. 8. Decreme Decrement nt the counter counter and repeat repeat steps steps through through 5 until until the counter counter become becomess 0. 9. Store Store the largest largest numbe numberr in r1 r1 in addre address ss 4062h 4062h
RESULT: Before Execution:
After Execution: Location 4062 has the largest element.
2. ARITHMETIC INSTRUCTIONS ASSEMBLY LANGUAGE PROGRAM ILLUSTRATING ADDITION, SUBTRACTION, MULTIPLICATION AND DIVISION . 5) Write an ALP to perform the following: If x=0-perform w + v; else if x=1-perform w-v; else if x=2-perform w*v; elseif x=3-perform w/v, where w & v are eight bit numbers. ORG 0000H SJMP 30H ORG 30H MOV R0, #40H MOVX A,@R0 MOV R1, A //R1 HAS CONDITION X INC R0 MOVX A,@R0 MOV B, A //B HAS 1ST NUMBER-v INC R0 MOVX A,@R0 //A HAS 2ND NUMBER-w CJNE R1,#00,CKSUB ADD A,B //PERFORM ADDITION MOV B,#00 //B HAS CARRY JNC SKIP MOV B,#01H SKIP:SJMP LAST CKSUB: CJNE R1,#01,CKMUL CLR C //RESET BORROW FLAG SUBB A,B MOV B,#00 //B INDICATES BORROW
8051 MANUAL
RNSIT
10
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
JNC SKIP1 MOV B,#0FFH //FF INDICATES NEGATIVE NUMBER SKIP1:SJMP LAST CKMUL: CJNE R1,#02,CKDIV MUL AB //16 bit product in AB with A having lower byte SJMP LAST CKDIV: CJNE R1,#03,OTHER DIV AB //Quotient in A & remainder in B SJMP LAST OTHER:MOV A,#00 MOV B,#00 LAST: INC R0 MOVX @R0,A INC R0 MOV A,B MOVX @R0,A HERE:SJMP HERE END Algorithm 1. Stor Storee the the cond condit itio ion n x in r1. r1. 2. Load Load the first and seco second nd number numberss to A and B register registerss respect respectively ively 3. Compare Compare the content contentss of r1 and perform perform the operations operations add, add, sub, etc etc accordingly accordingly.. 4. Store Store the result result present present in A and B registers registers to the appropriat appropriatee memory memory location locations. s. RESULT: Before Execution: ADD
SUB
After Execution: ADD
After Execution: SUB
Before Execution: MUL
After Execution: MUL
ASSEMBLY PROGRAM ILLUSTRATING SQUARE AND CUBE OPERATIONS. //cube is an example of 16-bit arithmetic operation //depending on flag condition, square or cube is performed // Flag is a bit in the bit addressable RAM, RAM, say 1st bit of location 20h is is used, then then bit address is 01 6) An eight bit number X is stored in external memory location 9000h. Write an ALP to compute (i) the square of the number X if LSB of data RAM 20h (bit address 01H) is set
8051 MANUAL
RNSIT
11
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
(ii) the cube of the number X if LSB of data RAM 20h (bit address 01H) is reset. Store your result at locations 9001, 9002, 9003h. ORG 0000H SJMP 30H ORG 30H MOV DPTR,#9000H MOVX A,@DPTR //GET NUMBER-X MOV R0,A //STORE IN R0 MOV B,A MUL AB //SQUARE IT-X^2 CLR C //FOR STORING RESULT JB 01,LAS 01,LAST T //IF BIT 01 IS SET THEN THEN END, END, ELS ELSE E DO DO CUB CUBE E PUSH B //STORE UPPER PART OF SQUARE MOV B,A //B-LOWER PART OF X^2 MOV A,R0 //A-X MUL AB //X*LOWER X^2 INC DPTR MOVX @DPTR,A //STORE PARTIAL RESULT MOV A,B MOV MOV R2,A R2,A //UPP //UPPER ER PART PART OF X*LO X*LOWE WER R X^2 X^2 IN R2 POP B //GET BACK UPPER PART OF SQUARE MOV A,R0 //A-X MUL AB //X*UPPER X^2 ADD A,R A,R2 //A //ADD TO TO PAR PART TIAL IAL RE RESULT SULT LAST:INC DPTR MOVX @DPTR,A MOV A,B ADDC ADDC A,#00 //ADD CARRY CARRY TO TO B(FOR B(FOR SQUARE SQUARE RESULT, RESULT, C=0) C=0) INC DPTR MOVX @DPTR,A HERE:SJMP HERE END RESULT: CUBE OF 56H IS 9B498 WHICH IS STORED AS 98, B4, 09 (LOWER BYTE FIRST)
To get square make the D1 bit of data memory 20h high, say FF,02,06,etc. The bit address is 01. Similarly bit address 78h correspond to D0 bit 0f data ram location 2Fh.
Algorithm 1. Store Store the eight eight bit bit number number x in A, r0 & B register registers. s. 2. Multiply Multiply A and B register registerss to obtain obtain the the square square (say (say SQH:SQ SQH:SQL) L) of the the number number x. x.
8051 MANUAL
RNSIT
12
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
3. 4. 5. 6. 7.
Check Check if bit 01 is set. set. If set go to end (stori (storing ng the result) result),, else do the cube cube operatio operations. ns. The high high part part of the squar squaree result result (SQH) (SQH) is stored stored on on the stack. stack. Multiply Multiply the the low part part of the square square result result (SQL) (SQL) with with x (partial (partial cube result) result).. Store Store the low low part of of the above above result result at 9001h 9001h & the the high part part in R2. R2. Retrieve Retrieve the the high part of the square square result result (SQH) (SQH) stored stored on the stack & multiply multiply with with x. 8. Add the low low part of the the above above result result (SQH*X) (SQH*X) with with R2 and store store in 9002h. 9002h. 9. Add the high high part part (SQH*X (SQH*X)) with the resulti resulting ng carry carry and store in in 9003. 9003.
3. PROGRAM ILLUSTRATING BIT MANIPULATIONS 7) Two eight bit numbers NUM1 & NUM2 are stored in external memory locations 8000h & 80001h respectively. Write an ALP to compare the 2 nos. Reflect your result as: if NUMINUM2, SET MSB OF 2F(7FH). if NUM1 = NUM2-Clear both LSB & MSB of bit addressable addressable memory location 2Fh ORG 0000H SJMP 30H ORG 30H MOV DPTR,#8000H MOVX A,@DPTR MOV R0,A INC DPTR MOVX A,@DPTR CLR C SUBB A,R0 JZ EQUAL JNC BIG SETB 78H SJMP END1 BIG:SETB 7FH SJMP END1 EQUAL:CLR 77H CLR 7FH END1:SJMP END1 END Algorithm: 1. Store Store the the eleme elements nts of the array array from from the the addres addresss 4000h 4000h 2. Mov Movee the first numbe numberr in r0 and the second second number number in registe registerr A respective respectively ly 3. Clear Clear carry carry flag and subtra subtract ct the two two numbers, numbers, if the carry carry flag flag is 0(if the nos nos are equal), Clear both LSB & MSB of bit addressable memory location 2Fh 4. If the carry carry bit is set then Set Set MSB MSB of 2F(7FH), 2F(7FH), else LSB of data RAM 2F (bit (bit address 78H). RESULT: 1) Before Execution: X:08000h = 45 & X:8001 = 35 After Executuion: D:02FH =01 2) Before Execution: X:08000h = 25 & X:8001 = 35 After Executuion: D:02FH =80 3) Before Execution: X:08000h = 45 & X:8001 = 45
8051 MANUAL
RNSIT
13
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
After Executuion: D:02FH =00
4. LOGICAL INSTRUCTIONS 8) ASSEMBLY PROGRAM ILLUSTRATING LOGICAL INSTRUCTIONS (BYTE LEVEL) 3 eight bit numbers X, NUM1 & NUM2 are stored in internal data RAM locations 20h, 21h & 22H respectively. Write an ALP to compute the following. IF X=0; THEN NUM1 (AND) NUM2, IF X=1; THEN NUM1 (OR) NUM2, IF X=2; THEN NUM1 (XOR) NUM2, ELSE RES =00, RES IS 23H LOCATION ORG 0000H SJMP 30H ORG 30H MOV MOV A, 20h 20h //donot //donot use #, as data data ram ram 20h is is to be acces accessed sed MOV R1,A //X IN R1 MOV A,21 A,21H H //A //A -NU -NUM1 CJNE R1,#0,CKOR ANL A, 22H SJMP END1 CKOR:CJNE R1,#01,CKXOR ORL A, 22H SJMP END1 CKXOR:CJNE R1,#02,OTHER XRL A, 22H SJMP END1 OTHER: CLR A END1: MOV 23H,A // //STORE STORE RESULT HERE: SJMP HERE END Algorithm: 1. Point to the the data data RAM RAM register register 20h 20h and and store store the the conditi condition on x. 2. Point to 21h and and 22h and and move move the first first number number to A regis register. ter. 3. Compare Compare the the contents contents of r1 and perfor perform m the operati operations ons according accordingly. ly. 4. The result result will will be be stored stored in 23H 23H regis register. ter. RESULT: 1)Before Execution: D:020H =00, 21=0f, 22 = 12 After Execution D:023H = 02 2)Before Execution: D:020H =01, 21=0f, 22 = 12 After Execution D:023H = 1F 3)Before Execution: D:020H =02, 21=0f, 22 = 12 After Execution D:023H = 1D 4)Before Execution: D:020H =34, 21=0f, 22 = 12 After Execution D:023H = 00 The above program can also be written as shown below (using indirect addressing) ORG 0000H SJMP 30H ORG 30H mov r0,#20h MOV A,@R0 //ON CHIP DATA RA RAM-DONOT USE MOVX
8051 MANUAL
RNSIT
14
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
MOV R1,A //X IN R1 INC R0 MOV MOV A,@R0 A,@R0 //A -NUM -NUM1 1 INC R0 // R0 POINTS TO NUM2 CJNE R1,#0,CKOR ANL A, @R0 SJMP END1 CKOR:CJNE R1,#01,CKXOR ORL A, @R0 SJMP END1 CKXOR:CJNE R1,#02,OTHER XRL A, @R0 SJMP END1 OTHER: CLR A END1:INC R0 MOV @R0,A //STORE RESULT HERE:SJMP HERE END Boolean variable instructions are also called as bit level logical instructions 9) 3 eight bit numbers X, NUM1 & NUM2 are stored in internal data RAM locations 20h, 21h & 22H respectively. Write an ALP to compute the following. IF X=0; THEN LSB OF NUM1 (AND) LSB OF NUM2, IF X=1; THEN MSB OF NUM1 (OR)MSB OF NUM2 , IF X=2; THEN COMPLEMENT MSB OF NUM1 STORE THE BIT RESULT IN RES, WHERE RES IS MSB OF 23H LOCATION ORG 00H SJMP 30h ORG 30h MOV R0,20H //R0-X CJNE R0,#0,CK1 MOV C,08H //LSB OF NUM1 (21H) - BIT ADDRESS -08 ANL C,10H //LSB OF NUM2 (22H) - BIT ADDRESS -10 SJMP LAST CK1:CJNE R0,#1,CK2 MOV C,0FH //MSB OF NUM1 (21H) - BIT ADDRESS -0F ANL C,17H //MSB OF NUM2 (22H) - BIT ADDRESS -17 SJMP LAST CK2:CJNE R0,#2,CK3 CPL 0FH MOV C,0FH //MSB OF NUM1 (21H) - BIT ADDRESS -0F SJMP LAST CK3:CLR C LAST:MOV 1FH,C //RES IS MSB OF 23H LOCATION -1FH HERE:SJMP HERE END RESULT: 20h = 00 => AND OF LSBs=1 (hence 80 in 23h location)
8051 MANUAL
RNSIT
15
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
20h = 01 => OR of MSBs = 0 (hence 00 in 23h location)
20h = 01 =>complement of MSB of 21h location. Hence 21h is changed to A1 and 23h location has 80h Before Execution After Execution
Algorithm: 1. Mov Movee the conditi condition on X (from (from 20h location) location) into into R0 regis register. ter. 2. If X=0; X=0; then move move LSB LSB bit of 21h to carry flag and ‘AND’ ‘AND’ Carry flag with with LSB bit of 22h. Goto step5 3. If X=1; X=1; then move move MSB MSB bit of 21h to carry carry flag flag and ‘OR’ ‘OR’ Carry flag flag with with MSB bit bit of 22h. Goto step5 4. If X=0; X=0; then complem complement ent MSB MSB bit of 21h 21h and move move it to carry flag. flag. Goto Goto step5 step5 5. Store Store Carry Carry flag at MSB MSB bit of of 23h location. location.
5. COUNTERS ASSEMBLY PROGRAM ILLUSTRATING HEX UP/DOWN COUNTERS. //counter program - hex/binary counters 10) Write an ALP to implement implement (display) an eight eight bit up/down binary (hex) (hex) counters on watch window. Note: to run this program, after selecting DEBUG session in the main menu use View-> Watch& call Stack window, in the Watches select watch 1(or 2) and press F2 and and enter a (for accumulator accumulator A) ORG 0H SJMP 30H ORG 0H MOV a,#00 BACK: ACALL DELAY INC a //dec a for binary down counter JNZ BACK HERE:SJMP HERE
DELAY: MOV r1,#0FFH DECR1:MOV r2,#0FFH DECR: MOV r3,#OFFH DJNZ r3,$ DJNZ r2,DECR DJNZ r1,DECR1 RET END
8051 MANUAL
RNSIT
16
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
RESULT: Accumulator A is incremented in binary from 00, 01,02…09,0A, 0B, …,0F,10,11,…FF
Algorithm: 1. Mo Move ve 00 to A regi regist ster er 2. Call the the delay subrouti subroutine ne for 1 second, second, in delay program program move move FFH to to registers registers r1, r2 and r3, loop and decrement decrement until 0. 3. Increme Increment nt A registe register(dec r(decrem remant ant for down down counter) counter)
ASSEMBLY PROGRAM ILLUSTRATING BCD UP/DOWN COUNTERS. //counter program – BCD up/down counters 11) Write an ALP to implement (display) an eight bit up/down BCD counters on watch window. ORG 0H SJMP 30H ORG 30H MOV a,#00 BACK:ACALL DELAY ADD a,#99H //ADD 01 for BCD up counter //for bcd counter DA A JNZ BACK HERE:SJMP HERE DELAY:MOV r1,#0FFH DECR1:MOV r2,#0FFH DECR:MOV r3, #0FFH DJNZ r3,$ DJNZ r2, DECR DJNZ r1, DECR1 RET END Algorithm: 4. Mo Move ve 00 to A regi regist ster er 5. Call the the delay delay subrouti subroutine ne for 1 second second (in delay delay program program move move FFH FFH to regis registers ters r1, r1, r2 and r3, loop and decrement decrement until 0). 6. Increme Increment nt A regis register( ter(add add 99h 99h for down down counter counter)) 7. Decimal Decimal adjust adjust accum accumulat ulator or for the the BCD BCD up/down up/down counte counter. r. RESULT: Accumulator A is incremented in BCD from 00, 01, 02…09, 10, 11,…99.
8051 MANUAL
RNSIT
17
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
6. SERIAL DATA TRANSMISSION Program illustrating serial ascii data transmission transmission (data-yE) p rogram, after selecting DEBUG DEBUG session in the main menu use Note-to use result of this program, View-> serial window #1. On running & halting the program, the data is seen in the serial window. 12) Conduct an experiment to configure 8051 microcontroller microcontroller to transmit characters (yE) to a PC using the serial port and display on the serial window. ORG 0H SJMP 30H ORG 30H MOV MOV TMO TMOD, D,#2 #20H 0H //ti //time merr 1; 1; mod modee 2 MOV TH TH1,#-3 #-3 //-3 //-3= =FD lo loade aded int into o TH TH1 fo for 96 9600 ba baud, ud, 11 11.0592 0592M MHz. MOV MOV SCO SCON, N,#5 #50H 0H //8//8-bi bit, t, 1 stop stop bit bit,, REN REN enab enable led d SETB TR1 //Start timer 1 AGAIN:MOV A,#’y’ //transfer “y” ACALL TRANS MOV a,#’E’ //transfer “E” ACALL TRANS AGAIN1:SJMP AGAIN1 TRANS: MO MOV SBUF,a //load SBUF HERE:JNB TI,HERE //Wait for last bit to transfer CLR TI //get ready for next byte RET END RESULT: yE is printed on the serial window each time the program is executed. Theory: In serial transmission as opposed to parallel transmission, one bit at a time is transmitted. In serial asynchronous transmission, the data consists of a Start bit (high), followed by 8 bits of data to be transmitted and finally the stop bit. The byte character to be transmitted is written into the SBUF register. It transmits the start bit. The 8-bit character is transferred one bit at a time. The stop bit is transferred. After the transmission, the TI flag = 1 indicating the completion of transmission. Hence in the subroutine wait until TI is set. Later clear the TI flag and continue with transmission of the next byte by writing into the SBUF register. register. (The program can also be written in interrupt mode). The speed of the serial transmission is set by the baud rate which is done with the help of timer 1. (Refer Ayala). Timer1 must be programmed in mode 2 (that is, 8-bit, auto reload). Baud rate Calculation: Crystal freq/ (12*32) = (11.0592MHz)/(12*32) (11.0592MHz)/(12*32) = 28800. Serial communication circuitry divides the machine cycle frequency(11.0592MHz)/(12) by 32 before it is being used by the timer to set the baud rate. To get 9600, 28800/3 is obtained by loading timer1 with -3 (i.e., FF – 3 = FD) for further clock division. For 2400 baud rate, 28800/12 => -12 = F4 in TH1. Algorithm: 1. Initialize Initialize timer timer 1 to operate operate in mode mode 2 by loadin loading g TMOD TMOD registe register. r. 2. load load TH1 TH1 with with -3 -3 to obta obtain in 9600 9600 baud. baud. 3. Initialize the asynchronous asynchronous serial communication communication transmission (SCON) (SCON) register. register. 4. Start Start timer timer1 1 to generate generate the baud baud rate clock. clock.
8051 MANUAL
RNSIT
18
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
5. Transmi Transmitt the character characterss “y” & “E” by writing into into the SBUF SBUF register register and waiting waiting for the TI flag.
7) TIMER DELAY PROGRAM Program illustrating timer delay 13) Generate a 1second delay continuously using the on chip timer in interrupt mode. ORG 0H //Reset Vector SJMP 30H ORG 0BH //TF0 vector SJMP ISR ORG 30H MOV a,#00 MOV R0,#0 MOV R1,#0 MOV TMOD,#02H //00000010-Run timer0 in mode 2 MOV TH0,#118 //Set up timer 0 to overflow in 0.05msec MOV IE,#82H //%10000010 – Enable timer0 interrupt SETB TCON.4 //Start the timer0 HERE:SJMP HERE ISR: CLR TCON.4 //Disable timer0 INC r1 //r1*r2 = 100*200 = 20000 * 0.05msec = 1sec CJNE r1,#100,SKIP MOV r1,#00 INC r0 CJNE r0,#200,SKIP MOV r0,#00H INC a SKIP: SETB TCON.4 //Enable Timer RETI //Return from interrupt subroutine END RESULT: Accumulator A is incremented in binary from 00, 01,02…09,0A, 0B, …, 0F, 10, 11, …FF every 1 second (for 33MHz clock setting & every 3 seconds for 11.0598MHz)
Algorithm: 1. 2. 3. 4. 5. 6. 7. 8. 9.
Set Set up timer timer0 0 in mo mode de 2 operat operation ion Load Load TH1 TH1 with 118 118 to generat generatee an interrupt interrupt every every 0.05m 0.05msec. sec. Reset Reset regis register terss a, a, r1 r1 & r0. r0. Repe Repeat at step step 4 cont contin inuo uous usly ly On inter interrupt; rupt; ISR at 000B 000B loact loaction ion goes goes to to step step 6 disa disabl blee time timer0 r0 Updat pdatee r1 & r0 Check Check if 20000 20000 interrupts interrupts (=1 (=1 sec) over. over. Yes –increm –increment ent accumu accumulato latorr a. enable enable timer timer & retur return n from from ISR. ISR.
8051 MANUAL
RNSIT
19
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
Timerdelay Timerdelay = 12*(257-delay)/frequency 12*(257-delay)/frequency Timerdelay=0.05msec Delay=256-((timerdelay Delay=256-((timerdelay * frequency)/12) frequency)/12) =256-(0.05*10 =256-(0.05*10 -3 * 33*106)/12 =256-137.5 =118.5 //loaded in TH0 To get 1sec delay 1/0.05msec 1/0.05msec = 200*100 in the ISR (assuming 33 MHZ crystal frequency. For 11 MHz, the calculations change).
8051 MANUAL
RNSIT
20
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
8. CONVERSION PROGRAMS 14) Write an ALP to implement decimal to hex conversion
ORG 0000H SJMP 30h ORG 30h MOV MOV DPT DPTR, R,#40 #40H H memory 40h MOVX A, @DPTR ANL A, #0F0H SWAP A MOV B,#0A #0AH MUL AB MOV r1,a MOVX A,@DPTR ANL A,#0FH ADD A,R1 INC INC DPTR PTR MOVX @DPTR,A HERE:SJMP HERE END
//2-di //2-digit git dec decima imall numbe numberr to be be conve converte rted d is give given n in data data
//obtain up upper de decimal digit //bring to the units place //M //MULTIPL IPLY tens dig digit with ith #0 #0A-to -toget tens tens in hex hex //temporarily //temporarily store the converted tens value //get the decimal number again //obtain the units digit //add to the converted tens value //in //incr crem emeent data data addr addreess //converted hexadecimal number in next location
RESULT: before execution- X:0040H = 45 (Decimal/BCD) After Execution: X:0041h = 2D (hex value) Algorithm 1. Mov Movee the decimal decimal data to be converted converted from exter external nal memory memory 40h to accumul accumulator ator.. 2. AND A reg with with 0f0h and and obtain obtain the upper upper MSB of the the decimal decimal digit digit and swap swap the LSB and MSB of accumulator to bring the same to units place. 3. Mov Movee 0ah to B registe registerr and multiply multiply with with A reg to conve convert rt to hex value, value, store store the converted tens value in r1 4. Get the the LSB LSB of the decim decimal al number number and and add to the the converted converted tens tens value value 5. point to to the next memo memory ry location location and store store the resul resultt (hexadecim (hexadecimal). al). 15) Write an ALP to implement hex to decimal conversion ORG 0000H SJMP 30h ORG 30h MOV DPTR,#9000H MOVX A,@DPTR //Get hex number MOV B,#10 DIV AB //divide by 10 (0AH) INC DPTR XCH A,B MOVX MOVX @DPT @DPTR, R,A A //Stor //Storee the the rema remainde inderr (in (in B) B) In units units pla place ce XCH A,B MOV B,#10 //Divide the quotient in A by 10 DIV AB INC DPTR
8051 MANUAL
RNSIT
21
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
XCH A,B MOVX MOVX @DPT @DPTR, R,A A XCH A,B INC DPTR MOVX MOVX @DPT @DPTR, R,A A HERE:SJMP HERE End
IVth SEM EC
//Stor //Storee the the rema remainde inderr (in (in B) B) In tens tens place place
//Stor //Storee the the quoti quotient ent (in A) in in hundr hundred edss place place
RESULT: 9000H – FF (HEX NUMBER) 9001 to 9003 – unpacked BCD number (decimal)- 5,5,2 (i.e., 255 stored Lower digit first)
Algorithm 1. Mov Movee the hex data data to to be conve converted rted to to accumu accumulato lator. r. 2. Mov Movee 10 to B registe registerr and divide divide with with A reg reg to convert convert to ascii ascii value value 3. Store Store the the conve converte rted d LSB LSB value value in r7 r7 4. Repeat Repeat the step 2 to obtain obtain the the convert converted ed MSB MSB value value 5. Store tore the the sam samee in in r6 r6
16) Write an ALP to implement BCD to ASCII conversion ORG 0000H SJMP 30h ORG 30h MOV R1,#50H MOV MOV A,@R A,@R1 1 //get //get BCD BCD data data byte byte from from RAM location location 50h MOV R2,A //Store in R2 ANL ANL A,# A,#0F 0FH H //Ge //Gett the the low lower er nib nibbl blee ORL ORL A,#30 A,#30H H //Add/ //Add/or or wit with h 30h i.e. i.e.,, 0-9 conv convert erted ed to 30-3 30-39h 9h INC R1 MOV MOV @R1,A @R1,A //Stor //Storee the lowe lowerr digit' digit'ss ASCI ASCIII code code MOV A,R2 //Get back the num number SWAP A //Swap nibbles in A ANL ANL A,# A,#0F 0FH H //Ge //Gett the the uppe upperr BCD BCD digi digitt ORL A,# A,#30 30H H //C //Conve onvert rt to to ASC ASCII INC R1 MOV MOV @R1,A @R1,A //Stor //Storee the uppe upperr digit' digit'ss ASCI ASCIII code code here: sjmp here END ASCII codes-38h 32h RESULT: The BCD code 28 at D:0050h is converted to 2 ASCII
Algorithm :
8051 MANUAL
RNSIT
22
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
//Converts the BCD byte in A into two ASCII characters. 1. Mov Movee the BCD BCD data data to be conver converted ted to accum accumulat ulator. or. 2. Get the the lower lower nibble( nibble(BCD BCD digit digit)) & ADD ADD (or ORL ORL)) with 30h 30h 3. Store Store the the conve converte rted d ASCI ASCIII value value 4. Get the highe higherr nibble(tens nibble(tens BCD BCD digit) digit) & ADD ADD (or ORL) ORL) with with 30h 5. Store Store the the conve converte rted d ASCI ASCIII value value 17) Write an ALP to implement hexadecimal to ASCII conversion //This program also illustrates conditional branching (JNC), call and return instructions. ORG 0000H SJMP 30h ORG 30h MOV R1,#50H MOV MOV A,@R A,@R1 1 //get //get hexadec hexadecimal imal data byte from RAM location location 50h 50h MOV R2,A //Store in R2 ANL ANL A,# A,#0F 0FH H //Ge //Gett the the low lower er nib nibbl blee ACALL ASCII //Convert to ASCII INC R1 MOV MOV @R1,A @R1,A //Stor //Storee the lowe lowerr digit' digit'ss ASCI ASCIII code code MOV A,R2 //Get back the num number SWAP A //Swap nibbles in A ANL ANL A,# A,#0F 0FH H //Ge //Gett the the uppe upperr BCD BCD digi digitt ACALL ASCII INC R1 MOV MOV @R1,A @R1,A //Stor //Storee the uppe upperr digit' digit'ss ASCI ASCIII code code here: sjmp here
ASCII:MOV R4,A //Store a CLR C SUBB A,#0AH //Check if digit >=0A MOV A,R4 JNC SKIP ADD A,#07H //Add 07 if >09 SKIP SKIP:A :ADD DD A,#30 A,#30H H //Else //Else add add only only 30h for 0-9 RET END D:0050h is converted to 2 ASCII codes-43h(for 0B) & 32h RESULT: The BCD code 2C at D:0050h (for 02) Another Example-BA
Algorithm : //Converts the hexadecimal byte in A into two ASCII characters. 1. Mov Movee the hexade hexadecima cimall data to be be converte converted d to accumula accumulator. tor. 2. Get the lower lower nibbl nibblee & call ASCII ASCII routine routine 3. Store Store the the conve converte rted d ASCI ASCIII value value
8051 MANUAL
RNSIT
23
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
4. Get the higher higher nibble nibble & call call ASCII ASCII routin routinee 5. Store Store the the conve converte rted d ASCI ASCIII value value ASCII subroutine 1. If digit digit greate greaterr than 09,(for 09,(for A-F) A-F) add 07h 07h & 30h 2. Else Else (i. (i.e., e., for 0-9) 0-9) add add only only 30h 30h 3. return 18) Write an ALP to implement ASCII to hexadecimal conversion ORG 0000H SJMP 30h ORG 30h MOV R1,#50H MOV A,@R1 A,@R1 //get ascii byte from RAM location 50h 50h CLR C SUBB A,#41H MOV A,@R1 JC SKIP CLR C SUBB A,#07H SKIP:CLR C SUBB A,#30H INC R1 MOV MOV @R1,A @R1,A //Store //Store the hex code code here: sjmp here END RESULT: The ASCII code 45 at D:0050h is converted to hexadecimal -0E at 51h
Note: For this program the input data should be only in the range 30h-39h & 41h to 46h. Algorithm : //Converts the ASCII characters into hexadecimal hexadecimal number. 1. Mov Movee the ASCII ASCII charac character ter to be conve converted rted to to accumulat accumulator. or. 2. If characte characterr is greater greater than than 41h,(for 41h,(for A-F) A-F),, then subtra subtract ct 07h & 30h 30h 3. Else Else (i.e. (i.e.,, for 0-9) 0-9) subt subtrac ractt only only 30h 30h 4. Store Store the the conve converted rted hexadeci hexadecimal mal num number. ber.
8051 MANUAL
RNSIT
24
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
INTERFACING PROGRAMS Hardware Interfacing
1.Waveform Generation using Dual DAC 2.Stepper Motor interface. 3.4X4 hexadecimal Keyboard interface 4.DC motor interface 5.Calculator 5.Calculator using Keyboard and Seven segment display. 6.Elevator 6.Elevator control. 7.Temperature 7.Temperature sensor. Features of Embedded C • C is a sim simple ple prog program rammi ming ng langu languag agee and so so very very easy easy to code. code. • Emb Embedde edded d C has has most most feature featuress of C-lang C-language uage with with more more stress stress on on certain certain bit manipulative instructions. • Th This is featu feature re make makess it easy easy to to write write progra program m for for μC and μP. 8 softwa • Keil Keil is a versat versatile ile software re with with a cross cross compi compiler ler that that will will conver convertt the C program program to to CRO assembly language languag (say 0e and thus the program can be executed on the desired target 8051).
5
P0
Dual
1 P1 Some of the bit manipulative manipulat ive instructions used are DAC Symbol Operation & Bitwise AND μCOR | Bitwise ~ Bitwise NOT >> Shift Right << Shift Left ^ P0.0
Xout
1.Dual Dac Interface to generate a.Square waveform b.Triangular Waveform c.Ramp waveform d.Sine waveform
8051 MANUAL
RNSIT
25
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
1.aAlgorithm for Square wave generation
Let initial, amplitude of the square wave be 2.5v(7F) and frequency count 100. Output the values 00h(0ff) and 7fh(on) Values through P0. If amplitude key key is pressed then increase increase the voltage in steps of 0.15v(8). 0.15v(8). If the frequency key key is pressed increment increment the count in steps of 50. If the count exceeds 1000 reset it back to 100. Every time amplitude amplitude and frequency changes output the value thro P0 and note the waveform on CRO.
Program for square wave
#include sbit Amp = P3^3; /* Port line to change amplitude */ sbit Fre = P3^2; /* Port line to change frequency */ void void dela delay( y(un unsi sig gned ned int int x) x) /* dela delay y rout routin inee */ */ { for(;x>0;x--); } main() { unsigned char on = 0x7f,off=0x00; unsigned int fre = 100; while(1) { if(!Amp) /* if user choice is to change amplitude */ { while(!Amp); /* wait for key release */ on+=0x08; /* Increase the amplitude */ } if(!Fre) /* if user choice is to change frequency */ { if(f if(fre re > 1000 1000)) /* if freq freque uenc ncy y exce exceed edss 100 1000 0 re reset set to to de defaul faultt */ */ fre = 100; while(!Fre); fre += 50; } P0=on; P1=on; delay(fre); P0 = off; P1 = off; delay(fre); }}
/* wait for key release */ /* Increase the frequency */ /* write amplitude to port */
/* clear port */
1.bAlgorithm for Triangular wave generation
Output the initial value 00 through P0.
8051 MANUAL
RNSIT
26
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
Increment it in steps of 1 until a count value of FFh (5V) is reached. Every Every time repeat step 1. Decrement it in steps of 1 until a zero value is reached and repeat step 1. Decrement Program for triangular wave: #include main() { unsigned char i=0; P0 = 0x00; /* P0 as Output port */ while(1) { for(i=0;i<0xff;i++){ /* Generate ON ON pulse */ */ P1 = i; P0 = i; } for(i=0xfe;i>0x00;i--) for(i=0xfe;i>0x00;i--) /* Generate OFF pulse */ {P0 = i; P1 = i;} } } 1.c.Algorithm for Ramp wave generation
Output the initial value 00 through P0. Increment Increment it in steps of 1 until a count count repeat step 1. Repeat step 1 & 2 continuously.
value of FFh (5V) is reached. reached. Every Every time
Program for Ramp waveform
#include main () { Unsigned char i=0; P0 = 0x00; /* P0 as Output port */ while (1) { for (i (i=0;i<0xff;i++) /* Generate ON ON pulse */ */ { P1 = i; P0 = i; } } } 1d.Algorothm for Sine wave
Compute different different step values (θ = 20o,15o…) of sine using the equation equation V= 2.5V +2.5Vsinθ. . Output the values thro P0. More the steps smoother will be sine wave.
8051 MANUAL
RNSIT
27
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
E.g.: θ = 0o V= 2.5V +2.5Vsinθ = 2.5V The value sent to DAC is 25.6X5V= 128.
Program for sine wave
#include main() { static int a[13]={128,192,238,255, a[13]={128,192,238,255,238,192,128 238,192,128,64,17,0,17,64 ,64,17,0,17,64,128}; ,128}; unsigned char i=0; P0 = 0x00; /* P0 as Output port */ while (1) { for(i=0;i<13;i++) /* Output different values */ { P0 = a[i]; } } } 2.Stepper Motor
• Stepp Stepper er moto motorr unlik unlikee DC DC moto motorr rotat rotates es in in steps steps.. • Stepper Stepper motor motor has has 4 coils coils which which forms forms the the stator stator and and a central central rotor. rotor. • Rotat Rotation ion depen depends ds on on excit excitati ation on of of stato statorr coils coils.. step coil A coil B coil C coil D 1 0 0 0 1 2 1 0 0 0 3 0 1 0 0 4 0 0 0 1 Anyone of these values forms the initial value. To get 360o revolution 200 steps are required. Step angle= 360o /200 = 1.8o. (difference between 2 teeth). Algorithm for Stepper Motor
• • • •
Confi onfig gure ure P0 P0 as as out outpu putt. Apply Apply the the initi initial al exci excitat tation ion of of 11 to moto motorr coils coils thro throug ugh h P0. P0. For clockwis clockwisee motion motion -Rotate -Rotate right right once the excit excitation ation and repe repeat at step step 2. For anticlock anticlockwise wise motion motion -Rotat -Rotatee left left once once the excitatio excitation n and repeat repeat step step 2.
8051 MANUAL
RNSIT
28
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
PS PS 8051µC P0 FRC 26pin Cable
Stepper Motor Interface Card
Stepper Motor
//Program for stepper motor interface #include void delay (unsigned int x) /* Delay Routine */ { for(;x>0;x--); return; } Main ( ) { unsigned char Val, i; P0=0x00; Val = 0x11; for (i=0;i<4;i++) (i=0;i<4;i++) { P0 = Val; Val = Val<<1; /* Val= Val>>1; for clockwise direction*/ delay (500); } } 3. 4X4 HEX Keyboard Algorithm for Keyboard Interface
• • •
Configur Configuree P1 as as output output port port to scan scan the rows rows and P0 P0 as input input port port to read read the the column column values. First First select select the the last row by by groundin grounding g that that row. row. Scan Scan the columns columns of entire entire row if if a key is pressed in that row then one of the column reads ‘0’. If now now key key is presse pressed d in the the select selected ed row all 1’s 1’s is returned. returned. So scan scan next next row. row. Repeat the action until all rows are scanned.
8051 MANUAL
RNSIT
29
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
PS PS 8051µC P0 FRC 26pin Cable
4X4 Keyboard Interface Card
4X4 Hex
keypad
//Program for 4X4 hex keypad. #include < REG51xD2.H> #include #include "lcd.h" unsigned char rows,columns,result,a rows,columns,result,abhi; bhi; unsigned char temp = 0; void delay() { unsigned int i; for(i = 0; i <= 20000; i ++); } void Display() { if(result > 0x09) { result += 0x37; WriteChar(result); } else { result += 0x30; WriteChar(result); } } void KeyScan() { again: columns = 0x77; rows = 0x04; result = 0x0c; next: P1 = columns; columns >>=1; if(CY) columns = columns |0x08 ; temp = P0; temp = (temp & 0x0f);
8051 MANUAL
RNSIT
30
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
if(temp != 0x0f) { rot: temp >>= 1; if(!CY) { ClrLcd(); return; } else { result += 1; goto rot; } } else { result -= 0x04; rows --; if(rows == 0) goto again; else { goto next; } } } void main() { P0 = 0xff; P1 = 0x00; InitLcd(); WriteString ("KEY PRESSED="); while(1) { KeyScan(); WriteString ("KEY PRESSED="); Display(); } } 4.DC Motor Algorithm for DC motor interface
• • •
Confi Configur guree P0,P P0,P1 1 as output output port port and and P3 as input input port. port. Let Let initi initiall ally y the motor motor rota rotate te with with hal halff speed speed coun countt 7fh. 7fh. If “INR” “INR” button button is pressed pressed reduce reduce the the count count becaus becausee the speed speed is invers inversely ely proportional to count. • If “DE “DEC” C” butt button on is is pres pressed sed incre increase ase the count. count.
8051 MANUAL
RNSIT
31
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
PS PS 8051µC P0 FRC 26pin Cable P3.2(inr) P3.3(dec)
DC Motor Interface Card
DC Motor
Program for DC motor
#include sbit inr= P3^2; //speed increment switch sbit dcr= P3^3; //speed decrement switch main() { unsigned char i=0x80; P0 = 0x7f; /*Run the motor at half speed.*/ while (1) { if (!inr) {while (!inr); if(i>10) i=ii=i-10 10;; //in //incr crea ease se the the DC DC mo moto torr spee speed d } if(!dcr) { while(!dcr); if(i<0xf0) i=i+ i=i+10 10;; //de //decr crea ease se the the DC motor otor spe speed } P0=i; } }
5.Calculator using Keyboard and 7-segment display Algorithm
• • • •
Read Read the numb numbers ers n1 and and n2 from keyboard keyboard and displ display ay them them on on seven seven segme segment. nt. Read Read the opera operand nd from from the keypad keypad if key key pressed pressed is B (+), (+), C(-),D C(-),D(*), (*),E(/) E(/) then then respective operation is performed. performed. Resul Resultt is displ displaye ayed d on 2 digi digitt seven seven seg segme ment nt displ display. ay. If any time the key pressed pressed value value returned returned as 10h then clear clear the the LCD. LCD.
8051 MANUAL
RNSIT
32
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
PS PS
8051µC P0 FRC 26pin Cable
Keypad
7 Seg Display
Program for calculator #include void DispChar(unsigne DispChar(unsigned d char ch); void ClrLED(); unsigned char getkey(); unsigned char getnum(); unsigned char getOp(); sbit sbit Clk = P3^4; /* Clock lock line line for for 7 se segment disp isplay lay */ */ sbit sbit Dat = P0^0; /* Data line ine for for 7 seg segment ment disp displa lay y */ main() { unsigned char tmp=0x0ff,n1=0,n2,Op,Res; unsigned char NumTab[10] = { 0x0c0,0x0f9,0x0a4,0xb0 0x0c0,0x0f9,0x0a4,0xb0,0x99,0x92,0x8 ,0x99,0x92,0x82,0x0f8,0x80, 2,0x0f8,0x80,0x90 0x90 }; unsigned char OpTab[4] = { 0x88,0x0Bf,0xc8,0x0a1}; bit Neg=0; ClrLED(); /* Clear 7 segment display */ while(1) { Neg = 0; /* Negative flag */ n1=getnum(); /* Get 1st number */
Op = getOp() getOp() - 0x0B; 0x0B; /* Get Opcode. Opcode. 0x0b 0x0b is keycode of of '+'(see keyboard keyboard schematics)*/ schematics)*/ n2=getnum(); /* Get 2nd number */ while(getkey()!= )!=0x13 x13); /* wait for '=' key */ ClrLED(); switch(Op) /* Perform corresponding correspon ding operation */ { case 0: Res = n1 + n2; break; case 1: if(n2>n1) /* check for negativity */ {
8051 MANUAL
RNSIT
33
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
Neg = 1; Res = n2 - n1; brea break; k; } Res Res = n1 - n2; break; break; case 2: Res = n1 * n2; break; case 3: Res = n1 / n2; break; } DispChar har(NumTab[Re [Res%10]); ]); /* Dis Disp play nu number */ */ DispChar(NumTab[Res/10]); if(Neg) /* if negative result display '-' */ DispChar(0x0Bf); }} void DispChar(unsigned char ch) /* Routine to display char on 7 segment */ { unsigned char i,tmp; P0=0x00; for(i=0;i<8;i++) /* for all bits */ { tmp = ch & 0x80; if(tmp) /* write data depending depending on MSB */ Dat = 1; else Dat = 0; Clk = 0; /* Give Clk Pu Pulse for synchronization */ */ Clk = 1; ch = ch << 1; /* Get next bit */ } } void ClrLED() { unsigned char i; for(i=0;i<4;i++) DispChar(0x0ff); DispChar(0x0ff) ; /* 0xff for clear segment ( see 7 segment manual manual for more info) */ } unsigned char getkey() { unsigned char i,j,indx,t; P2 = 0x00; /* P2 as Output put port */ P0 = 0x0ff; indx = 0x00; 0x00; /* Index Index for storing storing the first value value of scanline scanline */ while(1) { for(i=1;i<=4;i<<=1) /* for 4 scanlines */ { P2 = 0x0f & ~i; /* write data to scanline */ t = P0; /* Read readlines connected connected to P0*/ t = ~t; if(t>0) /* If key press is true */ {
8051 MANUAL
RNSIT
34
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
for(j=0;j<=7;j++) /* Check for 8 lines */ { t >>=1; if(t==0) /* if get pressed key*/ { return(indx+j); return(indx+j); /* Return index of of the key pressed */ } } } indx indx += 8; /* If no key key pres presse sed d incr increm emen entt inde index x */ } }} uns unsigne igned d char char get getnum num() /* Method thod for for gett gettin ing g num number ber */ { unsigned char tmp; while(1) { tmp = getkey(); if(tmp < 0x0a || tmp==0x10) /* if pressed key is number, return */ return(tmp); }} unsign igned char getOp() p() /* Method for getting Operator */ { unsigned char tmp; while(1) { tmp = getkey(); if((tmp > 0x0a && tmp <0x0f)|| tmp==0x10) /* if pressed key is a Operator, return */ return(tmp); }}
6.Elevator Algorithm for elevator interface • Read Read the floor floor reque request st thro throug ugh h inpu inputt port port P1. P1. • If the the current current floor and reque requested sted floor floor are are the same no change change light light up the the corresponding LED through P0. • If the the request requested ed floor floor greate greaterthan rthan current current moving moving up of of the lift is indica indicated ted by glowing of LED’s from current floor to the requested. • If the the request requested ed floor floor lesse lessertha rthan n current current moving moving down down of the lift is indica indicated ted by by glowing of LED’s from current floor to the requested.
8051 MANUAL
RNSIT
35
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
IVth SEM EC
PS PS 8051µC P0 FRC 26pin Cable
Elevator interface
Program for Elevator #include void delay(unsigned int); main() { unsigned char Flr[9] = {0xff,0x00,0x03,0xff,0x06 {0xff,0x00,0x03 ,0xff,0x06,0xff,0xff ,0xff,0xff,0xff,0x09}; ,0xff,0x09}; unsigned char FClr[9] = {0xff,0x0E0,0x0D3,0xff,0x0B6,0xff,0xff,0xff,0x79}; unsigned char ReqFlr,CurFlr = 0x01,i,j; P0 = 0x00; P0 = 0x0f0; while(1) { P1 = 0x0f; ReqFlr = P1 | 0x0f0; while(ReqFlr == 0x0ff) ReqFlr = P1 | 0x0f0; /* Read Read Request Request Floor from from P1 */ ReqFlr = ~ReqFlr; if(CurFl if(CurFlrr == ReqFlr) ReqFlr) /* If Request Request floor is equal equal to Current Current Floor Floor */ { P0 = FClr[CurFlr]; /* Clear Floor Indicator */ cont contin inue ue;; } /* Go up to read read agai again n */ else else if(C if(Cur urF Flr > ReqFlr qFlr)) /* If Curre urrent nt floo floorr is > requ reques estt flo floor or */ { i = Flr[CurFlr] Flr[CurFlr] - Flr[ReqFlr]; Flr[ReqFlr]; /* Get the no of floors to travel */ j = Flr[CurFlr]; for(;i>0;i--) /*Move the indicator down */ { delay(25000); }} else /* If Current floor is < request floor */ { i = Flr[ReqFlr] - Flr[CurFlr]; /* Get the no of floors to travel */ j = Flr[CurFlr]; for(;i>0;i--) /* Move the indicator Up */ { P0 = 0x0f0 | j; j++;
8051 MANUAL
RNSIT
36
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
delay(25000); } } CurFlr = ReqFlr; P0 = FClr FClr[C [Cur urFl Flr] r];; } } void delay(unsigned int x) { for(;x>0;x--); }
IVth SEM EC
/* Update Current floor */ /* Clea Clearr the the indi indica cato torr */
7.Temperature Sensor
PS PS 8051µC P0,P2,P3 FRC 26pin Cable
Temp Sensor Interface
Heat Source
The interface card has a DAC to convert the actual temperature to digital this is compared with reference temperarture. temperarture. Realay Realay also a part of interface card will turn on and off to indicate if the actual actual temperature temperature is above or below reference. reference. Algorithm for Temperature Temperature sensor 1. Config Configure ure P0 P0 and and P1 as as o/p, o/p, P3 as as input input port port.. 2. Set up up a counter counter with with intial intial value value 0xff send it to dac thro P0 after after a delay check if comparator o/p has gone low. 3. If low low compare with set value if actual actual greaterthan greaterthan set turn on the relay relay else turn off.
Program for temperature sensor. #include sbit Cmp_Out = P3^4; /*Input Bit for Comparator output*/ sbit sbit Rel_Con = P0^0; ^0; /*Relay co controlle ller Bit Bit i.e He Heate ater Po Power wer su supply co control*/ /*1- Supply OFF, 0-Supply ON*/ #define Dac_Data P1 /*DAC input Data PORT i.e. P1*/ void delay() { int l; for (l=0;l<=0x8;l++); } main() { unsigned char DacIp; void delay(void); Dac_Data =0x00; /*Move 00h to Dac input*/
8051 MANUAL
RNSIT
37
“MICROCONTROLLERS “MICROCONTROL LERS LAB”
P0=0x00; while(1) { DacIp= 0xff; do { DacIp++; Dac_Data = DacIp; delay(); }while(Cmp_Out); if(DacIp > 0x20) Rel_Con = 1;
IVth SEM EC
/*make P0 as output*/
/*DAC input Data counter*/
/*Increment the DAC input Data*/ /*Move the DAC data to DAC*/ /* Check comparator output for low */ /*Compare with the set value i.e.0x20*/ else Rel_Con = 0; }
/* Relay ON, Supply OFF */
}
8051 MANUAL
RNSIT
38