0% found this document useful (0 votes)
163 views63 pages

MC Unit 5

mc book

Uploaded by

Ketan Surashe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
163 views63 pages

MC Unit 5

mc book

Uploaded by

Ketan Surashe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 63
| at —Sjabus Topic : Port Structure with st Programming Port Structure with Programming A ‘Elan PICISFXXX port structure. (Dec. 2014, 8 Marks) ‘plain he function of port of PIC in deta (May 2016, 8 Marks) Some of the pins of /O ports are multiplexed with an alternate function from the peripheral features on the device. Whenever a peripheral is enabled that pin cannot be used as a general purpose /O pin. For using the ports as an input or output we need to program the ports. Each PORT has three SFRs for its operation. ‘They are : @ PORTs (reads the levels on the pins of the device) Gi)" TRISx (data direction register) Gii)_LATx (output lateh) ~ The general purpose VO ports available on the PIC 18FXX devices depends on the number of pins on the chip. - Table 8.1.1 shows the number of ports in PICI8 Fanily members. ‘be 8.1.1 : Number of ports in PICI8 family members Eg. for Port D we have PORTD, TRISD and LATD SFRs. TRISx register is used for making the port an input port or output port. ‘The LATx register is used for read-modify-write operations. ‘Table 8.1.2 lists the SFR addresses of ports AE for PIC 18F458. P di Porte ‘A, Port B, Port C, Port D om ethip | Numbor | Number | Ports Avlele SFR addresses of ports A-E for PIC 18458 otPins_| of Ports xe Ferrio | tern | 2 | Pot A, Pot Feo Perma | aapin | 9 | Por A, Pot 8, Pot FSI © Fe2il Feta | aopin | 5 | Port A, Port B, Port FSH G,Por D, Por E Fei Potress | capn | 9 | Port A, Por B, Pot Fou ©, Port D, Pot E, FAH Pot F, Pot 6, Por FeBH H,Potd roa Potreses [opin | 11 | Pot A, Pot B Pot F8DH 6, Pot 0, Pot Es a Pot F For. Pt Sn aa 1, Pon J, Por K, mse aun ~ Port a Me = TRISD 'IC 18F 48 is a 40 pin IC having 6 UO ports me aa ced as input ports OF output ports. p58 port as input OF output port. Eg To, Ports ‘AE can be us te make a port a8 Output pot me yy! 1 figuring « PIC 16) ‘The PIC 18F488 ‘1s to the TRISx register and ‘Uso: The SER TRISK is used for €O port a input port we need 10 te write Os to the TRIS register: [All the PIC 18F458 ports input ports. 1 Reading a Pin WhenTRI esas ie, om reset all the ports are configu 5 have values FFH on 8. sx = 1 (Input) =e know tat to make a port an input we need prite a 1 into the TRISx resister. Fig. 62134, resem 0 from a PICIB pin and Fig, 62:2 shows vending a 1 from the PICIS pin when TR; Fig. 821 shows the structure ofa PICIS port ‘along with its a So wt components. oo D alk i ve WR PORT xX ‘oD Seale | 1 } P : 4 — re {4 | N wars |_[S, 7 TRIS =1 CLK a 0 Ves ou ‘Schmitt trigge y oan Fig, 8.2.2 : Reading a 1 from PICS port pin The sequence of events while reading at the port pin are as follows: [gt ; Write a Lon the TRIS Latch. This will make its Q output high ie. 1 and Q output will be low. sell ; ASQ =1, the P transistor will turn off and as @ <0, transistor N will turn off. As both ts wore are off, they will block the path towards Vio or ground and the input signal passes to the buffer. Sell ; Thus, while reading the data from. input port we are reading the data at that pin. te: "ae easing data from the input port there are two possibilii@s: 1) some instructions read the status of intemal latch referred as LATX [9 seme instructions read the status of input port pin. Hence, tO avoid errors in program \éterentiate between the two instruction possibilities. | Theinstuctions that read the status of input port are as follows : 0) MovewPORTx (i) _BTFSS1,P BTrSCt.b (vy) TSTFSZt__(v) CPFSEQE Qa; 2 Writing to a Pin When TRISx = 0 (Output) ‘ced to write a 0 into the TRISx register of er that for making a port an output port we ni Fig. 8.23 shows writing a 0 to PIC 18 pin. The sequence of events while writing data on the are as follows : ming we must be able to Sep Seon Write a on the data latch, This will make Q=O.and @ output will be 1. As Q =1, the P transistor will turn off and N transistor will turn on, As the N transistor is om it provides a path towards ground to the input pin: Thus, if the programmer tries to read data from the PIC 18 pin, it will receive 8 low signal. o4 icrocontrotors (SEPU-ESTO) ROL wave | oso = D Yoo no wave] bet g}*§ —p'y>-HE gym ot DATALATCH ci —s anasto Lopate dE ar pm XY ' Ves wams| bow alt ll ras=0 a y on TIS LATCH a <} o op en no PORT Fig. 8.2.3 : Writing a 0 to PICI8 pin 7 Number of pins : Port A is a 7 bit 8.3_Reading LATx for PORTS ___| tidirectional port with 7 pins RAO to RAG. ‘Use : The LATx SFR is used for read-modify-write | - ‘The port A pins are multiplexed with the at operations. to digital converter. Hence, it has ale — We know that some instructions read the status functions as listed in Table 8.4.1. of internal Intch. Such instructions generally read a latch value, do the required operation ‘Table 8.4.1 : Port A Alternate functions and rewrite the value back to the port latch. = a Table 83.1 lists these instructions. They are portsite Funds called as Read-write- modify instructions. RAO ANO/ CVn Table 8.3.1 : Read-write-modify instructions mar ANL Instruction Function fe AN2/ Veet 1) ADOWF 6a] | Add Weg and fle RAS a 3)_BCF Iba) Clear bit of a fle register NGF al [sone RAS “ANA / $57 LDN. 4 ‘CONF fidJal] ‘Complement a fle registor RAG ‘OSC2/ CLKO ORWE Fao | Lagea excusve OR WRE i fie register 3 8.4.1 Port Aas Simple Input Pot bi Saray [su : go nn — series = When port A is used as simple 7%. must be written in all the bits “ } << register, Explain Pont A of PICLERXX. = Inthe following code Port Ais OE (Deo: 2014, 8 Mickey input port by writing 1s to the 7 is @. Explain function of port A of PIC in dota, ) The data obtained will be ** L—__ (tay 2016, 6 tarks | location of the file register. a 2 Por. toll the bits in TRISA register, Heat wer afigured as an output port. Port Bit | Function q RCO sort B —— Jaa a] RC1_| Ti0St § RC2__| CCPL foe PIC18FXXX. Ros | SCKSCL (Dec, 2014, 8 Marks) RC4 SDUSDA spin hetion of port B of PIC In dota. Ror tebe o (May 2016, 8 Marks) ROG ins: Port B is an 8 bit ae er of t Ror TREY DT ah mal port with 8 pins RBO-RBT. vidi to minimize the pins, the PIC18 Port B 8.6.1 Port C as Input er _ inorder Uiiplexed to some other functions. | — When ; input port “1” must be jins are mole : port C is used an input por Fable 85.1 lists the alternate functions of written in all the bits of TRISC register iB. Fable 85.1: Port B alternate functions 8.6.2 Port Cas Output Por it Function = If we write 0's to all the bits in the TRISC 80 into register, port C will be configured as an output port. ‘RBI INTI REQ INT2/ CANTX 8.7 PortD Peed en ad RBS CANRX. RBS - a Explain port D of PIC18FXXX. RBS PGM (Dec. 2014, 8 Marks) c a. Explain function of port D of PIC in detail. ree eS (May 2016, 8 Marks) Pe is) Number of pins : PORT D is an 8 bit bidirectional 45.1 Port B as Input Port ~ When port B is used as a simple input port “1” ust be written in the TRISB register 45.2 Port B as Output port with 8 pins RDO-RD7. = Table 8.7.1 lists the alternate functions of PORT D Table 8.7.1 : Port D alternate functions ~ Ifwe write 0's to all the bits in the TRISB Port Funetion "egister, Port B will be configured as an output sie ao c RDO | PSPO/C1IN + [Eee Eriencns ad RD1 | PSP1/CIIN- aE RD2 | PSP2/C2IN+ [Elan por ¢ of PICEF XXX. RD3_| PSP3/C2IN— Q (Dec. 2014, 8 Marks) RD4 | PSP4/ECCP1/P1A plain function of port C of PIC in detail. RDS | PSP5/PIB Neher oy (ay 2016, 8 Marks) RDS | PSPG6/PIC ‘nectional port : Port C is an 8 bit wide Sar | FePrELD ~ hy with 8 pins RCO-RC7. fr 86.1 lists the alternate functions of ae 8.7.1 Port D as Input — When Port D is used as input port a “1” must be written to all the bits in the TRISD register. 8.7.2 Port D as Output If we write 0's to all the bits in the TRISD register, Port D will be configured as an output Port 8.8 PortE To a. Explain pot E of PICIFXXX. (Bec. 2014, 8 Marks) Explain function of port E of PIC in detail. (May 2016, 8 Marks) Number of pins : Port E is a 3-bit wide, bidirectional port. Port E has three pins (REWANS/RD, — REVANG/WR/C1OUT REQAN7/CS/C20UT) and which are individually configurable as inputs or outputs. These pins have Schmitt Trigger input buffers. 8.9 Read-modify-write operations on the LATx register, read and write the latched output value for Port E. The corresponding Data Direction register for the port is TRISE. Setting a TRISE bit (= 1) will make the corresponding Port E pin an input (i.e., put the corresponding output driver in a high-impedance mode). Clearing a TRISE bit (= 0) will make the corresponding PORTE pin an output (i.e., put the contents of the output latch on the selected pin). ‘The TRISE register also controls the operation of the Parallel Slave Port through the control bits in the upper half of the register. When the Parallel Slave Port is active, the Port E pins fanction as its control inputs. Port Status Upon Reset All the PIC18F458 ports have value FF H on their TRIS register on reset. i.e. all the ports are configured as input ports on Reset. Table 8.9.1 gives the Reset values of TRIS registers for PICI8F458. Table 8.9.1 : Reset value of TRIS registers for PIC18 Register Reset Value @inary) TRIS,A wun TRIS'B wnt TRIS C 11111111, ‘TRISD 111111, Program 1 Write a C18 program to continuously. toggle all the bits of port C include void main (void) { 0 Make Port ¢ | M repeat foreyee PORTC 0555; 11 Ox indicates data ig PORTC = OxAA; } he, Program 2 Write a C program to toggle all the bi continuously. # inchide < P18F458.h> void main (void) { 8 of Pac TRISD = 05 for (3) { PORTD PORTD , | Program 3 Write a C program to toggle all bits of Port A 100) times. # include < PIBF458.h> void main (void) Make Port D an otpat pe x55 OxAA; { unsigned int 1 Bort A is output por 0; i < = 10,000 ;i ++) PORTA = 0355 PORTA = OxAA } while (1) ; i Program 4 ; ot Po Write a C program to toggle all the be att continuously with a 250 ms delay. Assut # include < P18F458.h> void Delay (unsigned int) ; void main (void) { TRISA = 1) Port Ais outpst PO while (1) ae | p con wo use functions like DELAY in the ® Teed to know following points : cn ‘fore the main function, the declaratio ja Delay Cunsigned int) ‘y uell the compiler that there will be a ‘laion called DELAY. It is called funetion prototype. 4 me functions are generally defined ediately after the main program ends as iomogram 4 The first line of function Gaaration must be exactly same as its function prototype. 7s SELES ye2aC program to toggle all bits of Ports B, C, D ‘rirucusly with a 250 ms delay. Assume AL = 10 MHz. # include void Delay (unsigned int): void main (void) { TRISB = TRISC Make Ports A, B, C and D as TRISD output ports forever while (1) { PORTB = 0155; // Toggle ports A, B.C, D PORTC = 0x55 5 PORTD = 0x55 ; Delay (250) ; PORTB = OxAA; PORTC = OxAA; PORTD = OxAA; Delay (250) + + } void Delay (unsigne { unsigned int is tunsigued char § for i= 051 ) ramon to branch to the interrupt vector address when the flag bit is set (© Interrupt priority bit, to assign high © riority or low priority to the interrupts. ] 3 Interrupt Structy rocontrotlers (SPPU-E&TC) 2 ope feature is enabled by These interrupts need to activated by y feature is e = The interrupt, pris maiog ithe IPEN bit in the RCON register When interrupt priority is enabled, there are two bits that enable interrupts globally. 9.4.1 Timer Flag Interrupts a timer/counter overflows, the corresponding timer flag TMROTF, TMRIF, TMR2IF and TMRSIF. The flag is cleared to 0, when the interrupt generates a program call to the timer subroutine in the memory. 9.4.2 Serial Port Interrupts The serial port interrupt is generated because of TXIF or RCIF. One interrupt is used for sending the data byte and the other whenever a data byte is received. - If the TXIE or RCIE flags in the PIE register are enabled when TXIF or RCIF are 1, the PIC18 microcontroller is interrupted and goes to 0008H location for executing the interrupt service routine. 9.4.3 External Hardware Interrupts The PIC18 supports three external hardware interrupts. They are INTO, INT1 and INT2. ‘These interrupts are located on pins RBO, RB1 and RB2. They are directed to vector location o008H. — These interrupts can be enabled by setting the INTxIE bit in the INTCON and INTCON3 registers. - On reset, the microcontroller configures these interrupts as positive edge triggered interrupts. 9.4.4 PORT B-Change Interrupts The pins RB, ~ RB; of port B can invoke an interrupt whenever any modifications are detected on the respective pin. The interrupt is called “PORTB-change interrupt”, ~ These interrupts have a single interrupt flag RBIF in the INTCON register. They can be enabled by the RBIE bit in the INTCON register. - Even though PORT: four port B pins, interrupt. This interrupt is use interfacing. 25 RT-B change interrupt can use it is considered to be a. single d mainly for keyboard Enabling and Disab! ling an Interrupt the interrupts an so that the by son interrupts. be emai cg ‘The interrupts can be enabled or gi modifying the GIE bit in the INTCON sity, Size: Fig. 9.5.1 shows the INTCON regis, controller can, 8 bit addressable register. It conpar thy bit, that disables all the interrupts wot Ds TWROIE Do INTOIE o Ds GE Ds PEIE GIE (Global Interrupt Enable) If GIE = 1, interrupts are enabled, interrupt source is enabled by setigg respective interrupt enable bit, If GIE = 0, all interrupts are disaby none of them will be acknowledged, ‘TMROIE : Timer 0 interrupt enable ITMROIE = 0 Disable Timer 0 overflow inter TMROIE = 1 Enable Timer 0 overflow inte INTOIE : External Interrupt 0 enable or disable INTOIE = 0 Disable external interrupt zer INTOIE = 1 Enable external interrupt 0 9.5.1: INTCON (interrupt control) register - For servicing an interrupt, the IE (interp enable) flag bit for that interrupt must be # with the GIE bit. After the interrupt is activated the GIE biti cleared. This ensures that the microcontnl will not service any other interrupt. After servicing the interrupt, the RETF instruction will activate the GIE bit, s microcontroller can service other interrupts ‘The PEIE (Peripheral Interrupts Enable) # must also be enabled if peripherals like Tis®* Serial port ete. are used. 9.6 Steps in Enabling ——an interrupt ‘To enable an interrupt the following steP5™" be considered : 5 cs ed, aa StepI : Set the GIB bit of INTCON wa interrupts. ae Step 11 : Set the corresponding IE (in! % enable) bit for that inter™F fy INTOIE will enable at interrupt 0. If the GIE bit ook then no interrupt will be gute even if the bit in the register is set. Rterrupts like TMROIF, "TMRITP, iMnaIF, ‘TXIF. Tho GIE bit must also be set. cis Interrupt programming in C Using 18 Compiler (18 eompilor uses the #pragma directive soot endo at a particular ROM address, Hransferring control to the ISR we need to Fa teembly language instruction GOTO, se the C18 compiler does not place ISR at yf wo) For wernerrupt vector table automatically. Tt is done as? Fpegence bi jori = 0x0008 | I high priority interrupt location prior (void) { osm GOTO high_isr _endasin } H#pragma code Hend code To compute the interrupt source we are ‘rected from location (0008H to other program using tyyord interrupt as follows : # fagma interrupt high_isr rid high ist (void) ( Weise —— Sjlabus Topic : Use of Timers with Interrupts 98 Use of Timers with Interrupts garner ee ao FEE WT Jntorrupt st it set for peripheral ‘This drawback can be meee method. If the timer interrupt tae ad flog is set whenever the ti Thue ice PIC m icrocontroller is \terrupted. ee ea Perform any operation till it is e rupt ic Table 9.8.1: ee terrupt set, then the ier in rolled Timer interrupt flag bits and their registers Timar_| Enabiobit | Register [Interrupt fag bi | Rogister Timero |" “Tunoe |intcon | TRO | INTCON Timer | “Tune |" PET [TRUE PIR Timor2 | TMAZIE | PIET TMRAIF PIL Timers | Ture | PIE2 | TMRSIF PIR Ex. 9.6.1 EEEEERGE Write a program to generate square wave 2 KHz with Timer 0 on pin PORTB.S5 with interrupt. Soln. = ‘The period of square wave = FGFs = 500 HS ___ Let us assume the duty eyele of square wave is 50%. Hence, the square wave will be high for > The Timer 0, Timer 1, Timer 2 and Timer 3 interupts are generated by TMROIF, TMRUP, TRAP and TMRSIF. These bits are set by E nllover in the respective Timer registers. When a timer interrupt is generated, the flag iit generated it, is cleared by the on chip . mare when the interrupt service routine 1 Taster chapters, we have se Trey 2 and 3 with the polling IRxIF flag is set whenever the ti en the use of ling method. mer rolls er, ac " wi Polling method ‘TMRxIF flag is monitored agit? user has to wait till the TMRxIF flag is minted: This is the main drawback of the "ng method, 250 ps and low for 250 ps. LetXTAL = 10 MHz. foe ‘Timor clock frequency = “= 208 «2.5 wine ‘Timer clock period = SE HEz = 04 ps ie. counter will count up every 0.4 ps. Be = 625 “i Count = 65596 ~ 625 = (64911),0 = FDF8H ‘TMROH = FDH 'TMROL = F8H 18 Program : Finchude ‘alefine mybit PORTBDs.RBS ‘yoid Timer 0_ISR (void) 5 #praggna interrupt my Ist void my_ist (void) jf (NTCONDits TMROIF = = 1) {Jif Timer 0 caused interrupt execute Timer 0 ISR Timer 0_ISR () + 008 sagia code hiprior|_int ; i I! high priority interrupt ‘oid hiprior’_int (void) { Microcontroller’, SPP TC) Senda ) # pragma code oid main (void) ‘ 15 = 0; // Make RBS output TRISH bits. TRIS: TOCON © 0x08 J/ Timmer 0, internal J, 16 bit mode, 00 presealer 1) Load TMROI J Load TMROL ‘TMNON = OxFD TMROL = OxF8 5 INTCONDIt ATMROIF = 05 1] Clear TMROIF flag, INTCONhits. TMROTE = 1 Enable Ti TOCONDits. THROON 1 Start Timer 0 INTCONDits.GIE, 1/ Enable all interrupts globally INTCONDits.PE 1/ Enable all peripheral interrupts } void Timer 0_ISR (void) it mybit = ~ mybi I Toggle RBS TMROH = OxFD; —_// Load TMROW TMROL = OxF8 5 1 Load TMROL, INTCONbits.TMROIF = 0 ; // Clear TMROIF flag, } Ex. 9.8.2 Write a program to generate frequencies of 2 KHz and 10 KHz on pins RB3 and RB4 respectively. Assume crystal frequency = 10 MHz. Soin. : fore ‘Timer clock frequency = =] sua 5 MHz Timer clock period = im = 0.4 pisee For 10 KHz (period = 0.1 msec) On period is 0.05 msec and off period is 0.05 msec, assuming 50% duty eycle. 0.05 msec - “Odpsec = 125 Count = 65536 - 125 = (65411), = FF83H ». TMRIH = FFH TMROL = 83H For 2 KHz (period = 0.5 msec) On period is 0.25 msec and iod i 0.25 msec, assuming 50% duty eyele. om period is . 0.25 msce “O04 psec = 626 65536 - 625 = (64911), = FD .TMROW = FOR TMROL = sFH +. Count F include # define PBS PORTBBIte.RBS define PIM PORTBDIts RD void Timer 0 ISI (void) 5 1 L_ISR (void) 5 # praagena it I high priority isr (void) { if (NTCONDits. MROLE Mil Timer 0 caused jpg ir I execute Timer yo ij ot ‘Timerl_(ISR) 5 Mexecute Timer } #pragma code hi_priori = Ox08 | I high priority void hi_priori (void) | { _asm GOTO my_isr _endasmn } # pragma code void main (void) { ‘TRISBbits. TRISB3 = 0; // Make RB3 an outpat ‘TRISBbits.TRISB4 = 0; // Make RBA an capt TOCON = 0x08 ; 1] Timer 0,16 bit ad, no prescaler TMROH = OxFDH ; J Load TMROH TMROL = 0x8FH; —//Load TMROL TICON = 0x88 ; Jj Timmer 1, 16 bit mode no prescaler TMRIN=OxFF; Load TMRIH ‘TMRIL = 0x83 ; 1/ Load TMRIL INTCONbits.TMROIF = 0; //ClearTize® interrupt Ost PIRAbitsTMRUIF J) Clear Tt interrupt fhe INTCONDits-TMROIE = 15 // Ensble Tet 0 interrupt PIEIbits.TMRIUE 1] Enable Tine! interrupt ‘TOCONbits. TMROON |jStart Tie TLCONbits.TMRION 11ST 4 py reivate sl peripheries INTCONDits.CIE 1) Globally eae interrupts while (1) 5 [1 keep looping till recognized 1 Torgle RBS TRISDbitat i © RBS SDhite-THISHG = 0 punott = OxFD 1 Load TMROM PORTC 0 i blows Port Ce eit Tnol = OOF s Loud TROL, Ponrp Make Pom Dan eu or ATCONDIIsTMROIF = 0 5 TICON = ona ; ert D an euterst pot M Clea Ti 1116 Wit er 6 bit mode, Timer 1, no prescal MRA = OFF cath ae ; : nt 1 tae TEC _ytiverl_ISR (void) TMRIL = 060 oe I TMIAL = 0:06; Lond TMRIL. pote ~ PDAs 1 Toggle Rita ; 11 Clear Timer ¥ interrupt quRiIt = Oxf! Load TMRU Dela AE Dr id TMRIL = 0x83 1 Load TMRIL teeript : q TICONbits-TMRION = 1: ATMRIITE = 0 1ON= 1; // Start Timer interrupts CO INTCONDits.GIE = 1; //Enable interropts s agam that displays a valuo of ‘Yat port C and 'N* 5 slobally weer ako gonerates a squaro wave of § KH wih while() ‘ikeep looping til interrupt £P alportpin REG. Use XTAL = 10 MHz fe is recognized. 10 MH: gus Tiner clock frequeney =") H# = 2.5 MHz PORTC =“ [isplay *Y" at Port C ; jis FORD" ‘Display *N’ at Port D qimer clock period = 35 ygHIz = 0-4 Hsec i For 5 KHz (period = 0.2 msec.) void Timerl_ISR (void) On period = 0.1 msec, off period = 0.1 msec, | | { 7 suming 50% duty cycle. ‘hogale bit RBG O.1msee _ 959 ‘oad TMRAH 0.4 usec ifload TMRIL : Count = 65536 — 250 = (65286),0 = FFO6H PIRIbits.TMRUIF Clear Timer 1 interrupt TMRIH = FFH ¥ TMRIL = 06H i een: 9.9 Programming External Hardware Interrupts microcontroller has three external Fiaclide # dene PB6 PORTBbits.RBG Timer]_ISR () ; [from erupt my_isr yi (void) ee | H@MAbits. TMRUF = =D) 1/1 Timer 1 caused i //execute Timer 1 ISR interrupt ‘The PIC18 interrupts. They are INTO, INT1 and INT2. Whenever they are invoked, the microcontroller gets interrupted. ‘The microcontroller stops the Gervent program execution and jumps to the carfor table to provide service to the interrupt. ‘The interrupts INTO, INT1 and INT2 are Jocated on pins RBO, RB1 and RB2 of port B. They are directed to vector location ‘0008H. The INTO interrupt can be enabled/disabled The TINTOIE bit of INTCON resister, NTL and INT2 interrupts can be enal cai Theabled using the E bits of the NTCONS register. : On reset the external hardware interrupts are positive ede ‘triggered interrupts. NTI, INT2 Interrupt flag bi their registers erupt | terol | Replator ] lntrupt | Realtor enable bit flag bit. 5 wD | WNTOE | TOON | INTO | INTCO (R80) itt] INTHE | INTOONS | INTHIF | INTCONS (R81) wwe] INTaIE | TOONS | INT2IF | INTCONS (R83) — Inorder to make the interrupts negative edge triggered we need to program the INTEDGx bits in the INTCON2 register. DD Dy De Dy D DD INTEDGO | INTEDG1 | INTEDG2 IINTEDGx : External Hardware Interrupt Edge Trigger Bit 0: Interrupt on negative edge 1: Interrupt on positive edge Fig. 9.9.1 : INTCON2 register — As shown in Fig. 9.9.1 bits Ds, Ds and D, hold the INTEDGO, INTEDGI, INTEDG2 bits. If bit = 0, the interrupt is negative edge triggered otherwise the interrupt is positive edge triggered. - On reset all the INTEDGx bits are 1, to indicate positive edge triggered interrupts. To make an interrupt negative edge triggered we need to make the INTEDGx bit of that interrupt low i.e. 0. - Incase of an edge triggered external interrupt, the external source has to hold the request pin high for atleast two instruction cycles and then hold it low for atleast two instruction cycles to ensure that the transition is seen so that the interrupt request flag is set. When the interrupt service routine is called, the INTxIF bits must be cleared to indicate that the interrupt is service and PIC18 microcontroller can respond to another interrupt. Assuming XTAL = 10 MHz instruction cycle time = 0.4 us = 400 ns For detecting edge triggered interrupts we need two instruction cycles high and two instruction cycles low. a 2instnection | 2instucton . Meienum pulse duration im for detecting edge = es oyeles, —— O8ps 08 ys Minimum pulse duration fordetectng edge = 4g triggered interrupts us & Write a C18 program to gonerato a sq tho froquoncy of tho signal applied at INTo one ety in Soln.: Program : F include # define PBS PORTBbi ‘void my_ist (void); void INTO_ISR(void) ; ‘#pragma interrupt my_ist void my_isr(void) : if (NTCONbits.INTOIF = =1) Hi external hardware int caused interrupt execute Tp py INTO_ISRO: } # pragma code hi-priori =0x08 ‘finterrupt location of high priority void hi_priori (void) { _asm GOTO my_isr _endasm + # pragma code void main (void) { TRISBbits.TRISBS = IPRBS= TRISBbits.TRISBO=1; ——_//INTO INTCONbits.INTOIF = 0; clear External INTCONDits.INTOIE = 15 // Enable Externe! INTCONbits.GIE = 1 ; e 1) Enable all intern B while(1) ; —// Keep looping till interron r void INTO_ISR (void) { a PBS = ~ PBS; 1) Toggle bit PS INTCONDits, INTOIF = 0; // Clear Ester 0% Ex.9.9.2 oi Write a C18 program to switch “on or “off” ee to port B.6 when extemal interrupt INT! INT1 be negative edge triggered. Y High priority interrupt location | void my_ist (void) sf QNTCONSbits INTIIF 11 extemal interrupt 1 caused Interrupt _ISR ‘Materrupt execute interruptl_ISR } : seid main (void) { /)RBO = output WRB1 ie. INTL INTCONSDits.INTIIF = 0; i clear External interrupt 1 INTCONSbits.INTHIE = 1 ; /{ Enable External interrupt 1 INTCON2bits.INTEDG1 = 0; i Make INT] negative edge triggered INTCONDits.GIE = 1; | // Enable all interrupts globally me i Keep looping till interrupt is recognized Sleep IRid) input BG = ~ PB6; 1 Tarn LED on and off | INCONSbits.INTLIF = 0; // Clear External interrupt 1. Programming the Serial Communication Interrupts me PCL8 aj . "eryeq. gy microcontroller has two interrupts Roy for serial communication TXIF and qtr (SPPU-ESTC) ° Intorrupt Structure of PIC18F ios The TXIF in the PIRL reginter in set wher data byto is transmitted tat CIP bit ie the PIRI reginter is set when a data byto is received. ~The TXIF (Transfer intorrupt) flag in wet if the last bit of framed date (ie. stop bit) in transmitted. It indicates that TKREG regiater is ready to transmit the next data byte ~The RCIF (Received Interrupt) flag in set if a byte is present in the RCREG register. RCIF is set to indicate that the byte needs to be picked up before it is lost by new arriving serial data. ~All the above concepts are applied equally with polling or interrupts. The difference arises in the manner in which the serial communication interrupts are served. ~ In the polling method, the TXIF or RCIF is monitored. We need to wait till the particular bit is set, — In the interrupt method, the microcontroller is ready to transmit or has received a byte we are notified. Any other task can also be completed while the serial ‘communication is done. - If the TXIE or RCIE bit in the PIE1 register is enabled, when the TXIF or RCIF are high the microcontroller gets interrupted. The PIC18 microcontroller the branches to memory location 0008H for executing the ISR. Table 9.10.1 : Serial Port interrupt flag bits and their when registers ‘Serial port | Enable | Register | interrupt lag | Register interrupt bit bit TXIF Te _| PIE TXIF PIRY ROI RCE | Pret RC PIRT Ex.9.10.1 Write a C18 program to take data from Port D and transfer it serially continuously. Use serial interrupt. Soln. : Progra F include void my_isr (void); void transmit_ISR(void) #progma intereu void my_ist (v0 { if (PIRIits. transmit_ISR() 5 IMigh priority interrupt ) " #progma code hi_priori = 0x08 void main( oid) { = TRISD = OxFFS [Port D = Input. ‘TRISChits.TRISC6 = 0; z //Make TX pin output pin. Enable transmit TXSTA=0n24 SPBRG = 155 JXTAL=10MHz, baud rate = 9600 RCSTAbitsSPEN = 15 //Enable serial port TXSTAbits.TXEN=1;__ //Enable transmit PIEIbits.TXIE {Enable transmit interrupt. INTCONbits.PEIE = 15 //Enable all peripheral interrupt INTCONDits.GIE = 1; //Enable all interrupts globally. i while (1); iKeep looping till interrupt is recognized. } void transmit_ISR (void) 4 TXREG = PORTD; //Send data from Port B serially to TXREG register. + Ex.9.102 Write a program that continuously read 8 bit data from port D and transmits it serially, while the incoming data from serial port is sent to port B. Let XTAL = 10 MHz and baud rate = 9600 Soin. : Program : # inclade void my_isr (voi void transmit, void my_isr (void) { if (PIRIbits. TXIF==1) Hf transmit execute trans transmit_isr( ); HIRD RCIF==1) —_// if receive interrupt, f is execute receive _isr, - receive _isr(); conte void hi_priori (void) { _osn GOTO my_isr _endasm } ‘pragma code void main(void) { ‘TRISD = Ox Nor D = 1 MPor B= uy Nt TRISC6 = 0; Wake tea vin = capa ‘TRISChits-TRISC7=1; Make receive pig Menable transmis Set baud rate = enable rene MEnable ona pore. Enable transmit PIEIbits.TXIE =1; //Enable transmit items PIElbits.RCI 3 MEnable receive i INTCONbits.PEIE ‘/fEnable all peripheral interagy INTCONbits.GIE = 1; //Clobally enable sl) interrupts while (1); } void transmit_isr(void) ft: TXREG = PORTD; —_//Send Port D rae serially } void receive_isr (void) { PORTB=RCREG; 11 Port B-Change Interrupt Bt - Ifa change is observed on any of the P25, RB7 of port B, an interrupt is genet ot interrupt is called as Port B interrupt, ¥ ~ It can be enabled and disabled by te in the INTCON register. RBIF is gi change interrupt flag bit located # register. ¥ ~ Although Port B change interrupt Pins, itis considered to be a single 3! ~ Mostly Port B change interrupt * we keyboard interfacing. ex 9-10 j Intorrupt Structure of PICIOF co cted t0 pit 9.12 s Oe ee Sr OY ont rere snterrupt Priority (A ot pango tho stato of two LEDs ee a|~ The picig 2 oe it gts. "oon | Interrupt priority levels," OMY two fae They are: ” @ Low priority interrupts : ‘These es interrupts are directd to vector loation foe Dbits.RDG ii) High tre VED) CO eRDT Gi) High priority interrupts : ‘These anne ae are directed to vector location “ portBint_ ISRO 08H, [Sst ; ~The addresses 00008H and 00018H are assigned erupt my_ist to bee (void) \t {qNTCONDits RBIF ) Hit Port B change interrupt then execute PortBint_ISR program potBlot_ISR(); : ‘ode hi_priori = 00008 cll prir (void) TRISDbits. TRISD6 | TRISDbits.TRISD7 TRISBhits.TRISB6 = 1; J/RB6 = lice. input | for interrupt | TRisbbits.TRISB7 = 1; //RB7 = 1 ice. input for interrupt | INTCoNbits.RBIF = 0; //clear RBIF flag | NConbits RBIE = 1; //Enable port B-change interrupt NNICONbits.GLE = 1; //Enable all interrupts : globally while (1; Ikeep looping till interrupt is } recognized. wi [Ba SR) Ln SPORTBhits.RB6; //-) change the state 11 | of LEDs JL) Clear RBIF interrupts to make them compatible with the earlier PIC microcontrollers. On reset all the interrupts are assigned high Priority, making it a single priority system. In order to make the system a two priority level ‘system we need to set the IPEN bit in the RCON. register. If IPEN = 1, then the interrupts can be assigned a low or high priority. On reset, IPEN = 0 i. all interrupts are assigned high priority, By programming the IP bits, we can assign low priority to any interrupt. A low priority interrupt will be directed to address 00018H. If IP bit = 0, interrupt will be assigned low priority otherwise interrupt will have a high priority. Table 9.12.1 shows the interrupt Flag Bits for the PIC18 interrupts, Table 9.12.1 : Interrupt flag bits for PICI8 and their registers Typeot | tntrupt | tterupt | tntemupt | —dnterupt Intorupt erablebit | fagbit | priority (easter) | eget) | Register Timero | tao | TwRor | TWROP Timer (NTCON) | (INTCON) | (INTCON2) Interupts | Tmert | Tuanie | Tuane | TwRUP een | ean | cpap Timer? | trae | Tura | TwRaP een | ery | cen Timers | Trae | Tura | TwRIP (ce Bema | own fw [owe [wrt ay (Pet) (piety | gNToONS) we | irae | wrar | wre aa (PIE1) (PIRI) (INTCON) xr |THE TXiF xP wt | a | eo | ore pts | ACF | ROE ROF ROP ne (PIE) (PIRI), (PRI) rant | Rae | RBF RIP pea woo | entoom | ewTooN2) change Interrupts Note: INTO 1s a singlo prior Jevol and is direct (o08H. ts priory cannot bo rod Intorupts. tion, lad to vector local fied, like othor 13 Interrupt Inside —__2n Interrupt ____—_—— — When the PIC18 microcontroller is eaeutne oA ISR in order to provide service to an int h and if another interrupt is invoked, then in fn ‘a case the newly invoked interrupt is a higl - priority interrupt and only then it can St the previously serviced low priority interrupt. is an interrupt inside interrupt or nested interrupt. - Allow priority interrupt can be interrupted by a high priority interrupt, but not by any other low priority interrupt. - All the PIC18 interrupts are latched and kept internally. This allows low priority interrupts to be serviced after the high priority interrupts are being serviced. — Ifa low priority interrupt is directed to vector location 0018H, the GIE1 bit in the INTCON register is disabled to indicate that a low priority interrupt is being serviced and all other interrupts will be blocked. After servicing the interrupt the GIEL bit is set to allow another low priority interrupts to be accepted. Ifa high priority interrupt is directed to vector location 0008H, the GIEH bit in the INTCON register is disabled to indicate that interrupt is being serviced. After servicing the interrupt the GIE bit is set to allow other interrupts, If two interrupts have the same priority then they will be serviced depending on the sequence in which program checks them i i wor ee em in the interrupt 9.14 Triggering the Int errupt by Software 7 —Pyserware It is possible to tri to trigger the ce ace, sing simple instructions that set t pts and cause the microcont, ee to the interrupt vector table wees ee 2 e interrupts. can trigger Eg. BSF INTCON, Ri " , RBIF will inte ctocontroller and force it to jump. a interrupts by Intor at math, cont Cc) Si itruction thi rollers (SPPU-EST We are using an it at ae ay norupt. 1 hao gh 7 This is ti torrupt called ay triggering of the interrupt, “hy 9.15 Interrupt Latency Definition : Interrupt Latency is defined ay & from when an interrupt is activated to thy AS microcontroller begins executing the code qj vector address 0008H or 0018H. ° = Depending on the type of intemy, instruction the interrupt lateney can jy % instruction cycles. 4 9.16 Fast Context Saving in Task Switching s_s+_wAl - In real time operating systems, the processes one task at a time and complet before it processes the next task. - The execution of a task involves the exteuin, an interrupt service routine. Also i; executing the task the access to th resources is very important as the task nee be completed efficiently and quickly. - Previously the systems had very few regia Hence, before executing a new tat & Programmers had to save the contents on the stack. This mechanism of savig$ contents of CPU before switching to a ner is called as context saving or ot switching. ‘The PIC18 microcontroller has many R5* Hence, we need not save the CPU conte? stack. ~ The PIC18 uses three registers : wasn and STATUS registers for executing @") ‘These registers are saved in shadow re, a high priority interrupt is recognize? *,y end of ISR we need to use “RETHES, instruction. This is called fast om! in task switching in PIC18 syste™ ay However, fast context saving is not interrupts with low priority. if ‘The depth of shadow registers is ‘at? or three high priority interrupts 8° Nt only the first ISR will use fast contes Interfacing of Switches, Keyboard, LED and Lcb f DIP switch erally & group 0! _ eS compris F er sr eight switches. An input port with tight are PORT B, PORT C, PORT D uses eight Fppswitehes: 40.1.1 shows the interfacing of pp ~ PS yes to PIC microcontroller. a Koy. — sw fr [+ \s ba charactor — ro Yoo = ; Fig. 10.2.1 : General operation of a keyboard wa ar] || Mwy Wo RC E o Outout PICIBFESS ac, _ Key ne [ental Vos FO? Fig. 10.2.2 : Bouncing of key switch + BDIP switches ¥ In case of a push button key, the metal contact Fi 10.1. : Interfacing 8 DIP switches to port C of PICI8F458 a Syllabus Topic : Interfacing of Keyboard Done ee Se ltis @ human oriented input peripheral. It is ‘4 to input data or program into the Sromputer. It consists of push button type niches. When a key is pressed, the microcontroller ‘ifs key depression and then performs nay te operation. “2 Key Switch Mechanism and key Debouncing te ee of this mechanism is to generate and ‘code each time a key is pressed. The ‘sm should send one and only proper code, run} MY is pressed. Fig. 10.2.1 shows the The Mtdtion of a keyboard. pubs keyboard is composed of a set of ‘Lig sh button switches. Each switch makes Re ggottact when pressed. The nature of the |W" tld be reliable, have long life and feel A bounces few times, hence the voltage across the switch fluctuates and generates spikes in the signal. Therefore, it is necessary to debounce the mechanical switches. This is called key debouncing. The key debouncing is done through hardware and software. Fig. 10.2.2 shows the bouncing of key switch. 10.2.2 Hardware Key Debouncing It is implemented by using flip-flop or latch. Fig. 10.2.3 shows a circuit diagram of hardware key debouncing. Fig. 10.2.3 : Hardware key debouncing 10-2 Interfacing of Switches, Key 4 -E8TC) [BS cocontotos (SPPU-ES. Veo : ected to A, the output nEASAS ASS AS i ‘itch is con : of ian hue gre i When the key ake oa with B, the output changes from logic © 1 in ‘The wiper bounces many times on ema Be fue output does not fluctuate between logic 1 HR. Th 0. When the wiper is not connected either to , the output of the latch remains constant. 10.2.3. Software Key Debouncing In the software technique the Fondo microcontroller waits for 20 ms before it accepts the key as an input. If after 20 ms the key is pressed the key is accepted by microcontroller. The process of software key debouncing is as shown in Fig. 10.2.4, Delay 20 ms ¥ Read keyboard ‘Accept key Fig. 10.2.4: Software key debouncing 10.3 Keyboard Interface Circ The keyboard is interfaced with microcontroller through input ports. The keyboard consists of mechanical switches. These switches are arranged in non-matrix or matrix form. 10.3.1 Non-matrix Type Keyboard = In non-matrix type keyboard, the key closure is identified by reading the port data, but it requires many port lines. The number of /O lines is equal to number of keys. Fig. 10.3.1 shows the interfacing of octal non-matrix type keyboard. ~ To identify the key value the following three functions should be performed : (1) Identifying a key closure, (2) Debouncing the key. (3) Encoding the key to an ap propri like hexadecimal. rate code fan Fe, Bg} FB + pa Fe, L je aL picter4se FB, e,| 4 FB By} aye Fig. 10.3.1 : Non matrix type keyboarg The above three functions can be through hardware as well as software. 4 ill see hardw: ice example we will see are . identification of key closure. ‘The interisg, as shown in Fig. 10.3.2. Veo Ker m3 a ‘ s 76; 8, Fe, RB, re, FB, 516 Fig. 10.3.2 : Hardware technique of identificait When all keys are open, the output of Bate (STB ) goes low. When one of the #* Pressed, the output of NAND gate G18)" high. The STB is used to identify thet ** interrupt the microcontrolle! Ex.103.41 aoe 8 simple keyboard to microcontrler PIC'® Fe) soln. Fig. P. 10.3.1 shows how a simple interfaced to PIC18 microcontroller. # S shown in Fig. P, 10.3.1 eight *.P ted to PORTB pins, Each port Pi S of key that is connected to that Pi?» conne, statu: g cones (SPPU-E&TC) =a pin shoves logic 1 then the key is open eee the key is closed. sv f z= [aiafalaiapa } Fig. P. 10.3.1 allowing Table P. 10.8.1 gives the keycodes for igs from PORTB. 10-3 Intortacing of Switches, Matrix Keyboard Interface ~ Inasimple keyboard interface one input line is ‘quired to interface one key and this increases ‘be number of keys. When a large number of keys are to be itterfaced, this technique is not useful. Matrix Sethod is used in such cases, so that the ® pier ofconnections are reduced. ie shows 16 keys arranged in 4 bel columns, No connections are there, +p Sate open, . is connection wee is pressed then there is 1 nit? corresponding rows and columns: om e acetone Pes eight lines to complete rows when Table P. 10.3.1 coal fal Keycode Key |D;| Ds | Ds | Ds | Ds [De | Ds | Do a3 oS «3 2 phil it fff fo 3 Rolf pale ft = z mliii [a fa [2 fo fa [2 s fe K fi {12 fa [2 [o }2 | [2 5. Z 3 2 w& {i [1 [1 fo [2 [1 |i jt é x x ? & li {1 fo [a [a {a [1 [2 P = wii jo fa fa fa {2 [2 [2 : & fo fa fa [a [2 2 [2 It 3 3 Fig. 10.4.2 shows the interfacing of a matrix keyboard, it requires two ports : an input port and an output port. The columns are referred t@ fas sean lines and rows are referred t0 8 return lines. sed, the yy is pre When a key is presser ro conn A and column at ve bh Ifthe output line of a r0% 5 the tine of a column high and °° ey is recognized by data is a output port and the input code ‘0 fun the input port. The steps real itentify the pressed key are j) To identify if any key is pressed oF 20 (i Toidentify if any key aw the column lines are made 2° a sending Tow on all the output lines! ie. all the keys in the Keyboar matrix are activated. (b) Read the status of rows ie. return lines. If the status of all lines is logic high, the key is not pressed. Otherwise if the status of all lines is logic low, the key is pressed. (i) Debouncing the key. (Using software debouncing as explained earlier) (ii) Identifying the pressed key. (a) Activate the keys from one column by making one column line zero. (b) Read the status of return lines. The zero on any return line indicates that key is pressed. (©) Activate the keys from next column and repeat steps (b) and (c) for all the PET Interace a 4 x 4 matrix keyboard. to PICISF4S8, Display eypressed on hyper terminal oR Draw and explain interfacing of 4°4 matix k , PICIEFXXX mierocontllr using inert Wie cous nea oR , Draw an interlacing diagram for 4°4 mati mal «spay the Koy pressed on LED, Witeaceaa, ond a4 Soin. : Fig. P. 10.4.1 shows the interfaci matrix keyboard to PICLF458, ing ofa 4x 4 Rotum ‘Unes: Sean Lines, TRY Tel orN TO uy YP, ee Ne! re @ € e€f¢ 5 P Bic ga 8 The 4 x 4 matrix keyboard is connected port B of PIC microcontroller. RBy - RB; a or return lines while pins RB; — RB, are colux return lines. For detecting the key presse ™ methods can be used. They are (@ Interrupt method Gi) Scanning method In this program we use the interrupt me detecting the key pressed. .. 6 Fig. P. 10.4.1(a) shows the flow determining the key pressed. Ground all tho rows, —— ead all columns. Yes Initialise RBIF Wait for interrupt ‘Wait for debounce —— Read all columns q Ground next row 1 Read all columns [Determine the key pressed Get scan code from table Return from interrupt Fig. P. 10.4.1(a) # pragma code # pragma imerrupt my jer void my ise (void) { if (NTCONDit.RBIF = = 1) // Is RBIF = 1? BRISK: # pragma code oid main () { TRISD 1) Make Port D an output port INTCON2bits.RBPU = 0; {WEnable PORTB pull up resistors TRISB = 0:FO; PORTB = 0xFo; while (PORTB! = OxFO) ; IF Wait until key isnot pressed ‘TXSTA = 0:20; SPBRG = 15 11 Baud rate 9600 TXSTA bits. TXEN = 1; //Enable transmit RCSTA bits. SPEN = 1; /Enable serial port INTCONbits. RBIE = 1; {f€nable PORTB interrupt on change INTCONbits. GIE = 1s enable interrupts globally while () 5 I Waitil key is pressed. } void RBIF_ISR (void) Indemnity the key pressed unsigned charx, COL = 0, ROW = 4: delay (15) ha jetermine the column nega cout = termi tS PORTH = OxFE: tem a it wonti = Oxf) is Bs Ae change yes then 0% ROW =0: che { PORTS = OxFD ; ero row 1 it (PORTB! = OxFD)// is there » nibble change ROW=1; —__Hiyesthen ow = 1 else { PORTB = OxFB) Ground row 2 if PORTB! = OxFB)//s there a nibble change Uiyes then row PORTB = OxF7; (Ground row 3 if (PORTB! = O:F7)//is there nibble change ? Row yes then row = 3 } } } if ROW <4) {is valid row found ? serial (keypad [ROW] [COL) ; (then send character while (PORTB ! = OxF0) PORTB = 0xF0; IWait for release INTCONDits.RBIF=0; —//Reset flag } void serial (unsigned char i) // send character { while (PIRI bits. TXIF! = 1); vat til ready TAREG = i; if send key pressed to ; serial port/ hyper terminal void delay (unsigned int ms) { ‘unsigned int x, y; for ( for Osx YS Delay (unsigned int) ; C main (void) put port forever PORTA = oxoo1t Delay (250) ; PORTA = OFF; Delay (250) : } , void Delay (unsigned int xtime) ( unsigned ints ‘unsigned char j 5 for (i = 0; i < atime ; i++) for G = 055 < 1653 j++) } Ex. 10.5.2 GED ESP NERS ‘An LED is connected to each pin of port D. Write a C program that will tum on each LED from pin DO to D7. Call a delay module before tuning on the next LED. pIcisFess 1 Port Ais out port® PoRTDbits.RD} porTDHits RD2 define PD2 define PDS define PDS define PDS |#define PDO |#define PDT void Delay PORTDH:t PORTDbits.RD7 nsigned int); {/PortD is ouiput port /surn on RDO Delay (250) PDI ‘tara on RDL Delay (250) ; pb2 = 1; turn on RD2 Delay (250); PD3 = 1; Jiurn on RDB Delay (250) 5 PDs umn on RDS Delay (250) Mtn on RDS Jituen on RDS Delay (250) 5 Po7=1; I turn on RD? Delay ( , , void Delay (unsigned in ti weit ely ome it ime) unsigned inti ‘unsigned char j; f= 051 < xine) fr G= 05) < 165544) OA a pce epi connactod 10 pin RCO aNd LED 10 Bin ig, a pogram to got tho status of switch and Sed tt the Way o Y 47 Ko! RCO picteF4s8 300 switch, ABs % t Ne Fig. P.105.3 Soin. : © program : F include 5 # define switch PORTChits.RCO 4 # define LED PORTBbits.RBO ‘void main (void) { 1 //Make RCO an inpt fia 0 // Make RB6 an oupatp while (1) { if (switch z LED = 15 /} Turn on LED else LED = 0; Itum off x Ex. 10.54 LEDs are connected tothe bits in PORT © and PORT. ite vel ace program that shows the count from 0 to FFH# Soin. : include #define LED PORTD void main (void) mn = 0; /fPort Cas an output pot THB, 11 Port D as an output pot | rote 1 Cleat Port C cnse 1/ Clear Port D for (3) { PORTC++; // increment port C , LED ++ 5 // increment port D } jors (SPPU-E&TC) = ‘Segment Display (SSD) . Aly ‘uses seven LEDS to make any digit, If displ ‘rps are on, it shows the digit 8, There al pos SSDS available, 1053: Structure of seven segment display (SSD) Common cathode i.e. the cathode of all the LEDs are given a8 a common pin, In this ease the anode is connected to the port pins. As ‘ready discussed in the section for LEDs, this method requires port pins to source large carrent. Common anode i.e. the anode of all the LEDs are given as a common pin. In this ease the cathode is connected to the port pins. 1055 \iite embedded C program to implement HEX counter on sertand splay the count. Soln: Title “HEX Count on LED Display” include < P18F458.h> #ietine Led_Disp PORTA @ @ ts imain(void) TRISA = 0; isp =02005 Jf declares PORTA as output // initiates count to 0 for =0x00; j Jafrfolstsfols ‘Ox6D fal ff fools O79 t-—— fol+{1{ofols]s oy = fafolrtsfotrts O58 | frfofsfafatr|s O35 7 [1[1 [4 [o[ofolo O70 ppb oF ree CR CE ox7B 1058 jie en instruction sequence to display 8 on the 4 seven trent splays shown in Fig. P, 10.5.6 == § wultiple seven segment displays to PICI8F458 through Port B and Port D Interfacing m Fig. P. 10.5.6 10-11 Intortacing of Switchos, K rd, LED & LCD. Soln. Program : __ The code for displaying 8 on the 7 segment display is Ox7FH. C program : # include void main (void) { TRISB = 0; —_//Make port B an output port TRISD = 0; // Make port D an output port PORTD = Ox7F; _//Output the segment pattern of 8 PORT = ox10 Mactivate 4, seven segment displays } Ex, 10.5.7 Write a program to display 54321 on a five seven segment display assuming that PIC18F458 is used, Soln. Fig. P. 10.5.7 shows the interfacing diagram. ‘The digits 54321 will be displayed on the five seven segment digits. The codes for displaying the digits are given in table below. Seven segment display | Displayed ciglt | Port D | Port Aight No. B 4 5 0x88 | 0x10 3 4 33 | oe 2 3 x79 | oxos 1 2 xs | oxce 0 1 0x30 | oot a Fig. P. 10.5.7 : Interfacing five se Program : F include void delay (unsigned int); char dsp (5) [2] = ({035B, 0x10}, (0333, 0x08), 0x79, 004}, {0x6D,0x02}, {0x30, 0x01}} void main (void) { intis TRISB=0; —_//Make port B an output port TRISD =0; —_ //Make Port D an output port while (1) { for (i =0;1<5;1+4) { PORTD = displ 0]; // output display ae PORTE = dispfi] [ ‘ten cea displ Delay (250) ; es! , } ra delay (unsigned int ite) “unsigned int i; wen segment displays with PICI8F458 unsigned int j ji 10-dols (U) and character font (F) 2iines 0 tine fasbe cane SAOGRAMaddess |0 0 0 1 ACG (generator RAM actress. (Ghracter generator | (ACG : CG RAM address) a cian geomet ran paca seta rman ene is erg re ote Spay Sa A ‘Set DD RAM address | 0 0 1 ‘ADD address. The display data (Geiaycaarasy | (s00:0D RAM ates) AN dam eet ad fete afer bs set 8 coe =] FAG Resta bes] ed Oe Busy Flag and oO 1 intemal operation is ‘Address dae sddross counter for CG and DD RAM address. dona and reads address [BF = 0 can accept command or instruction ‘counter contents Bf xy ira opon Wiss aia © GB & 00 Wire data to CG or DD | 1 0 write data RAM, aM Reads data trom CG or DD Read data from CGor | 1 1 read data RAM Sorat LD Tnorder to display © messnk O a a module we need to initialize the L a“ arth js initialized by writing command codes command register. _ Fuitiatization comprises of command codes for Tianng. the display, shilling | Corr evummatically after writing character, returning cursor home ete. : _ Aner the initialization wo can write data to the DD RAM or the CG RAM by issuing correct command and asserting the RAW signal low and RS signal high. The data is sent on the Port and a high to low pulse is applied on the E pin. ‘The DD RAM stores the characters in their ASCII code. The CG RAM stores the character in its internally generated character code. — Before sending the command or data it is essential to check busy flag ic. whether the LCD is ready or not. 10.6.4 Initialization of LCD ‘The following algorithm is required to initialize and write data to LCD : = Wait 1 second after power up for display to stabilize. — Initialize the LCD by giving the instruction 0x38 to the command subroutine. = Wait for 5 msec. - Issue the command 0x0F to command subroutine for display on, cursor on and cursor blinking. ~ Wait for 5 msec. — Issue the command 0x01 for clearing display to command subroutine. - Wait for 5 msec. — Issue the command 0x06 for making LCD in increment mode i.e. cursor should increment after every character is written to command subroutine. - Wait for § msec. = Issue the command 0x80 (to command subroutine), to position the cursor at 1* line 1+ character. - Issue the data character one by one giving their ASCII values using data subroutine. 10-16 Command subroutine Intorfacing of Switches, Give the instruction to the port data bus of the LCD. Connected 4 Make RS = 0’, to indicate instruction, Make R/W = ‘0’, to indicate write. - Make B=" To give ahigh-toloy, Wait for 120 usec. ¢ pulse on E pin so ag — MakeE= 0" to latch the command - Return. Data subroutine Check if LCD is ready by calling reaiy subroutine. Give the data to the port connected to the dats bus of the LCD. Make RS =‘Y’, to indicate data Make RW to indicate write Make E=‘l’ To give a hightolon Wait for 120 psec. } pulse on E pin soas Make E = ‘0’ to latch the data Return Ready subroutine for sending data or command» LCD using busy flag. 10.6.5 Interfacin, Make the busy pin (i.e. data bus bit 7) =‘, ® program the corresponding port pin of PICIS # ‘input port. Make RS: to indicate instruction. Make RAW to indic ite . ete cate read Make B= 1 Cheek ii i 0. Tei a eck if baay pin = 0’, If it is ‘1’, indicates LCD and. chee? asain make E = ‘0, then B= pin = "0", Return, busy pi . Repeat this until bo L with PICISrace Module Fig. 10.6.3 6.3 shows the 0 module wit the interfacing of a 10 Fig. 106.3 i aan 28FA58. ‘As shown 2 ae lines are connected to Pot att F458. ‘The ni teeny re pa ns Rs, 5 anc = ww voltage to adjust the contrast of the LCD. PPSSFISE Fig, 10.6.3 : Interfacing LCD module with PICISF4S8 bit bus) Ex. 106: Interface 2 line, 16 character LCD display to PICTEF458 using only one port. Write C and assembly language program to display message ‘HELLO’ on line 2 of LCD. Soin. : Fig. P. 10.6.1 shows the interfacing of a 16 character x 2 line LCD module with the PIC microcontroller. The data lines are connected to Port D of microcontroller. The control lines RS, R/W and E are driven by Port B lines RBO, RB1 and RB2. ‘The voltage at Vex pin is adjusted by potentiometer to adjust contrast of LCD. ——foser Ado] RoI 416 character «2 ne Lc Display Do Dy De. Ds, Dy Ds 05 10% Potentometer Fig. P. 10.6.1 : Interfacing 16 x 2 LCD to PICI8 Let us write program to display message “HELLO” bbeii : C Program : Iicrocontrotors (SPPU-EBTO) 10-17 Interfacing of Suitches, . 0D Vex pin is adjusted by potentiometer sep ete # include # define leddatal PORTD, # define RS PORTBDits.RBO |#define RW PORTBhits. RBI MPORTD LED pine HRS = RBO IRUW = RBL #define E PORTBbits.RB2 void main (void) { HEN = RB, ‘TRISI 11 Make port B an output port TRISD = 0; _ // Make port D an output port E=0; Delay (250) ; Ledemdl (038) ; ‘Mloitialize LCD 2 lis 5x7 matrix Delay (250) Ledemal (0x0E) ; Delay (250); Ledemd (0x01) ; Delay (250) + Leddemd (0306) ; 1 Display on, cursor on 1 Clear LED Shift curso right Delay (250) ; Ledemd (0xCO) ; MMLine 2, position 0 Delay (250) 5 Leddata (11) 5 Mdisplay lettee ‘W Delay (250) Leddata (E°) display letter ‘E” Delay (250) s Leddata (L'}; [display letter Delay (250); Leddata (L’)s 1) Display letter L Delay (250) 5 Leddata (0°) ‘Display letter O Delay (250) ; } void Ledemd (unsigned char value) //eormmand routine Delay (250) + E=0; if ‘oid Leddata (unsigned char value) //display routine Leddatal = value RS=1i ) void Delay (unsigned ( unsigned in 2 for (i= 054 # define Lata PORTD # define RS PORTBbits. REO # define RW PORTBbits.RB1 |# define EN PORTBbits. RB2 |# define BUSY PORTDbits.RD7 void main (void) E=li Delay (250) 5 E=0; t void Ledready () { ‘TRISD = OFF ; RS=0; 1s do. E=1; Delay (250) ; void delay (unsigned int time) unsigned int x, y ; for (& = 0; < itime sx +4) { 1/ Make Port B an output port 1/Make port Dan output port E=0: HE=0 Delay (250) ; Ledcommand (0x38); Mnitialize LCD 2 tines, 5X7 matrix Delay (250) 5 Ledeommand (0x08); {/display on, cursor on Ledready () 5 Iieheck the busy flag Ledcommand (0x01); ffcleardieplay Ledready ()s Hicheck the busy flag Ledcommand (0306) ; /fsift cursor right Ledready ()s check the busy flag Ledeommand (0x80); [line 1, position 0 Ledready () 5 Laisplay (8) 5 Display *M° Ledready () 3 1 Cheek the busy flag splay (1) 5 MW Display ‘T Lodeady () 5 I Check the busy flag Laisplay (C2); 11 Display ‘C? Ledready () 5 I! Check the busy flag Laisplay (R°) 11 Display R° Ledready () 5 i. Check the busy flag ) ORO: < 165 y 44); bug Ha Se Ex. 10. oa and explain the interfacing of LCD with Port D and Pot Of PICIBF x00 microcontroller. Write © code to dP “WELCOME. Soin. : oO TOT Ee L (SPPU-ELT( (ee shows fe wat) Intertacng of 1 interfa Te Fg line LCD module with vp or? ie si with the : 4p The data lines are connected ty Pa, Uedatn i ; : er, The control lines RS, peta (25 eae seromasrlier. The control lines RS, BA a od eipren oy Port E lines RED, REL and ty nai Iisplay eter‘ eases # Ven pin is adjusted by potentiometer eee of LOD. Me paddat i M Display letter © pepenomrast Delay (250) ; a Leddata (0°) ‘MDixplay letter O Delay (256) ; Leddata (') Misplay letter M Detay (24) ; Leddata (22) MDisplay letter E Delay (250) ; ) void Ledemd (unsigned char value) /Noommand routine| i 101 Pesnctoratan Delay (250) ; Fig. P. 10.6.3 : Interfacing 16 x2 LCD to PICI8 : E=0; Program void Leddata (unsigned char value) //display routine : 5 { Finclade SS this f dee loddatal PORTD 1 PORTD LCD pins ree value 5 bien PS PORTEbits. RED ae [fiiiee RW PORTEbits.REL E=k define E PORTEhits REZ Delay (250) ; | w0id main (void) E=0; } { } TRISB=0; —_// Make port B an output port void Delay (unsigned int time) 1) Make port D an output port Lederad (0238) 5 // Initialize LCD 2 lines, 5A matrix Delay (250) + Lcdemd (Ox0E) 5 // Display on, cursor on Delay (250); Draw and explain the interfacing of LCD with port D and port ULotemd (0:01) 5 W Clees UCD E of PICIAXXXL microcontroller without Busy flag. Write C Delay (250) 5 . to display ‘S.P.P.U Pune’. Ledberad (0x06) + I Shift cursor right am Me, P. 10.64 shows the interfacing ota Delay (250) 3 p ‘tion 0 16 character x 2 line LOD module with the PIC Ledemd (0/00) + Mine 2, posi it crocontroller. The data lines are connected Delay (250) + Leddata (W") + Jay letter “W i am. D of microcontroller, The conteol Tinet RS, ww and B are driven by Port F Tho voltage at Ve pin ix ad to adjust contrast of LOD. on REO, RET and REZ, jjunted by potentiom olor een WO BS} Gores nos i ennai 2oe fos fe is no re SA re oe ee LE rete t rea] Veo + el o_Mes ry J ‘ta Porton Fig. P. 10.6.4 : Interfacing 16 x 2 LCD to PICI8 © Program : [# include # define leddatal PORTD }# define RS PORTEDits,REO J PORTD LCD pins URS = REO #define RW PORTEDits.REL #define E PORTEDits. REZ void main (void) { ‘TRISB 1) Make port B an outpat port ‘TRISD 11 Make port Dan output port Delay (250); Leader (0x38) 5 I witilize LCD 2 lines, 47 mateix Delay (250) ; Ledemad (Ox0E) ; I Display on, eursor on Delay (250); Ledemd (0x01) 5 Clear LED Delay (250) ; Ledema (0x06) ; 11 Shift cursor right Delay (250) ; Ledemd (0xCO) ; Mline 2, position 0 Delay (250): Veddata (Sj Misplay letter‘? Delay (250) Ledidata ‘Méisplay lester? Delay (250) 5 Leddata (Ps display liter‘? Delay (250): Leddata (4) Delay (250 Leadata CP) Delay (250) + Lala Delay (250) 5 Lesddata (U') Delay (250) 5 Leddata (*) Delay (250) 5 | Veddata CP) Misplay ever | Delay (250) § | | MDisplay letter ys MDisplay Leddata (U') ‘Display Veter yy Delay (250) + Leddata (N') Delay (250) Leddata CE?) Delay (250) 5 } void Ledema (unsig { Leddata = value; Rs Display letter Ne Display leer E? cchar value) //eommand rote] Delay (250) ; E=0; Delay (250) ; E=0; } void Delay (unsigned int itime) ; ¥ (unsigned int itime) x 2 LeD with PIC i “Play the “My College’ message ode, Microcontroller to 8 bitintertace m a bd (Brlnocmctee sPPU-EATC) 1021 Intetacing of Switches, Keyboard, LED & LCD an Leddata (M0) Tisplay leter Pp, 10.6.6 shows the interfacing of a x 2 line LCD module with the PIC actor " enrol. ‘Tho data lines are connected to Port snore microcontroller. The control lines RS, RW » a8 ‘aro driven by Port E lines REO, RE1 and RE2. oe voltage at Vex pin is adjusted by potentiometer roadjust contrast of LCD, ‘Weharacter» Zine Leo Display Fig. P. 10.6.5 : Interfacing 16 x 2 LCD to PICIS Program : I# include if define Ieddatal PORTD |# define RS PORTEbits.REO deine RW PORTEbits. REL tine E PORTEbits. RE2 void main (void) // PORTD LCD pins HRS = REO JIRW = REL WEN = RE2 // Make port B an output port // Make port D an output port Delay (250) ; Ledema (0138) 5 / Initialize LCD 2 lines, 5x7 matrix Delay (250) ; {edemd (0308) ; 1) Display on, cursor on Delay (250); Vedemd (0x01); Clear LCD Delay (250); Ledema (0:06); J) Shift cursor right Delay (250) ledemd(OxCO); Line 2, position 0 Delay (250) ; Delay (250) Leddata (*y display leery? Delay (250) ; Leddata (C’}; Misplay Wetter "C? Delay (250); Leddata (*07; MDisplay letter ‘o? Delay (250) ; Leddata (‘') MDisplay letter T Delay (250) 5 Leddata (‘’) Misplay letter T Delay (250) ; | Leddata (‘e’) {Display letter ‘e” | Delay (250) ; Leddata (g') Misplay ‘g? | Delay (250) ; Leddata (') [Misplay letter ‘e? Delay (250) ; } void Ledemd (unsigned char value) //command routine { Leddata = value; RS= Delay (250) ; E=0; } void Leddats (unsigned char value) //display routine { Leddata = value ; RS=1; Delay (250) ; E=0; } void Delay (unsigned int itime) as a camrente nay nr oh Design a hennnny 7 fret thaghay oatra 9 UOD) Wn on anon from 0G 9 aa Cn nn ry. sen 8 He arcu, isn engdaia enya owcian- Soin. + im 7 ii Lt Fig. P. 10.6.6 : Interfacing diagram for frequency coanter with display on LCD AA wecond delay can delay of 100 mave, 10 times. ated by executing Program Minchide signed int i= 0, thavertlom_ent ; signee art bn, frequency 5 MSefine VAatn POKED M define KS PORT Bhits AAO M define RY PORT Hbit A M pragma coe i ni high interrspt void A pragyns cre om_veetr = Or Mom priority { sm goinlow 150 plasm , void high ISR (void) 11 1SR of high peony interrupt 7 t if (PURAbits THRE) { PIRIbiteTMRLUIF = 05 // clear the Tee 1 interop fag Uorerflow_entt+ 5 increment Timer | roll over count ) U # prapina cone propane interrupt low ISR ISR of tow pity | : intern void low ISR (void) " i fe ‘WRewurn if not Times 0 inte , vam ae, be clay (char value) 5 ready ; 7 I fanction to check if LCD fi busy or ready. TRISD = Opp, =0; 1 Por D = input por jors (SPPU-EATC) { Reo: for (i= O16 2555 4) 5 Beli J while (busy = = 1) TRISD = 05 feid Ledeommand (unsigned chard) //eommand routine t RW =0;" B=]; i 2551+); yi Joid Leddata (unsigned char x) // data routine ready () 5 Ldata A write data on port D I) 0;i< 25,1 ++) {id main (void) if char (0_count, temp, templ 5 0; i< 500051 ++) M1 wait for sometime for LCD to stabilize on power up Ledcommand (0x38) + dfissue command to 16 x2 LCD, 5x7 matrix. for ize 10-23 for O;i< 25,5 ++)5 1 wait for sometime PORTD 2 using software delay Leddata ( 1/ Display the thousands digit Ledeommand (0x0E) ; _//display on, cursor 0” y= templ and OxF0 5 fl a ve shia for (= 0,1< 25 i ++) 5 // wait for sometime y>>ds sialon using software delay = yl0x30; ; heels Sct, Ledcommand (0x01) ;_// clear display Leddata (2) ; 1! display the hundreds digi Intortacing of Switchos, K J, LED & LCD Ijwait for sometime software delay { curvor right 11 wat for sometime using software delay Ledcommand (0x06) ; {Hs for i = O,1< 2551 +4); Ledeommand (0x80); // Tine position 0 for (i =O; i< 2551 +4) 1/ wait for sometime using software delay} ize Timer 1 overflow count to 0 initialize frequency to 0. itialize Timer 1 10 0 0 tar Timer 1 interrupt flag =15 I Enable priority interrupt IPRIbits.TMRUIP = 1; Set Timer 1 interrupt to hil PIEbits:TMRUE = 15 // Enable Ti over interrupt 11 Enable Timer 1 with TICK ‘and prescaler 1 J/Enable global and peripheral interrupts 1! Create one second delay and ‘wait for interrupt INTCONDits.GIE = 0; // Disable global interrupts. temp=TMRIL; —_// save frequency low byte_ frequency = tloverflow_count * 65536 + TMRIH 1+ 256 + temp 5 /! eompute frequency Ledcommand (0x80); temp = TMRII ; unsigned char xl, y,2 5 x1 = templ & OxOF ; = x1 0x30; TICOI 0x83 ; INTCON = 0x0 5 delay (10) 5 Uf mask upper 4 bits make it ASCIL bits rmask upper fo xt [08305 Make it ASCH ie td) display the tens Veen (GTO, Mask bower 4 is yoo paki itt lower 4 bits 1531030 frostet SC Tass display the units dil a7 say single space Leddata (*") + I) display i Leddata CH"); 17, display unit of frequency Leddata (ZI! while (1) ) void delay (char value) : Ii delay of 100ms is executed 10 ties toget I second delay 11 Enable Timer 0 to set instruction clock, set presealerto 16. for (j = 03i< value si ++) 411 Put 15535 in Timer 0 high byte and low Wf byte so that it wil roll over in £50000 clock cycles TMROH = 0x3C TMROL = OxAF INTCONbits.TMROIF = + If Clear TMROIF flag, while (1 (INTCONbits.TMROIF)) ; 1/ wait till Timer 0 rolls over } Return ; D Fig. P. 10.6.7(a) + Interfacing ay | ro oa oa Ds os ii li Wheto ‘The output of ASCX30AN is 0.15 Vipsi fora voltage range from 2.06V to 2.36V. This range is small. Hence, we need a level shifting and scaling circuit as shown in Fig. P. 10,6.7(a) to cover the Voltage range from 0 to +5V. The offset adjustment is done with a potentiometer to 0.25V. Barometst Pressure is from 948 to 1083.8 mbar. Inorder to fa! the barometri as result by 7530 Pressure we need to divide oR x. 10.6.7 EEE Design of DAS system for pressure monitoring system (use ‘any suitable sensor). Soin. :ASCX30AN is a 0-30 psi pressure transducer. Ly Tw Extomal Vy Voyr GND NIC NIC ottsat adjust Fig, P. 10.6.7: ASCX30AN pin diagram Barometric pressure = gqg 4 A/D result 7.53 = 4g 4 AD result 100 Algorithm ; * 753 Main Program StepT : Init, z + Initialize step, Pers. Port B and port D as outPt + Initial Step IM; Wait, nize the Lep, Power un pe™® Software delay alte! Step IV Initinns” "* display tone eee, imtrvcog "* LCD by giving 08 e subrouting, —& ne asd som wD rollers (SPPU-E&TC) = Wait for some software delay, + fesuo the command Ox0B to co Tubroutine for display on, cursor on at : Wait for small software delay. see Vir; Cheek the LOD busy flag. the command 0x01 for clearin, display to command subroutine, ; Wait for small software delay. ers yheck the LCD busy flag, i issue the command 0x06 for shifting cursor right to command subroutine. sgep XI: Wait for small software delay. Sep XIV : Cheek the LOD busy flag. SepXV + Issue the command 0x80 to position cursor at line 1, position 1 using command subroutine. step XVI : Wait for small software delay. sepXVII : Check the LCD busy flag. siep XVII: Issue 0x81 to ADCONO to turn on ADC. step XIX : Issue 0xC5 to ADCON1. siep XX: Issue start of conversion. Siep XXI : Wait for end of conversion ie. DONE bit = 1. It indicates that ADC has completed conversion. StepXMII: Save the result in ADRESL and ADRESH registers. Step XXIII : Divide the ADC output by 7.53 to get barometric pressure. StepXXIV:Send ADC output to port D for displaying it on LCD. Step XXV: Calculate the digits and display it on LoD. Step XXVI : Also display unit of pressure (mbar). ®) Command subroutine : Sep: Give the instruction to port D connected to data bus of LCD. Sep: Make RS = 0' for command. Sep i : Make R/W = ‘0’ to indicate write. SepIV : Make B= ‘I’ + Wait for 120 sec High-to-low pulse on E pin to latch the command. © Dy, Bp Display subroutine : Step + Check if LCD is ready by calling ready subroutine. Give data to port D, connected to data bus of LCD. 10-25 Interfacing of Switches, Keyboard, LED & LCD Step TIT : Make RS ='T'to indicate data. oy + Make R/W ='0' to indicate write. tepV : MakeE Step VI : Wait for 120 usce | High-to-low pulse Step VII: Make Step VIII: Return, ‘0 on E pin to latch the data @) Ready subroutine : StepI_ : Make RD7=1. Step II: Make RS ='0’ to indicate instruction. Step I : Make W/W Step IV 'T to indicate read. Step V Step VI: Check if busy pin = ‘0. If it is ‘I’ it indicates that LCD is busy, hence again make E = ‘0’ then E = ‘I’ and check busy pin. Repeat this till busy pin=0, Step VII : Return. Program : [Hinchide unsigned int i= 0; |#aefine Ldata PORTD #define RS PORTBbits.RBO #define RW PORTBbits.RB1 #define E PORTBbits.RB2 define temp PORTAbits.RAO define Vref PORTAbits.RAS #define busy PORTDbits.RD7 void ready () function to check if LCD is busy or ready { RISD = OsFF ; 11 Port D = input port RS=0; RW=1; do 11 wait for busy flag i i<25sit4); } while (busy = = 1)s ‘TRISD = 0; J Void Ledcommand (unsigned char value) { Lata = value RS=03 ) id Ledisplay (unsigned char d) /veite data on port D s0 that itis given to LCD for displaying B=; for i = 055 <255544)5 E=0; ) void main () { unsigned char ADC_output, Lo_bytey i_byte , output, for 055 < 5000;i++) 5 wait for sometime for LCD| to stabilize on power up. Ifissue command to initialize 16% 2 LCD, 2 lines, WSXT matrix 1<25;it+); Ledcommand (0x38) for Iiwat for sometime using software delay Ledcommand (0r0E) ; 1/ display on, eursor on for (i= 035 <25 +); IIwait for sometime| using software delay Ledready () 5 Ledeorrmand(0x01) for i Jiclear display O;i<25;i++); — fwaitfor sometime] using software delay Ledrealy () 5 Ledeommand (0306) for i= 055 < 255544) 5 Ledready (): Ledenmmand (0x00) A shift cursor right 1] wait for sometime for (i= 051 < 255% If wait for sometime using sofware delay] Ledeeady () 5 TRISD = 0 TRISAbi make port D un output port i ADCONO = 0x81; //Channel 9, ae ADCONI = OxC5 5 Ge jt, while (1) { = 051 <255i++); s [fwait for sometime using softwar start conven while (ADCONODits.DONE = = 1); 11 wait for end of conve I save low be Hi_byte Ht save high bye | ‘ADC_output = Lo_byte| High byte ; output = 948 + (ADC_output * 100) /73 ; for (i PORTD = outputs ‘| Leddisplay (output/100) ; i Leddisplay ((output %100)/10); | 1! Display_| Leddisplay (output % 10) : the | Leddisplay (“m") ; presue | count Leddisplay (“b”) 5 Leddisplay (“a” Leddisplay ("2") ; Ledeommand (0x80) ; } I The pressure is in mbar } & 1060 ETERS OSA esign a PICIE based ition system temeratra measurement weing Lane using LM35, Write correspond Soin. HM © display the temperature on LOD. ‘The LM35 oper = 55°C to+ 19s nates Over a temperature range degree centigrade tt €n output of 10 mV for output will be 80 x 19%, {* 80°C temperature erunse 0 = 800 mv. Soa! SS) =e Fig. P. 10.6.8 : Block a data acquisition syste™ Gingra used for um of or temperature Measure! ment ~The A/D converter -TRISAO = 1 ; // Make RAO an input p : ot ; revolution ‘and maxi Cl8F458 ig of 10 bit = 20 = 1024 Stopa we na 10 mV output, FOr each weer OE °C Legs give ‘RR, srolors (SPPU-E&TC) 1027 j Forastep zo of 10™V, = Jntorlacing of Switches. Keyboard, LED & LCD Ve * 10 mV x 1024 steps = 10240 my Meroe Vn [Number ef] 10 bit AD | Reel temperature In = 10.24V (17) ope te] ouput | Hoary AD tpt spoever this much voltage is not acceptable, 5 2s s Tra top szo of 2.5 mV is selected, 50 | 20 [occooroio0 | cconooo101 Vou = 25mV x 1024 10__| 100 | 40 [o0ooro1000 | onco001010 Va, = 2560 mV = 2.56V 20 | 200 | 60 [ocoro10000 | ccooot0r00 80 300 {| 120 [0001111000 — (10mV con001 1110 ‘The binary output of the ADC is ae ae 4) oes Facil seu 88 cororeonon | coo voTon ie. 4 times the real temperature. We select a 500 | 200 |corro01000| —_coeor10010 | Ver= 2.56 V- | 60 [240 [ootrr10000] _oovott1100 _ The real temperature can be got by dividing the 70 | 700 | 280 | or00011000| 0001000110 AND output by 4. 20 800 | 320 _|.otor000000| 001010000 Fig, P. 10.6.8(a) shows the interfacing diagram 20 { 900 | 260 | otort01000 | oooror1010 of PICISF458 with LM35 temperature sensor. 100 | 1000 | 400 | orta0tc000| ooot100100 ov 110 1100 | 440__|.0110111000 0001101110 ‘20 | rao | 480 _[orr1100000] "_oort11000 “0 | re00 | 520 | 1000001000 |" oor0000010 “40 | 1400-{ 560 | 1000110000 | _oor001%00 150 [1500] 600 | 1001011000 | ootoot0110 Algorithm : (A) Main Program: StepI + Initialize port B and port D as output ports. StepII : _ Initialize the LCD. Step : Wait for some software delay after power up for display to stabilize. Step IV 2 Initialize the LCD by giving Fig. P, 10,6,8(a) : Interfacing diagram of PICISF458 ne ene comune based data acquisition system for measurement of routine. temperature StepV Wait for some software delay. ~ The LM336 zener diode is used for maintaining | Step VI: Issue the command Ox0E to Vne= 2.56 V and to overcome the fluctuations in command subroutine for display power supply. on, cursor on. ~ Table P, 10.628 gives the 10 bit output values for | Step VIE: Wait for smal software delay. ADC and the temperature with Vig = 2.56 V- Step VIII: Check the LCD busy flag. Step IX : Issue the command 0x01 for Table P. 10.68 clearing display to command Fi ca apRTaS subroutine pore ns | Yi nario ee "Say ND oust || StepX + Wait for small software delay. (0%) steps oe 4 StepXI + Check the LCD busy flag. 0 © | }ee00000000 | 0000000000 StepXII : Issue the command 0x06 for 10 | 4 | 0000000100 | __0000000001 2 20 8 0000001000 0000000010 shifting cursor right to command subroutine. Step XXIV : Step XXV Step XXVI : Cheek the LOD buy Na the 4 a the command 0x80 to ‘on cursor at line 1, position 1 using command subroutine. Wait for small software delay. Check the LCD busy flag. Issue 0x81 to ADCONO to turn on ADC. Issue 0xC5 to ADCON1. Issue start of conversion. Wait for end of conversion i.e. DONE bit = 1. It indicates that ‘ADC has completed conversion. Save the result in ADRESL and ADRESH registers. Divide the ADC output by 4 to get real temperature ic. @ right shift ADRESL by 2bits (i) rotate ADRESH 2 bits Gi) OR ADRESH with ADRESL to get 8 bit temperature output Send ADC output to port D for displaying it on LCD. Calculate the digits and display iton LOD. Also display unit of temperature (°C). (B) Command subroutine: Step I Step IT Step I Step IV Step V Step VI Step VI Give the instruction to port D connected to data bus of LCD, Make RS = ‘0’ for command, Make R/W ='0' to indicate write. Make E = Wait for 120 sec) Make E =‘0' Return. High-to- low pulse on E pin to latch the command, (©) Display subroutine : Step I Step Check if LOD is ready by cal ready subroutine. Give data to port D, connected to data bus of LOD. Step V a‘ step VI Wait for 120 psec Highton, Step VII Make E =‘ Pulse opp Step VIN: Return. Pinto late the data (D) Ready subroutine: StepI. : Make RD7=1. Step: Make RS = ‘0 to indi ey instruction. a Step : Make R/W='‘I'to indicate reaq StepIV : MakeE=1. StepV : Make E=0. StepVI : Check if busy pin = ‘0’ If itis? it indicates that LCD is buy, hence again make E = ‘the, E = ‘T’ and check busy pa Repeat this till busy pin = 0. Step VIL Return, lunsigned int i = 0; H#define Ldata PORTD }#define RS PORTBbits.RBO |#define RW PORTBbits.RBL }#define E PORTBbits.RB2 #define busy PORTDbits. RD7 3 pt ready () // function to check if LCD is busy or reat (sPPU-EBTC) 10-29 it 4)5 D biden () HK unsigned char ADC_output, Lo_byte, Hi_byte = for (i= 0:1 < 5000;i++)5 Jhwait for sometime for LCD to stabilize on power up-| Ledcommand (0x38) ; iJissve command to initialize 16 x 2iines, 5 x 7 matrix <25:i+4); Jiwait for sometime using software delay| Ledcommand (0x0E) 1] display on, cursor on for @= 031 < 253144): ‘{/ -wait for sometime using software delay Ledready () 5 ‘Ledoommand(0x01) for (i= 031 < 253144): 2 LeD,| for (i= 0; ifclear display 1] wait for sometime using software delay} Ledready ()3 Ledeommand (0306) + 1 shift cursor right for (|= 0 31 < 25 i++) 5 /! walt for sometime Ledready () 5 Ledcommand (0x80); _// issue the command 10 position the caror on the firs position of line 2 for (= 051< 25;i+4)5 7 wait for sometime using sofware delay bs Interfacing of Switches, mit 1d, LED & THIS se =O; Tnate pt avcaa TRISAbits.TRISAO = 1; // Make RAD en + RAS TRISADits-TRISAS 1 for V,, input f ADCONO = 0361 ; 1!Chanwel 0, ADC on. Z| f U-Gateh jusifed, ANO ADCON1 = 0x€5 = analog input, AN3 while (1) i for (i= 051 <255i++)5 J)wait for sometime using software delay| ADCONObits.GO = 1 start conversion ‘while (ADCONObits. DONE ys J] wait for end of conversion ADRESL_ Ii save low byte U/ save high byte 2; if shiftright by ) 10bit ADC 12 bits oupatis Iimask 2 uppe| cidedby 4 A bits to obtain real Hi_pyte << =6; //shift times [ temperature | iito the left { Hi_byte & = 0xC0 ; // mask the | I lower 6 bits i ADC_output = Lo_byte| High byte 5 i PORTD = ADC_output 5 Leddisplay (ADC_output/100) ; Display the 1 Leddisplay ((ADC_output%e100)/10) ; (temperature count Leddisplay (ADC_output % 10) + 1 Leddisplay (“°") 5 Leddisplay (C); The temperature is in °C Ledcommand (0x80} ; d as ae Ex. 10.6.9 EELS Write a program for interfacing button, LED, relay & buzzer as follows: ‘A. On pressing buttont relay and buzzer Is tumed ON and LED's start chasing rom ff to right a On pressing button? relay and buzzer is tamed OFF and LED start chasing from right t0 let. Lepo LED) tebe LEDS [LEDS LEDS LEDS LEDT Fig. P. 10.6.9 : Interfacing button, LED: Fig. P. 10.6.9 shows the interfacing of a buzzer, relay, button and LEDs to PIC18F458 microcontroller. The buzzer is connected to pin RBO. The relay is connected to pin RBI. For energizing the relay ULN2803 driver is used. Two buttons are connected to pins RCO and RCL. Eight LEDs are connected to Port D pins RDO to RD7. Program : [# include # define buzzer PORTBbits.RBO # define relay PORTBDits. RBI |# define button! PORTCbits.RCO # define button2 PORTChits.RC1 # define LEDS PORTDbits.RD4 # define LEDS PORTDbits. RDS |# define LEDG PORTDhits.DG # define LEDT PORTDbits.RD7 roid delay (unsigned int); void main (void). { ‘TRISChits-TRISCO + I/Make RCO= 1 jo. an input pi ee PIC1OF ASB ‘TRISChit TRISB = 0; TRISD = while (1) { if (button) { relay buzzer = 1; LEDO = 1; delay (10) 5 LEDI = 1; delay (10) 5 LED2 = 1; delay (10) ; LEDS = 1; delay (10) ; LED = 1; delay (10) ; LEDS = 1; delay (10) ; LED = 1; delay (10) LeD7 = TRISC] = 1; //Make RCL =1 pos uinza03 | FRY lution 1 lnos.=— Oe RO? i Button 2 ret }> \s, relay and buzzer to PICISF458 i.e. an input pin | // Make port B an output por // Make port C an output pat 11 Turn on Relay W Turn on buzzer | 1) Turn on LEDs from to right i.e, LEDO to LE # Tarn on LED)

You might also like