Home

mikroElektronika PIC Microcontrollers PIC16 Specifications

image

Contents

1. Address Name Bit Bits Bit Bit Bits Bitz Bit Bito ENX m Indirect register Timer TO Register en ra Least Significant Byte of Program Counter 03M status IRP RP RO TO PD z oc C 04h FSR Indirect Data Memory Address Pointer on roms mr me me Rm me mu RM RAO 06h PORTS RB7 RB6 RBS RB4 RB3 RB2 RB RBO RCO RDO on porte RE RE RE REO oah PCLATH Upper 5 bits of Program Counter 0Bh INTCON GIE PEE Toe INTE RBE TOF INTF RBIF och PR ADF RCF TXF SSPIF CCP1F TMR2IF TMRAIF ooh Pir osr Carr ctr eer BCUF ULPWUF CCP2F QEh TMR1L Least Significant Byte of the 16 bit Timer TMRO Most Significant Byte of the 16 bit Timer TMRO 11h TMR2 Timer T2 Register synchronous Serial Port Receive Buffer Transmit Register Capture ComparePWM Register 1 Low Byte LSB OEA TT ia Local 1 High Byte L5B EUSART Transmit Data Register EUSART Receive Data Register Capture Compare PWM Register 1 Low Byte LSB Le corran Mas ULM PWM Register 1 High Byte Zr A D Result Register High Byte Table 1 3 SFR Bank 0 http www mikroe com en books picmcubook ch1 11 of 14 5 3 2009 11 31 25 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview SFHs bank 1 om mor mdrewRegser O OOOO
2. A Register TSR SYNC 1 x 0 0 o Bron xfa anie 1 os Fig 6 3 EUSART Asynchronous Transmitter In order to enable data transmission via EUSART module it is necessary to configure it to operate as a transmitter In other words it is necessary to define the state of the following bits TXEN 1 EUSART transmitter is enabled by setting this bit of the TXSTA register SYNC 0 EUSART is configured to operate in asynchronous mode by clearing this bit of the TXSTA register and http www mikroe com en books picmcubook ch6 2 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules SPEN 1 By setting this bit of the RCSTA register EUSART is enabled and the TX CK pin is automatically configured as output If this bit is simultaneously used for some analog function it must be disabled by clearing the corresponding bit of the ANSEL register The central part of the EUSART transmitter is the shift register TSR which is not directly accessible by the user In order to start transmission the module must be enabled by setting the TXEN bit of the TXSTA register Data to be sent should be written to the TXREG register which will cause the following sequence of events e Byte will be immediately transferred to the shift register TSR e TXREG register remains empty which is indicated by setting flag bit TXIF of the PIR1 register If the TXIE bit o
3. 2400 2404 0 16 207 9600 9615 0 16 129 9600 0 00 119 9600 0 00 71 9615 0 16 51 10417 10417 0 00 119 110378 0 37 110 10473 0 53 65 10417 0 00 47 19 2k 19 23k 0 16 64 192 0 00 59 19 2k 0 00 35 19231 0 16 25 57 6k 56 82k 1 36 21 57 6k 0 00 19 57 6k 0 00 11 55556 3 55 8 115 2k 113 64k 1 36 10 115 2k 0 00 9 115 2k 0 00 5 SYNC 0 BRGH 1 BRG16 0 Fosc 4 MHz Fosc 3 6664 MHz Fosc 2 MHz Fosc 1 MHz dev cpi Actual Error SUEDE Actual Error SIMILE Actual Error SER Actual Error aoe si value Value E value T value Rate Ho Rate lo Rate Ho dec dec ec 300 1200 1202 0 16 2400 2404 0 16 9600 9615 0 16 10417 1041 7 0 00 19 2k 19 23k 0 16 97 6k 115 2K is Actual Error rd Actual Tr Actual Error i Actual Error ir Rate o Rate t Hate Yo Hate b dec C dec dec 299 9 0 02 1666 1199 0 08 416 2404 016 207 9615 0 16 51 10417 0 00 AT 19 23k 0 16 25 55556 3 55 8 http www mikroe com en books picmcubook ch6 10 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules Fosc 4 MHz Actual Error O Baud Rate Rate 300 1200 2400 9600 10417 19 2k 97 6k 115 2k Baud Rate Rate 300 aF os 0 0 00 Value dec Actual Error SPBRG Value dec SYNC 0 BRGH 1 SYNC 0 BRGH 0 BRG16 1 Fosc 3 6864 MHz S
4. EOI Ai C PORD TO Plava Leop First tone OO 0x05 aS USOS Dana DE Dp OEE Loop Second tone 05 307 OOS 0x03 DS UBB Osc USAS cor IE A A A ES IS ES US E A E A A TE TAS E E E Ua US TAU a END Macro beep Bl EP IN DCE Deir Der bsf DEE Der mov lw movwt Io cus Der ENDM MACRO Ser DEE mov lw movwt movlw movwt cali ENDM BEEE MACRO O Oe qua am EEO PEI STATUS OXIDE UIS c IS RUSO STATUS STATUS Siete ee ales IO E OPTTON REG S TATUS REO STATUS REI REO RET TMRO prescaler rate 1 250 OF Miele EEEO O E alien STATU FERO DOTEA TUS REI freq Beep_TEMP1 duration Beep_TEMP2 BEEPsulb capto LM SEI Ed d E ELM EM EM M d MM C D ME MN DM EM M P M M M I M EE s Subroutines BEBE SD elas Toe e ber BEEPa DEE BEEPb SUE Gatki Per Gaal lone 15 Ss Gore decfsz goro EIE return TMRO s Counter Initialization TECON C ROTE a OE TECON AE TOTE Clears IMRO Overflow Flag IS Sp Eds B Wait pecu one nS IN GU BEE TOKO IIE B Wait Bose zero OP ls sche alioval JENSEITS TOTE Check TMRO Overflow Flag BEEPD skip next if set Beep_TEMP2 f Is Beep_TEMP2 0 Go to BEEPa again Ne Ne Ne Ne Ne http www mikroe com en books picmcubook appb 46 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples B Wait movf Beep TEMPI w movwf Beep TEMP3 B Waita decfsz Beep TEMP3 f GOLO Ec Waltr
5. In order to avoid any error which may occur on Brown out reset the PIC 16F887 has built in defense mechanism It is a simple OO but effective circuit which reacts every time the voltage power WCC MC U supply drops below 4V and holds that level for more than 100 micro seconds In that case this circuit generates reset signal and since that moment the whole microcontroller operates as if it has just been switched on R1 _ AA Fig 8 23 Master Clear Pin 1K or more MCLR C1 0 1uF no danger GND Previous Chapter Table of Contents Next Chapter http www mikroe com en books picmcubook ch8 15 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set TOC Introduction Ch 1 Ct 2 Ens Ch 4 Ch 5 Ch 6 Ch 7 Chime Ch 9 App A App B App C Chapter 9 Instruction Set It has been already mentioned that microcontrollers differs from other integrated circuits Most of them are ready for installation into the target device just as they are this is not the case with the microcontrollers In order that the microcontroller may operate it needs precise instructions on what to do In other words a program that the microcontroller should execute must be written and loaded into the microcontroller This chapter covers the commands which the microcontroller understands The instruction set for the 16FXX includes 35 instructions in total Such a sm
6. Increment f by 1 f gt f Decrement f by 1 f 1 gt f Rotate left f through CARRY bit Rotate right f through CARRY bit Complement f f gt d Bit oriented Instructions Clear bit b in f 0 gt f b Clear bit b in f 1 gt f b Program Control Instructions Test bit b of f Skip the following instruction if Skip If f b 0 clear Test bit b of f Skip the following instruction if Skip if f b 1 set Decrement f Skip the following instruction if clear Increment f Skip the following instruction if set f 1 gt d skip if Z 1 f 1 gt d skip if Z 0 Go to address k gt PC Call subroutine PC gt TOS k gt PC Return from subroutine TOS gt PC S with constant in k gt W TOS gt PC http www mikroe com en books picmcubook ch9 2 of 35 5 3 2009 11 35 12 AM Ma NA EZ DC Z O NN N N C EA o UA E LEE EC A E C E E NI NNN m et ut rea D prn mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set RETFIE Return from interrupt TOS gt PC 1 gt GI E 2 Other instructions NOP No operation TOS gt PC 1 gt GI E 1 CLRWDT Clear watchdogtimer 07 WD 17710 1 ro pp 1 SUBE Go into sleep mode ae A TO PD 1 Table 9 1 16Fxx Instruction Set 1 When an I O register is modified as a function of itself the value used will be that value present on the pins themselves 2 f the instruction is executed on the TMR regist
7. 21 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers subtraction T2 T1 If the registers use pulses coming from external source then such a timer is turned into a counter This is only a simple explanation of the operation itself How does a timer operate In practice pulses coming from the quartz oscillator are once per each machine cycle directly or via a prescaler brought to the circuit which increments the number in the timer register If one instruction one machine cycle lasts for four quartz oscillator periods then by embedding quartz with the frequency of 4MHz this number will be changed a million times per second each microsecond Timer register 1 1 1 Elapsed time B A uS Fig 0 28 Timer Operation It is easy to measure short time intervals up to 256 microseconds in the way described above because it is the largest number that one register can contain This obvious disadvantage may be easily overcome in several ways by using a slower oscillator registers with more bits a prescaler or interrupts The first two solutions have some weaknesses so it is preferable to use prescalers or interupts Using prescaler in timer operating A prescaler is an electronic device used to reduce a frequency by a pre determined factor Meaning that in order to generate one pulse on its output it is necessary to bring 1 2 4 or more pulse
8. ADCONI Register LADFM VCFG1 VCFGO Legend Bit is unimlemented RAN Readable Writable bit 0 After reset bit is cleared Fig 7 5 ADCON1 Register ADFM A D Result Format Select bit e 1 Conversion result right justified Six most significant bits of the ADRESLH are not used and e 0 Conversion result left justified Six least significant bits of the ADRESL are not used VCFG1 Voltage Reference bit selects negative voltage reference source needed for A D converter operating http www mikroe com en books picmcubook ch7 5 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules e 1 Negative voltage reference is applied on the Vref pin and e 0 Voltage power supply Vss is used as negative voltage reference source VCFGO Voltage Reference bit selects positive voltage reference source needed for A D converter operating e l Positive voltage reference is applied on the Vref pin and e 0 Voltage power supply Vdd is used as positive voltage reference source In Short In order to measure voltage on an input pin by A D converter the following should be done Step 1 Configuring port e Write logic one 1 to the corresponding bit of the TRIS register to configure it as input and e Write logic one 1 to the corresponding bit of the ANSEL register to configure it as analog input Step 2 Configuring ADC module Co
9. BtS Bt4 BRS BL Bt Biro R 1 R W 1 RIW 1 RW l Features RISE l reses reise Trise Teise0 Bit ame Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Legend Bit is unimplemented RW Readable Writable bit R Readable bit x After reset bit is unknown 1 After reset bit is set Fig 3 14 Port E and TRISE Register Similar to Ports A and B three pins can be configured as analog inputs in this case The ANSELH register bits determine whether a pin will act as analog input AN or digital input output e REO AN5 determined by bit ANS5 of the ANSELregister e REI AN6 determined by bit ANS6 of the ANSELregister and e RE2 AN 7 determined by bit ANS7 of the ANSELregister ANSEL and ANSELH Registers The ANSEL and ANSELH registers are used to configure the input mode of an I O pin to analog or digital http www mikroe com en books picmcubook ch3 8 of 10 5 3 2009 11 32 31 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 3 I O Ports RW 1 RW RW RW RW RWG RW RW Features ANSEL ANS7 ANS6 ANS5 ANS4 ANS3 ANS2 ANS ANSO Bitname Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit O RW 1 RW I O RWO R t X RW RW 1 Features ANSELH ANS13 ANS12 ANS11 ANS10 ANS9 ANS8 Bitname Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit O Bit 2 Bit 1 Legend Bit is unimplemented R W Readable Writable bit 1 After reset bit is set
10. If instructions which reset the watchdog timer are set at the appropriate program locations besides commands being regularly executed then the operation of the watchdog timer will not affect program execution If for any reason usually electrical noises in industry the program counter gets stuck on some memory location from which there is no return the watchdog will not be cleared and the register s value being constantly incremented will reach the maximum et voila Reset occurs http www mikroe com en books picmcubook ch0 24 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Program nstruction 1 Instruction 2 Fig 0 31 Watchdog Timer A D Converter External signals are usually fundamentally different from those the microcontroller understands Ones and Zeros so that they have to be converted in order for the microcontroller to understand them An analogue to digital converter is an electronic circuit which converts continuous signals to discrete digital numbers This module is therefore used to convert some analogue value into binary number and forwards it to the CPU for further processing In other words this module is used for input pin voltage measurement analogue value The result of measurement is a number digital value used and processed later in the program http www mikroe com en books picmcubook ch0 25 of 30 5 3 2009 11
11. Number of cycles 1 EXAMPLE label IORLW 0x35 Echo isis esc io NUR ca alas iauie d GIN i ocean Z 0 IORWEF Inclusive OR W with f Syntax label IORWF f d Description The content of register f is OR ed with the content of W register If d w or d 0 the result is stored in the W register If d f ord 1 the result is stored in register f Operation W OR f gt d Operand 0 x f lt 127 d gt 0 1 Status affected Z Number of cycles 1 EXAMPLE 1 label IORWF REG w Before Instruction execution REG OxI W 0x91 Are In Creon REC 10255 W 0x93 Z 0 http www mikroe com en books picmcubook ch9 20 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set EXAMPLE 2 label IORWF REG f Before instruction execution REG 0x13 W Ox91 After Instruction REG 0x95 W 0x91 Z 0 MOVE Move f Syntax label MOVF f d Description The content of register f is moved to a destination determined by the operand d If d w or d 0 the content is moved to register W If d f or d 1 the content remains in register f Option d 21 is used to test the content of register f because this instruction affects the Z flag of the STATUS register Operation f gt d Operand 0 x f lt 127 d gt 0 1 Status affected Z Number of cycles 1 EXAMPLE 1 label MOVF FSR w Before instruction execution FSR 0x
12. Number of cycles 1 EXAMPLE 1 label ANDLW Ox5F Before instruction execution W as 1010 0011 SED SETS BN Dues inercia NWS UE DOSE 0 03 AS 0 eS DIET le aor 1 EXAMPLE 2 label ANDLW 0x55 Before instruction execution W OxAA 1010 1010 COELO OA AS O Puppen Ino CrO OLLON E eO EOS Z 1 result is 0 ANDWE AND W with f Syntax label ANDWF f d Description AND the W register with register f lf d w or d 0 the result is stored in the W register fd ford 1 the result is stored in register f http www mikroe com en books picmcubook ch9 7 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set Operation W AND f gt d Operand 0 lt f lt 127 d 0 1 Status affected Z Number of cycles 1 EXAMPLE 1 label ANDWF REG f Before ne trcuetion execution ux PEC Ox Z DIDI AO ARTO LAO ARO AZ After Anstruceton NW OxI REG OOZ 1 0000 0 0 0x07 EXAMPLE 2 label ANDWF FSR w Before Instru tilon exeecubuon wol FSR 0x 2 7 x9 9 9p COR EI EUH PROTON MEO OU SNS IS DIEQUE ER e 07 0 91929 9 959 05 400 22 BCE Bit Clear f Syntax label BCF f b Description Bit b of register f is cleared Operation 0 gt f b http www mikroe com en books picmcubook ch9 8 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set Ope
13. To measure time e Reset the TMRO register or write some well known value to it e Elapsed time in microseconds when using quartz 4MHz is measured by reading the TMRO register and e he flag bit TMROIF of the INTCON register is automatically set every time the TMRO register overflows If enabled an interrupt occurs To count pulses e The polarity of pulses are to be counted is selected on the RA4 pin are selected by the TOSE bit of the OPTION register TOSE O positive 1 negative pulses and e Number of We may be read from the TMRO register The prescaler and interrupt are used in the same manner as in timer mode Timer TMR1 Timer TMR1 module is a 16 bit timer counter which means that it consists of two registers TMR1L and TMR1H It can count up 65 535 pulses in a single cycle i e before the counting starts from zero 16 bit counter register s TMR1H Register TMRIL Regiser MEE A BT AQ A AAA bit 15 bit8 bit 7 bit 0 Fig 4 5 Timer TMR1 Similar to the timer TMRO these registers can be read or written to at any moment In case an overflow occurs an interrupt is generated The timer TMR1 module may operate in one of two basic modes as a timer or a counter However unlike the timer TMRO each of these modules has additional functions Parts of the T1CON register are in control of the operation of the timer TMRI http www mikroe com en books picmcubook ch4 5 of 12 5 3 2009 11 32 57 AM mikroElektron
14. e l Timer Tlgate source is T1G and e 0 Timer Tlgate source is comparator SYNCC2OUT C2SYNC Comparator C2 Output Synchronization bit e 1 Comparator C2 output is synchronized to falling edge of Timer TMR1 clock and e 0 Comparator output is asynchronous signal VRCON Register http www mikroe com en books picmcubook ch7 12 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules VREN VROE VRR VRSS VR3 VR2 VR VRO Legend RAW Readable Writable bit 0 After reset bit is cleared Fig 7 13 VRCON Register VREN Comparator C1 Voltage Reference Enable bit e 1 Voltage reference CVref source is powered on and e 0 Voltage reference CVref source is powered off VROE Comparator C2 Voltage Reference Enable bit e 1 Voltage reference CVref is connected to the pin and e 0 Voltage reference CVref is disconnected from the pin VRR CVref Range Selection bit e 1 Voltage reference source is set to low range and e 0 Voltage reference source is set to high range VRSS Comparator Vref Range selection bit e 1 Voltage reference source is in the range of Vref to Vref and e 0 Voltage reference source is in the range of Vdd Vss power supply voltage VR3 VRO CVref Value Selection If VRR 1 low range Voltage reference is calculated using the formula CVref VR3 VRO 24 Vdd If VRR 0 high range Voltage reference is calcu
15. main do necne Oe Soi banksel ANSEL Selects bank containing register ANSEL CET ANSEL Clears registers ANSEL and ANSELH Sites ANSELH ALL pins are digital banksel TRIOB Selects bank containing register TRISB ipe IR IL IS Ao ae obi se ares nato rectas iio Mies banksel ICON Selects bank containing register TICON DOE TICON TMR ICS IMRI counts pulses generated by oscillator bsf MACON neh sO Prescaler rate is 1 8 Dor TICON TICF ESI psf JE CROTNDS TENSISETEXO SI nnn One mea banksel PIRI Selects bank containing register PIEI Deas Ie 309 RMR TE TE RET TMR1 interrupt overflow enabled bsf INTCON PEIE Peripheral modules interrupt enabled Timer TMR1 belongs to peripheral modules locas INTCON GIE Global interrupt enabled banksel PORTE Pp SseleeGrs Dank Containing rcgilster po elche EO TE c Tecum c Ou E LOCOS Geir IE OS Remain here end oO Ea TNI Using timer TMR2 configuring quartz oscillator This example illustrates the use of timer TMR2 The microcontroller uses internal oscillator HFINTOSC with the frequency of 500 kHz The whole program works as follows After the period of time defined by register PR prescaler and postscaler has expired an interrupt occurs Interrupt routine decrements the content of the PR register and simultaneously increments the content of port B Since the number in register PR which determines when interrupt is to occur is constantly decremented interrupt will occur for shorter and shorter per
16. mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set RSTO Lano Tr siu eim execution CS BB A MQ Piel IN Cr dE INS REG 0x00 E d INCFSZ Increment f Skip if 0 Syntax label INCFSZ f d Description Register f is incremented by one If d w or d 0 the result is stored in register W If d f ord 1 the result is stored in register f If the result is 0 then a NOP is executed instead making this a two cycle instruction Operation f 1 gt d Operand 0 lt f lt 127 d 0 1 Status affected Number of cycles 1 or 2 depending on the result EXAMPLE LAB 01 INCFSZ REG f Increment REG by one PARSO m okip this line a result is O CARIO Mp Jump here if result is OU The content of program counter Before instruction execution PCZ LAB Oladdress The content of REG after instruction REG REG 1 If REG 0 the program counter points to the address of label LAB 03 Otherwise the program counter points to address of the next instruction i e to LAB 02 address IORLW Inclusive OR literal with W Syntax label IORLW k Description The content of the W register is OR ed with the 8 bit literal k The result is stored in register W Operation W OR k gt W http www mikroe com en books picmcubook ch9 19 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set Operand 0 lt k lt 255 Status affected
17. www mikroe com en books picmcubook ch2 9 of 12 5 3 2009 11 32 08 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 2 Core SFRs Fig 2 15 PCON register e ULPWUE Ultra Low Power Wake up Enable bit o 1 Ultra Low Power Wake up enabled o 0 Ultra Low Power Wake up disabled e SBOREN Software BOR Enable bit o 1 Brown out Reset enabled o 0 Brown out Reset disabled e POR Power on Reset Status bit o 1 No Power on reset has occurred o O0 Power on reset has occurred This bit must be set in software after a Power on Reset occurs e BOR Brown out Reset Status bit o 1 No Brown out reset has occurred o O0 Brown out reset has occurred This bit must be set in software after a Brown out Reset occurs PCL and PCLATH Registers The size of the program memory of the PIC16F887 is 8K Therefore it has 8192 locations for program storing For this reason the program counter must be 13 bits wide 2 13 28192 In order that the contents of some location may be changed in software during operation its address must be accessible through some SFR Since all SFRs are 8 bits wide this register is artificially created by dividing its 13 bits into two independent registers PCLATH and PCL If the program execution does not affect the program counter the value of this register is automatically and constantly incremented 1 1 1 1 In that way the program is executed just as it is written instruction by ins
18. Appendix B Examples This is a sort of RAM memory so data can be written to and read from it but its contents is irretrievably lost upon the power goes off CGROM Memory CGROM memory contains the default character map with all characters that can be displayed on the screen Each character is assigned to one memory location 4 higher bits of address A Pe ep wla Ls LUA St mi Fr AE ooo IZIBRBIr Tp al ASC a EFIE je fe y SAD Tat Th Pye g ooo JEDI 7 115 S poro EEE 39 35p54 Soo GUS pF sqm S ew eo A SAI 4I E 9 oo STIS eb S e Ra xil i COESKEki MED A ao URL tua t PR e HAM Tim s aix IE pL fe DIN In p sre IRL OOO The addresses of CGROM memory locations match the characters of ASCII If the program being currently executed encounters a command send character P to port then the binary value 0101 0000 appears on the port This value is the ASCII equivalent to the character P It is then written to LCD which results in displaying the symbol from the 0101 0000 location of CGROM In other words the character P is displayed This applies to all letters of the alphabet capitals and small but not to the numbers xxt l10 xxxx 1011 As seen on the previous map addresses of all digits are pushed forward by 48 relative to their values digit 0 address is 48 digit 1 address is 49 digit 2 address is 50 etc Accordingly in order to display digits cor
19. CCP1 interrupt condition has occurred CCP1 is unit for capturing comparing and generating PWM signal Depending on operating mode capture or compare match has occurred In both cases bit must be cleared in software This bit is not used in PWM mode o 0 No CCP1 interrupt condition has occurred e TMR2IF Timer2 to PR2 Interrupt Flag bit o 1 TMR2 8 bit register to PR2 match has occurred This bit must be cleared in software before returning from the interrupt service routine o 0 No TMR2 to PR2 match has occurred e TMRIIF Timerl Overflow Interrupt Flag bit o 1 The TMRI register has overflowed This bit must be cleared in software o O0 The TMRI register has not overflowed PIR2 Register The PIR2 register contains the interrupt flag bits http www mikroe com en books picmcubook ch2 8 of 12 5 3 2009 11 32 08 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 2 Core SFRs OSFIF C2IF CtlF EEIF BCLIF ULPWUIF CCP2IF Legend Unimplemented bit RW ReadableWritable bit R Readable bit 0 After reset bit is cleared Fig 2 14 PIR2 register e OSFIF Oscillator Fail Interrupt Flag bit o l QU oscillator failed and clock input has changed to internal oscillator INTOSC This bit must be cleared in software o 0 System oscillator operates normally e C2IF Comparator C2 Interrupt Flag bit o 1 Comparator C2 output has changed bit C20UT This bit must be
20. Description The content of register W is XOR ed with the 8 bit literal k The result is stored in register W Operation W XOR k gt W Operand 0 lt k lt 255 Status affected Z Number of cycles 1 EXAMPLE 1 label XORLW OxAF Belore Ins ruction execution ED EIOS 7 OO EET I a E Te S sito OxIA OA TOIO 0xIA Z 0 EXAMPLE 2 Const agu 0x label XORLW Const Before instruction execution W 0xAF AO O IL OAE Conse NS O AO hi Oe 7 After In tro Cion W 0k53 OS Z 0 XORWE Exclusive OR W with f http www mikroe com en books picmcubook ch9 32 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set Syntax label XORWF f d Description The content of register f is XOR ed with the content of register W A bit of result is set only if the corresponding bits of operands are different If d w or d 0 the result is stored in register W If d f ord 1 the result is stored in register f Operation W XOR k gt d Operand 0 x f lt 127 d 0 1 Status affected Z Number of cycles 1 EXAMPLE 1 label XORWF REG f Before Instruction execution eS INDEED TP OxXAF e IET TES O ME bx EXE Abeer instruction REG OXIA W 0xBD 3000 L010 Css A EXAMPLE 2 label XORWE REG w Before Instruction execution REG OxAF W gs 1010 ct IE OAT OFr OTOT OE After instruction REG 0xAF W UxlA gt 39001 T
21. EEPROM Size 256 Bytes Address Oh Revision File C ADOCUMENTS AND SETTINGSIMARKOJ MIE DESKTOP TOUCHPANEL BIGPICS P 18 TOUCHPANEL HEX Device PICI6FBB7 Operation None Fig 8 14 Enable Int Ext Switchover Fail Safe Clock Monitor d vice PICISF887 Verify Blank Erase Reset Load HEX Reload HEX Save HEX CODE EEPROM Options Progress rs The Fail Safe Clock Monitor FSCM monitors the operation of external oscillator and allows the microcontroller to proceed with program execution even the external oscillator fails for some reason In this case the internal oscillator takes over its role http www mikroe com en books picmcubook ch8 9 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits a i O O LFINTOSC HFINTOSC 31 kHz 32uS Fig 8 15 Fail Safe Clock Monitor The fail safe clock monitor detects a failed oscillator by comparing the internal and external clock sources In case it takes more than 2mS for the external oscillator clock to come the clock source will be automatically switched The internal oscillator will thereby continue operating controlled by the bits of the OSCCON register When the OSFIE bit of the PIE2 register is set an interrupt will be generated The system clock will continue to be sourced from internal clock until the device successfully restarts the external oscillator and switches bac
22. Fig 5 8 CCP1CON Register P1M1 P1MO PWM Output Configuration bits In all modes excepting PWM the P1A pin is Capture Compare module input P1B PLC and P1D pins act as input output port D pins In PWM mode these bits affect the CCP1 module as shown in the table 5 4 below P1M1 P1MO Mode PWM with single output 0 0 Pin P1A outputs modulated signal Pins P1B P1C and P1D are port D input output Full Bridge Forward configuration 0 1 Pin P1D outputs modulated signal Pin P1A Is active Pins P1B and P1C are inactive Half Bridge configuration 1 0 Pins P1A and P1B output modulated signal PinsP1C and P1D are port D input output Full Bridge Reverse configuration 1 1 Pin P1B outputs modulated signal Pin P1C is active Pins P1A and P1D are inactive Table 5 4 CCP1CON Register DC1B1 DC1B0 PWM Duty Cycle Least Significant bits are only used in PWM mode in which they represent two least significant bits of a 10 bit number This number determines PWM signal s duty cycle The rest of bits 8 in total are stored in the CCPRIL register CCP1M3 CCP1MO CCP1 Mode Select bits determine the mode of the CCP1 module CCP1M3 CCP1M2 CCP1M1 CCP1MO Mode 0 0 0 0 Module is disabled reset 0 0 0 1 Unused Compare mode CCP1IF bit is set on match 0 0 1 it Unused Capture mode 0 0 1 0 1 0 Every falling edge on the CCP1 pin 0 1 0 1 IRE mode Every rising edge on the CCP1 pin 0 1 1 0 Capture mode Every 4th rising edge on
23. Here is an explanation on the figure above First a byte representing units is applied on a microcontroller port and a transistor T1 is activated simultaneously After a while the transistor T1 is turned off a byte representing tens is applied on a port and transistor T2 is activated This process is being cyclically repeated at high speed for all digits and corresponding transistors A disappointing fact which indicates that the microcontroller is just a kind of miniature computer designed to understand only the language of zeros and ones is fully expressed when displaying any digit Namely the microcontroller does not know what units tens or hundreds are nor what ten digits we are used to look like Therefore each number to be displayed must go through the following procedure First of all in a particular subroutine a multi digital number must be split into units tens etc Then these must be stored in special bytes each Digits get recognizable format by performing masking In other words a binary format of each digit is replaced by a different combination of bits using a simple subroutine For example the digit 8 0000 1000 is replaced by binary number 0111 1111 in order to activate all LEDs displaying digit 8 The only diode remaining inactive in this case is reserved for the decimal point If a microcontroller port is connected to the display in a way that bit 0 activates segment a bit 1 activates segment b bit 2 segment c etc
24. Higher byte of argument is moved ES cn Lower byte of argument is moved CTO LOEME Decrements HIcnt and LOcnt while needed and calls subroutine Delaylms mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples PETC STATUS 4 SOTO End eet Delaylms decf Fea tes decf IG e T Og Leo Delaylms movlw IO a movwt TOO me OCIS e nop nop nop nop nop nop OJO decfsz IPs T goto oo return End ENDM Delaylms provides delay of 100 10us 1ms OO Sia lt hoe Execution time of Loop2 is TO us Mv ME M M M Ae Mu E Iu uU UU M E Macro button MIR D M M CMM p E UL MU M UE US bukeon MACRO pore pin Nilo label local Pressedl Local Pressed2 local lll Losa PEZ IFNDEF debouncedelay define debouncedelay 10 ENDIE IF hilo 0 Ese NE pin goto Ese te di poems celo teo Les Pressedl Beros Pore pin Gere Pressedl aus ens de Counc ede Ear Goro label posi ELSE Dimes Core pin SOES Exit Pau ems deso unc cde kay Pressed2 btfsc Sida Saka goto Pressed2 aus ens dewounieede Vay goro label Exit ENDTE ENDM All labels are local Enables debounce time to be defined A e aa S36 Opel Ie pull up used If Ug push button is pressed Wait for 10ms debounce Wait until released and jump to specified address If pull down used if 0 push button ws released Wait for 10ms debounce Wait until released and
25. RA5 General purpose I O port A A KIA ATA hannal A RA3S AN3 Vref C 1IN 9 http www mikroe com en books piemcubook ch1 4 of 14 5 3 2009 11 31 25 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview HA JENGA PUPUSE VWV POLA AN4 AD Channel 4 RAS AN4 SS C20UT f 35 SPI module Input Slave Select C20UT Comparator C2 Output REO ANS a REO General purpose I O port E AN5 A D Channel 5 RE4 ANG 9 RE1 General purpose I O port E ANG A D Channel 6 RE2 ANT 10 RE General purpose I O port E AN A D Channel 7 Vdd 11 Positive supply Vss 12 Ground GND Table 1 1 Pin Assignment Number re purpose I O port A RAT OSCT CLKIN 13 Crystal Oscillator Input CLKIN External Clock Input OSC2 Crystal Oscillator Output RAG OSC2 CLKOUT 14 CLKO Fosc 4 Output RAG General purpose I O port A RCO General purpose I O port C RCO T1OSO TTCKI 15 T1OSO Timer T1 Oscillator Output T1CKI Timer T1 Clock Input RC1 General purpose I O port C RCT TTOSO TTCKI 16 T1OSI Timer T1 Oscillator Input CCP2 CCP1 and PWM 1 module I O RC2 General purpose I O port C RC2 P1A CCP1 17 P1A PWM Module Output CCP1 CCP1 and PWM1 module I O RC3 General purpose I O port C RC3 SCK SCL 18 SCK MSSP module Clock I O in SPI mode SCL MSSP module Clock I O in IC mode RDO 19 RDO General purpose I O port D RD1 20 RD1 General purpose I O port D
26. RD 21 RD2 General purpose I O port D RD3 22 RD3 General purpose I O port D RC4 General purpose I O port A RCA SDI SDA 23 SDI MSSP module Data input in SPI mode SDA MSSP module Data I O in IC mode http www mikroe com en books picmcubook chl 5 of 14 5 3 2009 11 31 25 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview RCS SDO RCG TX CK RC7 RX DT RD5 P1B RD6 P1C RD7 P1D Vss Vdd RBO AN12 INT RB1 AN10 C12INT3 RB2 AN8 RB3 ANS PGM C121N2 RB4 AN11 RB5 AN13 T1G RB6 ICSPCLK Number SDA MSSP module Data I O in I C mode RCS General purpose I O port C SDO MSSP module Data output in SPI mode RC6 General purpose I O port C 25 TX USART Asynchronous Output CK USART Synchronous Clock RC General purpose I O port C 26 RX USART Asynchronous Input DT USART Synchronous Data 24 Table 1 1 cont Pin Assignment General purpose I O port D RD5 General purpose I O port D 28 P1B PWM Output 20 RD6 General purpose I O port D P1C PWM Output 30 RD7 General purpose I O port D P1D PWM Output 31 Ground GND 32 Positive Supply RBO General purpose I O port B 33 AN12 A D Channel 12 INT External Interrupt RB 1 General purpose I O port B 34 AN10 A D Channel 10 C12INT3 Comparator C1 or C2 Negative Input RB2 General purpose I O port B ik AN8 A D Channel 8 RB3 General purpose I O port B 36 ANS A D C
27. all instructions are executed in only one instruction cycle The only exception isjump instruction which is executed in two cycles e Owing to the fact that a program ROM and temporary data RAM are separate the CPU can execute two instructions simultaneously Simply while RAM read or write is in progress the end of one instruction the next program instruction is being read via another bus e When using microcontrollers with von Neumann architecture one never knows how much memory is to be occupied by some program Basically each program instruction occupies two memory locations one contains information on WHAT should be done whereas another http www mikroe com en books picmcubook ch0 27 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers contains information upon WHICH data it should be done However it is not a hard and fast rule but the most common case In microcontrollers with Harvard architecture the program bus is wider than one byte which allows each program word to consist of instruction and data In other words one program word one instruction INSTRUCTION SET Instructions that can be understood by the microcontroller are known as an instruction set When you write a TE program in assembly language you actually tell a story by specifying instructions in the order they should be movlw Ox3F executed The main restriction in this proces
28. the location containing interrupt vector is passed over during regular program execution Part of the program being activated when an interrupt request arrives is called the interrupt routine Its first instruction is located at the interrupt vector How long this subroutine will be and what it will be like depends on the skills of the programmer as well as the interrupt source itself Some microcontrollers have more interrupt vectors every interrupt request has its vector but in this case there is only one Consequently the first part of the interrupt routine consists in interrupt source recognition Finally when the interrupt source is recognized and interrupt routine is executed the microcontroller reaches the RETF IE instruction pops the address from the stack and continues program execution from where it left off o o Instructions Addresses Instructions Addresses Instructions Addresses er Interrupt LM o Y a STACK A AS Fig 1 7 Interrupt System How to use SFRs You have bought the microcontroller and have a good idea how to use it There is a long list of SFRs with all bits Each of them controls some process All in all it looks like a big control table with a lot of instruments and switches Now you are concerned about whether you will manage to learn how to use them all You will probably not but don t worry you don t have to Such powerful microcontrollers are similar to a supermarkets t
29. then the table below shows the mask for each digit http www mikroe com en books picmcubook appb 9 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples lelojolojo t oft Number 5 binary 77 f b b 0 1 1 0 1 1 0 1 Number 5 mask loa f dpg f edc ba j pe le Lao dp Low current common cathode display Digits to display Display Segments d o O O 0O N DUB q NO CIcoIcoIcrIcIcIgoIgo Ic Jc RhhRRPRPROPEPBE O PrPrPOoOoOrrFrRrFR FB oF PRP rFPrFPrPrPrF OOF O PrPOoOrrFrFOoOrRrRrFRFoOoF ol elolelolololerlojr lo RhROPPAPOOOBRE RhROPP RPBRPPOOMG In addition to digits from 0 to 9 there are some letters A C E J F U H L b c d o r t that can be also displayed by means of the appropriate masking In the event that the common anode displays are used all ones contained in the previous table should be replaced by zeros and vice versa Additionally NPN transistors should be used as drivers as well OPTOCOUPLER An optocoupler is a device commonly used to galvanically separate microcontroller electronics from any potentially dangerous current or voltage in its surroundings Optocouplers usually have one two or four light sources LED diodes on their input while on their output opposite to diodes there is the same number of elements sensitive to light phototransistors photo thyristors or photo triacs The point is that an optocoupler us
30. voltage and current to start operation but there are also miniature ones that can be activated by a low current directly obtained from a microcontroller pin This figure shows the most commonly used solution In order to prevent the appearance of high voltage self induction caused by a sudden stop of current flow through the coil an inverted polarized diode is connected in parallel to the coil The purpose of this diode is to cut off the voltage peak GND GND LED DIODES You probably know all you need to know about LED diodes but we should also think of the younger generations How to destroy a LED Well Very simple http www mikroe com en books picmcubook appb 6 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples Quick burning Like any other diode LEDs have two ends an anode and a cathode Connect it properly to a power supply voltage The diode will happily emit light Turn it upside down and apply the same power supply voltage even for a moment It will not emit light NEVER AGAIN Slow burning There is a nominal i e maximum current determined for every LED which should not be exceeded If it happens the diode will emit more intensive light but not for a long time Something to remember Similar to the previous example all you need to do is to discard a current limiting resistor shown below Depending on power supply voltage
31. with a letter of alphabet or and may consist of maximum of 32 characters Besides it is easily used e It is sufficient to enter the name of a label instead of a 16 bit address in instruction which calls some subroutine or a jump The label with the same name should also be written at the beginning of a program line in which a subroutine starts or where a jump should be executed As a general rule labels have easily recognizable names During program compiling the assembler will automatically replace the labels by the corresponding addresses r A EN EE EE ENDS SONNO mE NR EN NU First column ee Correctly written label Start End P123 Incorrectly written label Start drele COMMENTS Acomment is often an explanatory text written by the programmer in order to make a program clearer and easier to understand It is not necessary to comment every line When three or four lines of code work together to accomplish some higher level task it is better to have a single higher level comment for the group of lines Therefore it is added if needed and has to start with Comments added to assembly source code are not compiled into machine code INSTRUCTIONS http www mikroe com en books picmcubook appa 2 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller Instructions are defined for each microcontroller family by the manufacturer Therefore it
32. 0 13 8 or 10 Wee 1 Me ee Ve Yeu st tp e OS cee beer emer I I lee 20 qeu 10 2 2x81x 16 AIN High End 8 bit architecture 16 bit Instruction Word Length 0 2x82 ea 2X AN2 PICI8FXXX uri p MI NN I ME 10 or 12 TL NA us SPI 0 2x82 Ven t USART PIC18FXXJ XX 8 128 l1024 3036128 1001 40 48 10 16 10 2 E AAA V SPI PICL8FXXKXX 8 64 768 3936 28 44 64 10 13 10 2 1x83x16 A I2C 2 All PIC microcontrollers use harvard architecture which means that their program memory is connected to CPU via more than 8 lines Depending on the bus width there are 12 14 and 16 bit microcontrollers The table above shows the main features of these three categories http www mikroe com en books picmcubook ch0 29 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers As seen in the table on the previous page excepting 16 bit monsters PIC 24FXXX and PIC 24HXXX all PIC microcontrollers have 8 bit harvard architecture and belong to one out of three large groups Therefore depending on the size of a program word there are first second and third category i e 12 14 or 16 bit microcontrollers Having similar 8 bit core all of them use the same instruction set and the basic hardware Skeleton connected to more or less peripheral units In order to avoid tedious explanations and endless story about the useful features of different microcontrollers this book describes
33. 10 bit result ADFM 0 Fig 7 2 ADRESH and ADRESL Registers A D Acquisition Requirements For the ADC to meet its specified accuracy it is necessary to provide a certain time delay between selecting specific analog input and measurement itself This time is called acquisition time and mainly depends on the source impedance There is an equation used for accurately calculating this time which in the worst case amounts to approximately 20uS Briefly after selecting or changing the analog input and before starting conversion it is necessary to provide at least 20uS time delay to enable the ACD maximal conversion accuracy ADC Clock Period Time needed to complete a one bit conversion is defined as TAD The required TAD must be at least 1 6 uS One full 10 bit A D conversion is a bit longer than expected and amounts to 11 TAD periods However since both the conversion clock frequency and source are determined by software one of the available combination of bits ADCS1 and ADCSO should be selected before voltage measurement on some analog input starts These bits are stored in the ADCONO register Device Frequency Fosc ADC Clock Source ADCSI ADCSO 20 Mhz 8 Mhz 4 Mhz 1 Mhz Fosc 2 0 0 100 nS 250 nS 500 nS 2 uS Fosc 8 0 1 400 ns VS ps 8 uS Fosc 32 1 0 1 6 uS 4 uS 8 uS 32 uS Frc 1 1 2 6uS 2 6uS 2 6uS 2 6uS Table 7 1 ADC Clock Period Any change in the system clock frequency will affect the ADC clock frequency which may adversely
34. 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Fig 0 32 A D Converter Internal Architecture All upgraded microcontrollers use one of two basic design models called Harvard and von Neumann architecture Briefly they are two different ways of data exchange between CPU and memory von Neumann Architecture http www mikroe com en books picmcubook ch0 26 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Microcontrollers using this architecture have only one memory block and one 8 bit data bus As all data are exchanged by using these 8 lines this bus is overloaded and communication itself is very slow and inefficient The CPU can either read an instruction or read write data from to the memory Both cannot occur at the same time since the instructions and data use the same bus system For example if some program line says that RAM memory register called SUM should be incremented by one instruction incf SUM the microcontroller will do the following RAM ROM program 1 Read the part of the program instruction specifying WHAT should be done in this very case it is the incf instruction for increment 2 Read further the same instruction specifying upon WHICH data it should be performed in this very case it is the SUM register 3 After being incremented the co
35. 35 input output pins o High current source sink for direct LED drive o Software and individually programmable pull up resistor o Interrupt on Change pin 8K ROM memory in FLASH technology o Chip can be reprogrammed up to 100 000 times In Circuit Serial Programming Option o Chip can be programmed even embedded in the target device e 256 bytes EEPROM memory o Data can be written more than 1 000 000 times e 368 bytes RAM memory e A D converter o 14 channels http www mikroe com en books picmcubook chl 1 of 14 5 3 2009 11 31 25 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview o 10 bit resolution 3 independent timers counters Watch dog timer Analogue comparator module with o Two analogue comparators o Fixed voltage reference 0 6V o Programmable on chip voltage reference PWM output steering control e Enhanced USART module o Supports RS 485 RS 232 and LIN2 0 o Auto Baud Detect e Master Synchronous Serial Port MSSP o Supports SPI and I2C mode RES MCLRIVpp RBT ICSPDAT RAO ANO ULPWLC12INO RB6 CSPCLK RAT AN1 C121N1 RBSI AN13 T1G RA2 AN2 Vref C Vref C21NA RBAI ANT1 RA3IAN3 Vref C41NA RB3 ANS PGM C 121N2 RAA TOCKI C1OUT RB2IANS RAS ANA 55 C20UT RB1 ANTO C121N3 REOIANS RBO AN12 NT RE1 AN Vdd RE2IANT Vss Vdd RDTIP1D Vas RDGIPIC RATIOSCT CLKIN RDS P1B RAG OSC2 CLKOUT RDA RCOTIOSOTICKI RCTIRX DT RC1 TIOSI CCP2 RCGITXICK RC2 P4AAICCPA
36. 5 3 2009 11 34 00 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules SSPCON2 Register GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN RAN Readable Writable bit R Readable bit 0 After reset bit is cleared Fig 6 25 SSPCON2 Register GCEN General Call Enable bit In 12C slave mode only e 1 Enables interrupt when a general call address 0000h is received in the SSPSR and e 0 General call address disabled ACKSTAT Acknowledge Status bit In 12C Master Transmit mode only e 1 Acknowledge was not received from slave and e 0 Acknowledge was received from slave ACKDT Acknowledge data bit In 12C Master Receive mode only e 1 Not Acknowledge and e 0 Acknowledge ACKEN Acknowledge condition Enable bit In 12C Master Receive mode e 1 Initiate acknowledge condition on SDA and SCL pins and transmit ACKDT data bit It is automatically cleared by hardware and e 0 Acknowledge condition is not initiated RCEN Receive Enable bit In 12C Master mode only e 1 Enables data receive in 12C mode and e O0 Receive disabled PEN STOP condition Enable bit In 12C Master mode only e 1 Initiates STOP condition on pins SDA and SCL Afterwards this bit is automatically cleared by hardware and e 0 STOP condition is not initiated RSEN Repeated START Condition Enabled bit In IC master mode only e 1 Initiates START condition on pins SD
37. ADC Mode and Registers Even though the use of A D converter seems to be very complicated it is basically very simple simpler than using timers and serial communication module anyway http www mikroe com en books picmcubook ch7 1 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules a Ca C34 Tana ins A 1 1 E 1c C o c MEN a EL o A e 8 a A e E amp ADCON1 Register Fig 7 1 ADC Mode and Registers The module is under the control of the bits of four registers e ADRESH Contains high byte of conversion result e ADRESL Contains low byte of conversion result e ADCONO Control register 0 and e ADCON1 Control register 1 ADRESH and ADRESL Registers When converting an analog value into a digital one the result of the 10 bit A D conversion will be stored in these two registers In order to deal with this value easier it can appear in two formats left justified and right justified The ADFM bit of the ADCON1 register determines the format of conversion result see figure 7 2 In the event that A D converter is not used these registers may be used as general purpose registers http www mikroe com en books picmcubook ch7 2 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules ADRESH Right justified Left justified
38. BIFSC EECON WRI Cole PCE STATUS REO MOVE ADDRESS W MOVWF EEADR MOVE DATA W MOVWF EEDATA IS STATUS REO BCE EUG ONU ID BSF EECONI WREN ESE NEON ACI Wait for the previous write to complete Bank 2 Move address to W Write address Move data to W Write data Bank 3 Select EEPROM Write to EEPROM enabled All interrupts disabled Ne Ne Ne Ne Ne Noe Ne Ne Ne Ne Ne Ne MOV LW Soh Required sequence start MOVWF EECON2 MOVLW AAh MOVWF EECON2 Required sequence end Bow EECONT WR BoE INTCON EHE Interrupts enabled BOE EECONI WREN T Write to HERE ROM disabled Reset Black out Brown out or Noises On reset the microcontroller immediately stops operation and clears its registers Reset signal may be generated externally at any moment low logic level on the MCLR pin If needed it can be also generated by internal control logic Power on always causes reset Namely because of many transitional events which take place when power supply is on switch contact flashing and sparkling slow voltage rise gradual clock frequency stabilization etc it is necessary to provide a certain time delay before the microcontroller starts operating Two internal timers PWRT and OST are in charge of that The first one can be enabled or disabled during program writing The scenario is as follows http www mikroe com en books picmcubook ch8 13 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontr
39. Chapter 5 CCP Modules In this mode the PWM signal is output on the P1A pin while at the same time the complementary PWM signal is output on the P1B pin Such pulses activate MOSFET drivers in Half Bridge mode which enable disable current flow through device FET Driver ia Le Fig 5 12 Half Bridge Mode In relation to this circuit it is very dangerous to switch on both MOSFET drivers simultaneously The short circuit caused in that moment will be fatal In order to avoid that it is necessary to provide a short delay between switching drivers on and off This delay is marked as td in figure 5 13 below The problem is solved by using the PDCO PDC6 bits of the PWM1CON register Period E CBLIDO Pulse Width a ms a TMR2 PR2 TMR2 PR2 TMR2 PR2 Fig 5 13 Half Bridge Mode As shown in figure 5 14 the same mode can be used to activate MOSFET drivers in Full Bridge http www mikroe com en books piemcubook ch5 11 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules FET Driver FET iU Driver riv Fig 5 14 Activate MOSFET drivers Full Bridge Mode In Full Bridge mode all four pins are used as outputs In practice this mode is commonly used to run motors which provides simple and complete control of speed and rotation direction There are two such configurations Full Bridge Forward and Full Bridge Reverse es
40. Fig 3 15 ANSEL and ANSELH Registers The rule is To configure a pin as an analog input the appropriate bit of the ANSEL or ANSELH registers must be set 1 To configure pin as digital input output the appropriate bit must be cleared 0 The state of the ANSEL bits has no affect on digital output functions The result of any attempt to read some port pin configured as analog input will be 0 Fig 3 16 ANSEL and ANSELH Configuration In Short You will probably never write a program which fully utilises all the Ports in an efficient manner to justify learning all http www mikroe com en books picmcubook ch3 9 of 10 5 3 2009 11 32 31 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 3 I O Ports there is to know about these Ports However they are probably the simplest modules within the microcontroller This is how they are used e When designing a device select a port through which the microcontroller will communicate to the peripheral environment If you intend using only digital inputs outputs select any port you want If you intend using some of the analog inputs select the appropriate ports supporting such pins configuration ANO AN13 e Each port pin may be configured as either input or output Bits of the TRISA TRISB TRISC TRISD and TRISE registers determine how the appropriate ports pins PORTA PORTB PORTC PORTD and PORTE will act e i use some of the analog inputs set the appropriate b
41. OFF amp PWRIE ON amp MCLRE ON amp CP OFF k CPD OFF amp BOR ON amp IESO ON amp FCMEN ON amp LVF OFF amp DEBUG OFF y B E E DAS has Config word should CONFIG CONFIG2 BOR40V amp WRT OFF be displayed in one line z a AAA ERAN AAA ORG OxO00Q Address of the first program instruction RESET vector MMC EE cime leu den M E S banksel TRISB Selects bank containing TEISB o CURE TRISB All port B pins are configured c3 as outputs o banksel PORTE Selects bank containing PORTE a mowlw B 01010101 Moves number 01010101 to W movwt PORTE Moves number 01010101 from W to PORTB end End The purpose of the header and initial directives is briefly described below Header The header is placed at the beginning of the program and gives basic information in the form of comments name of the program release date etc Don t be deluded into thinking that after a few months you will know what that program is about and why it is saved in your computer Initial directives list p 16f887 This directive defines processor to execute a program include p16f887 inc It enables the compiler to access the document p16f887 inc If you have MPLAB installed it is placed by default on C Program files Microchip MPASM Suite Every SFR register contained in this document as well as every bit has its own name and address If the program reads fo
42. Previous Chapter Table of Contents Next Chapter http www mikroe com en books picmcubook ch9 34 of 35 5 3 2009 11 35 12 AM Status Affected STATUS STATUS DC STATUS STATUS DC STATUS STATUS DC STATUS Z STATUS Z STATUS STATUS DC STATUS Z STATUS STATUS DC STATUS Z STATUS STATUS DC STATUS Z STATUS DC STATUS Z STATUS Z STATUS STATUS DC mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set http www mikroe com en books picmcubook ch9 35 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller TOC Introduction Ch 1 Ch 2 ers Ch 4 Gh Ch 6 EN Ch 8 Climo App A App B App C Appendix A Programming a Microcontroller Microcontrollers and humans communicate through the medium of the programming language called Assembly language The word Assembler itself does not have any deeper meaning it corresponds to the names of other languages such as English or French More precisely assembly language is only a passing solution In order that the microcontroller can understand a program written in assembly language it must be compiled into a language of zeros and ones Assembly language and Assembler do not have the same meaning The first one refers to the set of rules used for writing program for the microcontroller while the later refers to a
43. RELAY POR gt en 2 Ol Done nay ES oA tS IAS CS tS usan vs us SS TAS PA us LAS IA Ca as MAIN PROGRAM Yat RA AT TAS TAD TA AGO AE AE Vas Wah Uae AOS AT TAN Tah LAS AGB ARGUS QAI C WS tah AT Tay REA AGIR AS Uae Pas Or Oise 000 7 Address Or the first program Instruciion banksel TROE Selects bank containing register TRISB ea TRISE Aport E pits are cue as EIE I NS Cn TRISD 7 AM port D pins are Coni igured as o teus movlw EXI OOO This number is written to W register movwf TRISA ge Oily live recia opio om TOYOTA AS o banksel OPTION REG Bank Containing OPTION_REG tegistes Ot OPTION REG LUGS Pan RAS as supplied with pulses bsf OPTION_REG PSA Prescaler rate is 1 1 banksel PORTE r sceleebs bank Containing PORTE register el TMRO Clears timer register DCE PORTO gt AMO O M Toop movfw TMRO Timer register is moved to W register movwft PORTB W register is moved to PORTB xorlw TEST Operation exclusive OR between http www mikroe com en books picmcubook appb 29 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples W register and number TEST 00000101 DEESE STATUS AZ If numbers are equal result is 0 and DSi POR TD r DIt STATES A cea pe POP a oe GOO loop and jump to label loop is executed end SO eas Sie OCjie Sn EXAMPLE 7 Using macros in the program using debounce routine You have probably noticed in the previous example that the microcontroller does not alwa
44. Receive complete The SSPBUF register is full and e 0 Receive not complete The SSPBUF register is empty During data transmit in 1 C mode only e 1 Data transmit in progress does not include the bits ACK and STOP and e 0 Data transmit complete does not include the bits ACK and STOP SSPCON Register WCOL SSPOV SSPEN CKP sspm3 ssPM2 SSPM1 SSPMO Legend RW Readable Writable bit 0 After reset bit is cleared http www mikroe com en books picmcubook ch6 20 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules Fig 6 24 SSPCON Register WCOL Write Collision Detect bit e 1 Collision detected A write to the SSPBUF register was attempted while the I C conditions were not valid for a transmission to start and e 0 No collision SSPOV Receive Overflow Indicator bit e 1 Anew byte is received while the SSPSR register still holds the previous data Since there is no space for new data receive one of these two bytes must be cleared In this case data in SSPSR is lost and e O0 Serial data is correctly received SSPEN Synchronous Serial Port Enable bit determines the microcontroller pins function and initializes MSSP module In SPI mode e 1 Enables MSSP module and configures pins SCK SDO SDI and SS as the source of the serial port pins and e 0 Disables MSSP module and configures these pins as I O port pins I
45. Relay In this example the TEST register contains number 5 Naturally it could be any number and could be calculated or entered via the keyboard Instead of a relay the microcontroller can activate some other device and instead of push buttons it can use sensors This example illustrates one of the most common uses of the microcontroller in industry When something is done as many times as needed then something else should be switched on or off http www mikroe com en books picmcubook appb 28 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples vcc C Input 10K RESET l mall ha i i i i U i O i 10K o D VCC TI E Relay co i CO m m i GND i i 8MHz O o 2x20 30pF HI 1 Va A GND Example 6 PT DE RAZAS TAF A IAEA GE IESU AGO RAS Cal ah REA Cah ah TAS al Wal eat TAZAS Lah AE E All Ah ri TAR Cat A A BOOK UE CaS erate AS a Tall Val TR TARTAR Cah Gal Catia Cah VAT GIC eT aI S NACION RACK BECA UII Ral Wal Ay A Header ES We we we ce eos US US A A A A A TS SS E A US A AS O OS BS SS A O O RO OS TA A ESS SS SS SS O US OA TA O AR TA O SS SS SS NOS O AR SUS ES TS US TS DS SS OR A US US UNS Ne Ne Ne Ne IATA US WSUS eS EK RA DEFINING VARIABLES CD US Ue US TOS US ToS AL US TS ToS TS WS ToS US US WS TS US US WSIS FAL US IS AS US US OS HS TS US SIAL US IS TOS TALUS Toss Se VS TEST egu Od CS Binary number OOOOOTOL TEST define
46. S E d I LR E M E M C E MS C o ME EA E d mE I RE X E ON banksel DCE Der PEE psf banksel ee banksel Op mov lw movwt movlw movwt hexyl decfsz Goro mov lw movwt movlw movwt LO decfsz Goro Goro end EXAMPLE 3 Using nested loop The connection scheme is again the same To make this a bit more interesting a different combination of port B bits change each other And that s not all of course As seen from the previous two examples the microcontroller is very fast and often it needs to be slowed down The use of the built in oscillator LF as in example 2 is the last measure that should be applied The problem is more often solved by using nested loops in a program In this example the variable counter1 is decremented 255 times by 1 in the shorter loopl Prior to leaving this loop the program will countdown 255 times from 255 to 0 It means that between only two LED diode s blink on the port there are 255x255 pulses coming from the quartz oscillator Precisely speaking the number of pulses amounts to approximately 196 000 since it also takes some time to execute jump instructions and decrement instructions Yes it s true the microcontroller mostly waits and does nothing Example 3 0x0000 OSCCON OSCCON O OSCOON S OSCCON 4 OG eO TRIOB TRISB PORIB EDEN PORTB lay deg Counter counterl Laja B I0I0TOTO PORTB lay ede counterl Counter ocio KOOP Ne C Ne Ne me
47. STATUS Save register PCLATH 2e lecet o bank containing PORTE Increments PORTB register by 1 Selecto Dank Contarning PRZ PR2 is decremented by 1 ECLATO 1s Given is Original stare STONES victis S ones S Se cu cS Wo ws Given its original craie Selects bank Containing PIRI Clears interrupt flag IMR2IF Global interrupt enabled Return from interrupt routine 0 KK KK KK KK KK KK KK KK KK KK KKK eK KK KK RK KK KK KK KKK KK KK KKK KKK KKK KKK KK i MAIN PROGRAM ma ln TOOP banksel pef psf Df DST banksel cl els banksel cla cl banksel mov lw movwt Elri banksel sir DSE DS GOLO end EXAMPLE 10 Module CCP1 as PWM signal generator OSCCON OSCCON G O E CONT OSCCON 4 OSCCON O ANSEL ANSEL ANSELH iRise Masa PRZ TZ CON HARE TZ CON POR Ie TIS IL ETE EMETTE Nae ON Eire INEC CON CIE loop Ne Ne Ne Ne Ne Ne Ne Ne Ne Sake Mb S a Malm Program Selects bank containing register OSCCON selects internal oscillator HEEINTOSC with frequency of li E MLErOCONTELeOLler uses internal osceillacor Selects bank containing register ANSEL Clears registers ANSEL and ANSELH All pins are cus ci Selects bank containing register TRISB Allport B pins gsm ecc SOINS NS Selects bank containing register T2CON Sets all control register bats prescaler 1 16 postscaler 1 16 TMR2 0N Selects bank containing register PIEI TMR2 interrupt enabled Peripheral modules interrupt enabled Timer T
48. TOES IL Selects bank containing register PIEI Interrupt TMR1 is enabled Peripheral modules interrupts are enabled Global interrupt enabled Prescaler TMR2 1 4 Number in register PR2 BES EO configure CCP1 module Remain here ENC AS OGE Am PIC16F887 A D converter is used in this example Everything is quite simple A variable analog signal is applied on the AN2 pin while the result of conversion is shown on port B as a binary number In order to simplify the program as much as http www mikroe com en books picmcubook appb 37 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples possible only 8 lower bits of the result of conversion are shown GND is used as a negative voltage reference Vref while positive voltage reference is applied on the AN3 pin It enables voltage measurement scale to stretch and shrink To make this clear the A D converter always generates a 10 bit binary result which means that it detects a total of 1024 voltage levels 21021024 The difference between two voltage levels is not always the same The less the difference between Vref and Vref the less the difference will be between two of 1024 levels Accordingly the A D converter Is able to detect slight changes in voltage WCC O 10K Voltage to measure Example 11 GND 8849LDld INDUCED A UE OE HUI Header ROT AA QUK AG US TAL
49. UA AS ERA TAS CAT AS ello ela 0x20 ici LOcatr LO caue CME endc Block or aAriables or c ca ob address 20h iol of block a dc D NM DE KM UE A uu UE EE ORG 05501010 Reset vector MO garo main Conto Stare OL Ene procrom Tabel mu olas M I M uu I E E EU E E M SL US include pause line include uc me shaves M M MM M UAR EE E E DUUM EE UU D DU E EE UU E UE main banksel ANSEL Selects bank containing ANSEL CIE ANSEL cla ANSELH pins ake digiuial banksel IE Sie bet IRISA O0 SNE Ton DSE EREDA dl E jenlia orsus IS 2 8 d telrexh E Sta cl TRES Allport E pins are outputs Clr RISD ALL port D pins are outputs banksel BORTE cl PORTE PORTE Q CLET PORTH PORTD 0 Clit Sige cnt 0 Loop banksel PORTA IG DRE E Om PORTA 0 0 Increment Due com PORTA 1 0 Decrement I3DRE E OR PORTA Ue ave banksel EEADR movlw ME Reads EEPROM memory location movwt EEADR at address 5 banksel EECON1 Der ie ONSE DEED DoT ERCON RD Reads data from EEPROM memory banksel EEDATA movfw EEDATA Moves data to W banksel PORTO movw ft PORTO Data is moved from W to PORTD COLO ESOP merene ie Increments number on port B MENA Si MONE Su W movwf PORTE Goro Loop Ip eus c mes Decrements number on port B decf Sr E MONT CAE W movwf PORTE GOEG TOOP Save top ies alba rOn pore B to RERROM banksel EEADR memory location at address 5 movlw AO movw f EEADR Writes address banksel PORTE movfw RORTE Coples Pore B o
50. again It means that most of time as well as power obtained from batteries is wasted This problem is solved by using internal oscillator for program execution while these 1024 pulses are counted Afterwards as soon as the external oscillator frequency becomes stable it will automatically take over the leading role The whole process is enabled by setting one bit of the configuration word In order to program the microcontroller it is necessary to select the Int Ext Switchover option in software http www mikroe com en books picmcubook ch8 8 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits Enabled mikroElektronika PicFLASH v7 09 with mikrolCD File Device Buffer Windows USB About History Configuration Bits Code Protect Oscillator H5 BE f None Watchdog Timer Enabled C OO00h TFFFh All Power Up Timer Disabled ki FLASH Program Memory Master Clear Enabled Write Enable Data EE Protect Disabled i E White protection Off Brown Qut Detect BOD Enabled C OO000h DOFFh Protected C DOOOh D7FFh Protected Int Ext Switchover l Pu o C 0000h OFFFh Protected Fail safe Cik Monitor Enabled ha Low Voltage Program Enabled In Dircuit Debugger ICD Disabled e Calibration word Protect Cal Word 34H Brown out Reset Sel set to 4 OY ID Locations 3FFF 3FFF 3FFF 3FFF Clear Program Memory Size 8 K Device Status Idle Type
51. amp C Logic States PSSBD1 PSSBDO Pins P1B P1D Shutdown State Control bits define logic state on output pins P1B and P1D when CCP module is in shutdown state PSSBD1 PSSBDO Pins logic state 0 0 0 0 1 Jl 1 X High impedance Tri state Table 5 9 B amp D Logic States Previous Chapter Table of Contents Next Chapter http www mikroe com en books picmcubook ch5 15 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules e TOC e Introduction e Ch 1 e Ch e Ch e Ch e Ch e Ch e Ch e Ch e Ch e App A e App B e App C O O N wD Ui A W N Chapter 6 Serial Communication Modules EUSART The Enhanced Universal Synchronous Asynchronous Receiver Transmitter EUSART module is a serial I O communication peripheral It is also known as Serial Communications Interface SCI It contains all clock generators shift registers and data buffers necessary to perform an input or output serial data transfer independently of the device program execution As its name states apart from the usage of clock for synchronization this module can also establish asynchronous connection which makes it irreplaceable in some applications l For example in the event that it is A U Lu LA U LATU 1 difficult or impossible to provide special channels for clock and data transfer for example radio remote control or infrared the EUSART U
52. an interrupt while its input is connected to one of the microcontroller pins It is the RAO pin Referring to Fig 3 4 R 200 ohms C 1nF discharge time is approximately 30mS while the total consumption of the microcontroller as is 1000 times lower several hundreds of nanoamperes PICTGF887 Fig 3 4 Sleep Mode Port B and TRISB Register Port B is an 8 bit wide bidirectional port Bits of the TRISB register determine the function of its pins RB7 RB6 RBS RB4 RBS RB2 RBI RBO TRISB7 TRISB6 TRISBS TRISB4 TRISB3 TRISB2 TRISB1 TRISBO Bit is unimplemented Readable Writable bit After reset bit is unknown After reset bit is set Fig 3 5 Port B and TRISB register Similar to Port A a logic one 1 in the TRISB register configures the appropriate port pin as input and vice versa Six pins on this port can act as analog inputs AN The bits of the ANSELH register determine whether these pins act as analog inputs or digital inputs outputs RBO AN12 determined by bit ANS12 of the ANSELH register RB1 AN10 determined by bit ANSIO of the ANSELH register RB2 AN8 determined by bit ANS8 of the ANSELH register RB3 AN9 determined by bit ANS9 of the ANSELH register RB4 AN11 determined by bit ANS11 of the ANSELH register and RB5 AN13 determined by bit ANS13 of the ANSELH register Each Port B pin has an additional function related to some of the built in peripheral units which will
53. and e 0 Receiver operates normally ABDEN Auto Baud Detect Enable bit is used in asynchronous mode only e 1 Auto baud detect mode is enabled Bit is automatically cleared on baud rate detect and e 0 Auto baud detect mode is disabled In Short Sending data via asynchronous EUSART communication 1 The desired baud rate should be set by using bits BRGH TXSTA register and BRG16 BAUDCTL register and registers SPBRGH and SPBRG 2 The SYNC bit TXSTA register should be cleared and the SPEN bit should be set RCSTA register in order to enable serial port 3 On 9 bit data transmission the TX9 bit of the TXSTA register should be set 4 Data transmission is enabled by setting bit TXEN of the TXSTA register Bit TXIF of the PIR1 register is automatically set http www mikroe com en books picmcubook ch6 12 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules 5 If needed the bit TXEN causes an interrupt the GIE and PEIE bits of the INTCON register should be set 6 On 9 bit data transmission value of the ninth bit should be written to the TX9D bit of the TXSTA register and 7 Transmission starts by writing 8 bit data to the TXREG register Receiving data via asynchronous EUSART communication Baud Rate should be set by using bits BRGH TXSTA register and BRG16 BAUDCTL register and registers SPBRGH and SPBRG The SYNC bit TXSTA register sh
54. are Fosc ee _ Fosc ooo Desired Baud Rate Desired Baud Rate 64 SPBRGH SPBRG 1 SPBRGH SPBRG gt Calc Baud Rate Desired Baud Rate Error 75 Lo Desired Baud Rate SYNC 0 rosc 20 MHz Fose 18 432 MHz Fosc 11 0592 MHz Fosc 11 0532 MHz Actual Error j Actual Error Ellie Actual Error LEGE Actual Error Es Rate EE Rate value Rate value Rate value dec dec dec dec Baud Rate 1221 1 73 1200 0 00 1200 0 00 2404 0 16 2400 0 00 2400 0 00 9470 1 36 9600 0 00 9600 0 00 10417 0 00 10286 1 26 i 10165 2 42 19 53 1 73 19 2 0 00 19 2 0 00 57 6k 0 00 57 6 0 00 SYNC 20 BRGH 0 BRG16 0 Fosc 4 MHz Fosc 2 MHz Fosc 1 MHz Baud Rate E PBR dL PBF Em PBF E PRF Actual Error m Actual Error EDIT Actual Error EE Actual Error _ Of value E 0 value ze value i oy Hate lo dec Rate Ho dec Rate fo dec Rate Ho dec 300 300 0 16 300 0 16 51 1200 1202 0 16 1202 0 16 12 2400 2404 0 16 9600 10417 10417 0 00 19 2k 57 6k 115 2k http www mikroe com en books picmcubook ch6 9 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules SYNC 0 BRGH 1 Fosc 20 MHz Fosc 18 432 MHz Fosc 8 MHz Dv Actual Error ges Actual or Actual Actual Rate Yo Rate Rate Yo dec ac dec 1200
55. bank containing register TRISB Writes 1 to register W Number is moved to PORTB Port B bits rotates by one place lerr Callo subroutine DET AN Tests the firs port A Dic Ote applied to pin Go o label Mis applied to pin Coro label loop ojo CAN AS ak TACA Cal Wak ORC AR al RAT ahi Tak ah CA ARA tah E Vat tA Yas Daf ads TT Cah CAS EAS LAT RACIAL AR AR RADAR OS rat a TA Tah Af ras TAL IE AT CA Cat ASIA LAR Wat A Tat wall SUBROUTINES movwf TRISA banksel BORTE movlw fey 191810 1070 19 0 1E V movwf PORTE TOOP ie dlas POF TE Call DELAY logs o LSS eq SOE S IOC os goto ISI DELAY CET GONDUOLE S6 Soja elf counterl s Toop decfsz counter goto loe decfsz counter2 SISTE ao pil return end EXAMPLE 6 Moram u Clears arable eoe e Clears variable counterl Decrements variable Result as not 0 Go Decrements variable counter2 by 1 Result is not 0 EGO as lab ei Return Leon Sulorourimne DEL counter py I to Tabel Toop End XE Progr Aam TMRO as a counter defining new variables using relay This time TMRO is used as a counter The idea is to connect the counter input to one pushbutton so that it counts one pulse at a time upon every button press When the number of counted pulses becomes equal to the number in register TEST logic one voltage 5V will be applied to the PORTD 3 pin Since this voltage activates an electro mechanical relay this bit is called the same
56. based on a simple and efficient idea When an interrupt request arrives the flag bit is to be set first IEbit Interrupt gt Interrupt Flag Enabled Fig 2 8 Interrupt System Registers If the appropriate IE bit is not set 0 this event will be completely ignored Otherwise an interrupt occurs In case several interrupt sources are enabled it is necessary to detect the active one before the interrupt routine starts execution Source detection is performed by checking flag bits It is important to understand that the flag bits are not automatically cleared but by software during interrupt routine execution If this detail is neglected another interrupt will occur immediately upon return to the program even though there are no more requests for its execution Simply put the flag as well as IE bit remained set All interrupt sources typical of the PIC16F887 microcontroller are shown on the next page Note several things e GIE bit enables all unmasked interrupts and disables all interrupts simultaneously e PEIE bit enables all unmasked peripheral interrupts and disables all peripheral interrupts This does not concern Timer TMRO and port B interrupt sources To enable interrupt caused by changing logic state on port B it is necessary to enable it for each bit separately In this case bits of the IOCB register have the function to control IE bits http www mikroe com en books picmcubook ch2 4 of 12 5 3 2009 11 32 08 A
57. be explained in later chapters e All the port pins have built in pull up resistor which make them ideal for connection to push buttons switches and optocouplers In order to connect these resistors to the microcontroller ports the appropriate bit of the WPUB register should be set http www mikroe com en books picmcubook ch3 4 of 10 5 3 2009 11 32 31 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 3 I O Ports Legend RAV Readable Writable bit 1 After reset bit is set Fig 3 6 WPUB register Having a high level of resistance several tens of kilo ohms these virtual resistors do not affect pins configured as outputs but serves as a useful complement to inputs As such they are connected to CMOS logic circuit inputs Otherwise they would act as if they are floating because of their high input resistance Pin with pull up resistor Pin without pull up resistor Digital output Ld Digital input MCU Fig 3 7 Pull up resistors Apart from the bits of the WPUB register there is another bit affecting pull up resistors installation It is RBPU bit of the OPTION REG It is a general purpose bit because it affects installation of all Port resistors e If enabled each Port B bit configured as an input may cause an interrupt by changeing its logic state In order to enable pins to cause an interrupt the appropriate bit of the lOCB register should be set http www m
58. books picmcubook ch9 13 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set EXAMPLE 1 label CLRW Bello mella ale ito lat Pel las ratero DL 55 W 0x00 Z 1 CLRWDT Clear Watchdog Timer Syntax label CLRWDT Description Resets the watchdog timer and the WDT prescaler Status bits TO and PD are set Operation 0 gt WDT 0 gt WDT prescaler 1 gt TO 1 gt PD Operand Status affected TO PD Number of cycles 1 EXAMPLE label CLRWDT BECOOL LMSUICUCELOM ee Cul Lon Areo as ele come COME Complement f WDT WDT prescaler MDI Counter WDT prescaler TO 1 AD WDT prescaler counter x etl e 0x00 Lae http www mikroe com en books picmcubook ch9 14 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set Syntax label COMF f d Description The content of register f is complemented logic zeros 0 are replaced by ones 1 and vice versa If d w or d 0 the result is stored in W If d f or d 1 the result is stored in register f Operation f gt d Operand 0 x f lt 127 d 0 1 Status affected Z Number of cycles 1 EXAMPLE 1 label COMF REG w Before Instruction execution REG OxI 9109 94 0011 00155 complementing ec sm cs cbe enm REC III DT IND NES He W OxEC EXAMPLE 2 label COMF INDF f Before in
59. but useful __ config This directive is used to include config word in the program upon compiling It is not necessary because the same operation is performed by software for loading program into chip However do you have any idea which software will be used by the end user What options will be set by default You are the end user Do you know which program you will be using for MCU programming next year Make life easier for yourself take this directive as a necessary one and include it in your program http www mikroe com en books picmcubook appb 21 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples EXAMPLE 2 Using program loop and internal oscillator LFINTOSC This is a continuation of the previous example but deals with a bit more complicated problem The idea is to make the LED diodes on the port B blink A simple thing at first glance It is enough to periodically change logic state on the port B In this case numbers 01010101 and 10101010 are selected to change in the following way Set binary combination 01010101 on port B Remain in loop Replace existing bits combination on port B with 10101010 Remain in loop2 and Return to the step 1 and repeat the whole procedure mit nae A Do you know how fast this should be done It would be possible to observe changes on port B only if apart from the delays provided in loop1 and loop2 the whole process is slowed
60. by software It is done by clearing and resetting the CREN bit Note it is not possible to receive new data as far as the OERR bit is set If the STOP bit is zero 0 the FERR bit of the RCSTAregister detecting receive error will be set and To receive 9 bit data it is necessary to set the RX9 bit of the RCSTA register Receive Error Detection There are two types of errors which the microcontroller can automatically detect The first one is called Framing error and occurs when the receiver does not detect the STOP bit at the expected time Such error is indicated via the FERR bit of the RCSTA register If this bit is set it means that the last received data may be incorrect It is important to know several things A Framing error does not generate an interrupt by itself If this bit is set the last received data has an error A framing error bit set does not prevent reception of new data The FERR bit is cleared by reading received data which means that check must be done before data reading and The FERR bit cannot be cleared by software If needed it can be cleared by clearing the SPEN bit of the RCSTA register It will simultaneously cause reset of the whole EUSART system Another type of error is called Overrun Error The receive FIFO can hold two characters An overrun error will be generated if the third character is received Simply there is no space for another one byte and an error is unavoidable When this happens the OERR b
61. changing state on port B or RBO INT pin o 1 Enables all unmasked peripheral interrupts o 0 Disables all peripheral interrupts e TOIE TMRO Overflow Interrupt Enable bit controls interrupt enabled by TMRO overflow o 1 Enables the TMRO interrupt o 0 Disables the TMRO interrupt e INTE RBO INT External Interrupt Enable bit controls interrupt caused by changing logic state on pin RBO IN external interrupt o 1 Enables the INT external interrupt o 0 Disables the INT external interrupt e RBIE RB Port Change Interrupt Enable bit When configured as inputs port B pins may cause interrupt by changing their logic state no matter whether it is highto low transition or vice versa fact that something is changed only matters This bit determines whether interrupt is to occur or not o 1 Enables the port B change interrupt o 0 Disables the port B change interrupt e TOIF TMRO Overflow Interrupt Flag bit registers the timer TMRO register overflow when counting starts from zero o 1 TMRO register has overflowed bit must be cleared in software o 0 TMRO register has not overflowed e INTF RBO INT External Interrupt Flag bit registers change of logic state on the RBO INT pin o 1 The INT external interrupt has occurred must be cleared in software o 0 The INT external interrupt has not occurred e RBIF RB Port Change Interrupt Flag bit registers change of logic state of some port B input pins o 1 At least one
62. command it is important to give the LCD enough time to do its job Owing to the fact that the execution of the slowest command lasts for approximately 1 64mS it will be sufficient to wait approximately 2mS for LCD LCD Initialization The LCD is automatically cleared when powered up It lasts for approximately 15mS After this display is ready for operation The mode of operation is set by default It means that 1 Display is cleared 2 Mode DL 1 Communication through 8 bit interface N 0 Messages are displayed in one line F 0 Character font 5 x 8 dots 3 Display Cursor on off D 0 Display off U 0 Cursor off B 0 Cursor blink off http www mikroe com en books picmcubook appb 16 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples 4 Character entry ID 1 Displayed addresses are automatically incremented by 1 S 0 Display shift off Automatic reset is mostly done without any problems Mostly but not always If for any reason the power supply voltage does not reach full value within 10mS the display will start performing completely unpredictably If the voltage supply unit is not able to meet that condition or if it is needed to provide completely safe operation the process of initialization is applied Initialization among other things causes a new reset enabling display to operate normally Automatic reset is mostly done without any problems Mostly but n
63. communicates with peripheral components it may happen that data transfer fails for some reason In that case it is recommended to check the status of some bits which can clarify the problem In practice the state of these bits is checked by executing a short subroutine after each byte transmission and reception just in case WCOL SPCON 7 If you try to write a new data to the SSPBUF register while another data transmit receive is in progress the WCOL bit will be set and the contents of the SSPBUF register remains unchanged Write does not occur After this the WCOL bit must be cleared in software BF SSPSTAT 0 In transmit mode this bit is set when the CPU writes to the SSPBUF register and remains set until the byte in serial format is shifted from the SSPSR register In receive mode this bit is set when data or address is loaded to the SSPBUF register It is cleared when the SSPBUF register is read SSPOV SSPCON 6 In receive mode this bit is set when a new byte is received by the SSPSR register via serial communication whereas the previously received data has not been read from the SSPBUF register yet SDA and SCL Pins When SPP module is enabled these pins turns into Open Drain outputs It means that these pins must be connected to the resistors which at the other end are connected to positive power supply Fig 6 32 Open Drain Output Resistors http www mikroe com en books picmcubook ch6 26 of 27 5 3 2009 11 34 00
64. example if you design an electronic lock or an alarm it would be great to enable the user to create and enter a password but useless if it is lost every time the power supply goes off The ideal solution is the microcontroller with an embedded EEPROM Interrupt The most programs use interrupts in regular program execution The purpose of the microcontroller is mainly to react on changes in its surrounding In other words when some event takes place the microcontroller does something For example when you push a button on a remote controller the microcontroller will register it and respond to the order by changing a channel turn the volume up or down etc If the microcontroller spent most of its time endlessly a few buttons for hours or days It would not be practical The microcontroller has learnt during its evolution a trick Instead of checking each pin or bit constantly the microcontroller delegates the wait issue to the specialist which will react only when something attention worthy happens The signal which informs the central processor about such an event is called an INTERRUPT Central Processor Unit CPU As its name suggests this is a unit which monitors and controls all processes inside the microcontroller It consists of several smaller subunits of which the most important are http www mikroe com en books picmcubook ch0 16 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrolle
65. for this prog C System File s are extemal bo project use shook http www mikroe com en books picmcubook appa 17 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller Click Blink to include the document Blink asm into the project Program writing example The program writing procedure cannot start until all previous operations have been performed Program written below is a simple illustration of proj ect making Erogram to s t POE B Cans bo ou e ome pers leon LU Dare April o 2007 MU ls IAE GNO Hou eee IT Toe Slava Siac lat i Declaration and coniig uration Ok Che microcontroller S tS PROCESSOR Wome aio e kelo DI o e e net SOOM TCP OI T WDT E e TENETE CIN IRE O a alo en declaration S colo endc 0x20 pu OI POG ST memory Structure S ORG 055010 goto Main ORG 0x04 goro Main Main banksel TRIE CUr E FRISB banksel PORTE movlw OEE movwf PORTS Loop Gore Loop End Ne Ne Ne Ne Ne Ne Ne Ne Ne Pase free RAM locacion No cd alo Les RASSE Wwemcuog Arter reset qump to chis location lime eacmOE V ACTO No interrupt routine SILENCE EDS Program Selec Dank Containing TRISB Port EP COn roUe ac ON He Select bank containing PORTB W FF WO IN oo Jump to label Loop The program should be written to the Blink asm window or copied from disc by means of options copy paste When copied the program
66. here Hie Oe co eel practice devices operating in this way are very rare for example simple neon signs You guess among other components input pins will also be used in this example There is a schematic in the figure below while the program is on the next page Everything is still very simple http www mikroe com en books picmcubook appb 26 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples RB7 RBS LED 330R RBA m RB3 A 330R LED RB2 AME RAS U RB1 reo RBo LED 7 _330R DO i RE1 Vdd O VEC RE2 O Ves E Joa o Pori LED a 330R L osc i aw saat osc2 RDA LED ARCO RCT RC1 roe AA 330R SMH E JH RC2 ROS LED LI 3 d RC3 RCA dd RDO RD3 LED 330R RD1 RD2 GND GND At the beginning of the program immediately upon defining variables the microcontroller pins are configured by using registers TRISA and TRISB In the main program one bit on port B is set first Then the contents of this register is constantly moved by one place to the left instruction rlf PORTB It gives us the impression that the lit LED diodes is moving To make it visible the whole process must be slow enough Press on the push button STOP stops the movement and the program remains in loop3 Delay is provided by means of a nested loop This time it i
67. is recommended to check carefully prior installation which of them iS in use e For each microcontroller pin there is a maximum current limitation it can receive or give Because of this if several displays are connected to the microcontroller it is rec ommended to use so called Low current LEDs using only 2mA for operation and e Display segments are usually marked with the letters from a to g but there is no fast rule indicating to which micro controller pins they should be connected For this reason it is very important to check connecting prior to commencing program writing or designing a device Displays connected to the microcontroller usually occupy a large number of valuable I O pins which can be a big problem especially when it is needed to display multi digital numbers The problem is more than obvious if for example it is needed to display two 6 digit numbers a simple calculation shows that 96 output pins are needed in this case This problem has a solution called MULTIPLEXING Here is how an optical illusion based on the same operating principle as a film camera is made Only one digit at a time is active but they change their state so quickly that one gets impression that all digits of a number are active simultaneously http www mikroe com en books picmcubook appb 8 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples dx Low current common cathode displays
68. is up to the user to follow the rules of their usage The way of writing instructions is also called instruction syntax The instructions movlp and gotto in the following example are recognized by the PIC16F887 microcontroller as an error since they are not correctly written Correctly written commands movlw H FF goto Start Incorrectly written commands movip H FF qotto Start OPERANDS An operand is a value an argument upon which the instruction named by mnemonic operates The operands may be a register a variable a literal constant a label or a memory address Using operand moviw H 01F movwt LEVEL operand as a variable LEVEL operand as a constant stored in the microcontroller memory DIRECTIVES Unlike instructions being written to on chip program memory after compilation directives are commands of assembly language itself and do not directly affect the operation of the microcontroller Some of them must be used in every program while others are only used to facilitate or enhance the operation Directives are written to the column reserved for instructions The rule which must be observed allows only one directive per program line This section covers only a few of the most commonly used directives It would certainly take up too much space and time to describe all the directives recognized by the MPLAB program Anyway a complete list containing all directives which the MPLAB assembler can underst
69. mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples movlw ENE 2 Binary number 10000 as moved uo WM movw ft POROS Number is moved to PORTB movlw I m pu Number hFF is moved to W movw f counter2 Number is moved to variable counter2 Koa movlw DEB Number hFF is moved to W movw E counterl gt Number is moved to counter toopi decfsz counterl Decrements counter by 1 If result as 0 SOTO Toop okip mex dns eM deb CIT decfsz counter2 Decrements counter2 by 1 If result as 0 gore OOP A ekip mes Tg esie e TO movlw IEA O Binary number 00001111 is moved to W movw ft PORTE Number is moved to PORTB movlw MAREN Number hFF is moved to W movw f counter2 Number 15s moved to variable counter loop4 movlw IATA Number hER Xs moved to W movw ft Cio exe db Number is moved to variable counterl Toop decfsz counterl Decrements counterl by 1 If result is O okip Nee sie n IMG s a CDI Gor OOPS decfsz counter2 Decrements cour cnt by 1 If result is D goro loop4 Skip Next siet en goro LOOP n June see akabel sloore end ECO C Toe Oo ikem Example 4 Using timer TMRO and Interrupts If you have read the previous example you would have noticed a disadvantage of providing delays using loops In all these cases the microcontroller is captive and does nothing It simply waits for some time to pass Such wasting of time is an unacceptable luxury and some other m
70. of programs and electronic circuits having this purpose can be found on the Internet Do as follows open hex code document set a few parameters and click the icon for compiling After a while a sequence of zeros and ones is to be programmed into the microcontroller through the serial connection cable and programmer hardware There is nothing else to be done except for placing the programmed chip into the target device In case it is necessary to make some changes in the program the previous procedure may be repeated an unlimited number of times Is this a happy ending This section briefly describes the use of MPLAB and programmer software developed by Mikroelektronika Everything is very simple You have already installed MPLAB havena t you Open a new project and a new document with extension asm http www mikroe com en books picmcubook appc 3 of 7 5 3 2009 11 36 25 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix C Development Systems ee mne mem eme e em es Ca EL ee e a ou d o Ce i A 7 Chlock DE r etak FAH A NT rre Liberte L EPECHTE znt amiz TESTIS RE A b pe vrakrura progra memcrijse Of DE 2 Baralt vector 7 PLATE ge i Aaa EHETE IH me FIF FIBA TER TEIL desto Baa io fee Lite Pept CUA TEIE TE TEE kark nam j TETEA i Poel progra rar TELLA 0 TO tet TRIBA Pa clrt TEITE L CEFRIL Lh ide d o RETA CFE cir car e ES A oe PA TT CER Ciel 1 lm
71. of subroutine The program in the following example performs addition of two 2 byte variables ARG1 and ARG2 and moves result to the variable RES When 2 byte variables are used it is necessary to define higher and lower byte for each of them The program itself is very simple It first adds lower bytes of variables ARG1 and ARG2 and higher afterwards If the sum of addition of two lower bytes is greater than 255 maximal byte value the remainder is added to the RESH variable Program eo selec revolt s oo es AIN CODE Apri AS O MU PETOS PROCESSORS 999 gt Derinin processor inelude pL6toov7 uvnet 5 Microchip INC database TUIS ACE ORE sm IDE ES E EAN Ip Oe Crock TORZO Beginning of RAM ARG1H Argument 1 higher byte ARGIL Argument 1 lower byte ARG2H Argument 2 higher byte ARG2L Argument 2 lower byte RESH Result higher byte RESL Result lower byte endc End of variables ORG 0x00 Reset vector goro SICUT Ste Write values to variables mov lw Qt d ARG1 0x0104 movwft ARG1H movlw 0x04 movwt ARG1L movlw OOO ARG2 0x0705 movwt ARG2H movlw USOS movwt ARG2L http www mikroe com en books piemcubook appa 9 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller Main Main program call Add16 Call Slo out Ve scio copien Loop Remain here Add16 zem OX bue ine ES add Evo lo OLE mummers oie E RESH RESA 0 mov ARG1L w w ARGIL add
72. of the microcontroller In case the brown out circuit is not built in a simple external circuit for brown out reset can be connected to this pin Timers Counters The microcontroller oscillator uses quartz crystal for its operation Even though it is not the simplest solution there are many reasons to use it Namely the frequency of such oscillator is precisely defined and very stable the pulses it generates are always of the http www mikroe com en books picmcubook ch0 20 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Fig 0 27 Timers Counters same width which makes them ideal for time measurement Such oscillators are used in quartz watches If it is necessary to measure time between two events it is sufficient to count pulses coming from this oscillator That is exactly what the timer does Most programs use these miniature electronic stopwatches These are commonly 8 or 16 bit SFRs and their content is automatically incremented by each coming pulse Once a register is completely loaded an interrupt is generated If the timer registers use an internal quartz oscillator for their operation then it is possible to measure time between two events if the register value is T1 at the moment measurement has started and T2 at the moment it has finished then the elapsed time is equal to the result of http www mikroe com en books picmcubook ch0
73. operation is shown in figure 5 4 below If a logic zero 0 represents switch off and logic one 1 represents switchon the power that the load consumes will be directly proportional to the pulse duration This ratio is often called Duty Cycle http www mikroe com en books picmcubook ch5 3 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules Fig 5 4 CCP1 in PWM mode Another example common in practice is the usage of PWM signals in the circuit for generating signals of arbitrary waveforms for example sinusoidal waveform See figure 5 5 below PWM signal before filtration p RC filter PWM signal after filtration gt Fig 5 5 CCP1 in PWM mode with filtration Devices which operate in this way are often used in practice as switching regulators which control the operation of motors speed acceleration deceleration etc http www mikroe com en books picmcubook ch5 4 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules Bits of CCP1CON Register B ani i D F EFC Pe A m TMR2 PR2 aj a hh A aSa p d Pin Comparator RC2 CCP1 if TRISC 2 _Reset Bits T2CKS1 T2CKPSO of T2CON register Timer T2 prescaler Comparator lem uf LI Fig 5 6 PWM module The figure above shows the block diagram of the CCP1 module setup in PWM
74. oscillator is not factory calibrated and operates at 31kHz http www mikroe com en books picmcubook ch8 6 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits Similar to the external oscillator the internal one can also operate in several modes The mode is selected in the same Way as in case of external oscillator using bits of the Config Word register In other words everything is performed within PC software immediately before program writing to the microcontroller starts Internal oscillator in INTOSC mode In this mode the OSCI pin is available as general purpose l O while the OSC2 pin outputs selected internal oscillator frequency divided by 4 0501 Pin Fig 8 11 INTOSC Mode NO Internal oscillator in INTOSCIO mode In this mode both pins are available for general purpose O Fig 8 12 INTOSCIO Mode IO OSC2 Pin yo Internal Oscillator Settings The internal oscillator consists of two separate circuits 1 The high frequency internal oscillator HFINTOSC is connected to the postscaler frequency divider It is factory calibrated and operates at 8MHz Using postscaler this oscillator can output clock sources at one of seven frequencies which can be selected via software using the IRCF2 IRCF1 and IRCFO pins of the OSCCON register The HFINTOSC is enabled by selecting one of seven frequencies between 8 MHz and 125 k
75. problem is solved by setting such instructions at addresses ending by xx00h This enables the program to jump up to 255 locations If longer jumps are executed by this instruction the PCLATH register must be incremented by 1 for each PCL register overflow e On subroutine call or jump execution instructions CALL and GOTO the microcontroller is able to provide only 11 bit addressing For this reason similar to RAM which is divided in banks ROM is divided in four pages in size of 2K each Such instructions are executed within these pages without any problems Simply since the processor is provided with 11 bit address from the program it is able to address any location within 2KB Figure 2 17 below illustrates this situation as a jump to the subroutine PP1 address However if a subroutine or jump address are not within the same page as the location from where the jump is two missing higher bits should be provided by writing to the PCLATH register It is illustrated in figure 2 17 below as a http www mikroe com en books picmcubook ch2 10 of 12 5 3 2009 11 32 08 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 2 Core SFRs jump to the subroutine PP2 address PCLATH 4 3 00 01 10 11 Q O QS p noo a Instructions RETURN RETLW Or RETFIE Fig 2 17 PCLATH Registers In both cases when the subroutine reaches instructi
76. regisier W banksel EEDAT http www mikroe com en books picmcubook appb 40 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples movwt banksel perf psf bef SE TE SNO Gore mov lw movwt mov lw movwt psf Erse goto DSi Der OO end EXAMPLE 13 EEDAT BECON EECON1 EECON1 INTCON INTCON S DA EECON2 H AA EECON2 EECON1 EECON1 SU INTCON EECON1 Loop Writes data to temporary register EEPGD WREN Write enabled GIE All interrupts disabled GIE WR WR Wait for write to complete GIE Interrupt enabled WREN tests pus h button again EN O ao ua am Two digit LED counter multiplexing In this example the microcontroller operates as a two digit counter Concretely the variable Dval is decremented slow enough to be visible and its value is displayed on twodigit LED display 99 0 The challenge is to enable binary number to be converted in decimal one and split it in two digits tens and ones Besides since the LED display segments are connected in parallel it is necessary to ensure that they change fast in order to make impression of simultaneous light emission time division multiplexing Remember that in electronics multiplexing allows several analog signals to be processed by one analog todigital converter ADC In this very case time division multiplexing is performed by the timer TMRO while binary to de
77. row In case of 4 bit initialization the procedure is as follows Wait more than15mS RS RW D7 D6 D5 D4 Bit BF cannot be checked before this instruction 0 00 01 1 Display is set to 8 bit mode Display is set to 8 bit mode RS RW D7 D6 D5 D4 Bit BF cannot be checked before this instruction 0 00 01 1 Display is set to 8 bit mode Wait more than 100uS RS RW D7 D6 D5 D4 Bit BF cannot be checked before this instruction Bit BF can be checked after the following instructions RS R W D7 D6 D5 D4 Start operation in 4 bit mode After this point 4 higher bits are written first 4 lower afterwards The number of display lines and character font have to be defined and these values cannot be changed after this point Display off Display clear Set entry mode http www mikroe com en books picmcubook appb 18 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples Initialization ends EXAMPLE 1 Writing header and configuring I O pins The only purpose of this program is to turn on a few LED diodes on port B It is nothing special Anyway use this example to study what a real program looks like The figure below shows a connection scheme while the program is on the next page VCC LED gt s as i LED y MR i pl AN e 330R d LED AA a O LED y 220K i vcc c C TI I LED AA 330R Oo mos
78. s microprocessors Intel kept on developing it and in April 1974 it launched an 8 bit processor called the 8080 It was able to address 64Kb of memory had 75 instructions and initial price was 360 Another American company called Motorola quickly realized what was going on so they launched 8 bit microprocessor 6800 Their chief constructor was Chuck Peddle Apart from the processor itself Motorola was the first company that also manufactured other peripherals such as the 6820 and 6850 At that time many companies recognized the greater importance of microprocessors and began their own development Chuck Peddle left Motorola to join MOS Technology and kept working intensively on developing microprocessors At the WESCON exhibition in the USA in 1975 a crucial event in the history of the microprocessors took place MOS Technology announced that it was selling processors 6501 and 6502 at 25 each that interested customers could purchase immediately It was such a sensation that many thought it was a kind of fraud considering that competing companies were selling the 8080 and 6800 at 179 each On the first day of the exhibit in response to the competitor both Motorola and Intel cut the prices of their microprocessors to 69 95 Motorola accused MOS Technology and Chuck Peddle of plagiarizing the protected 6800 Because of that MOS Technology gave up further manufacture of the 6501 but kept manufacturing the 6502 It was the 8 bit microprocessor with 5
79. should be compiled into executable HEX format by using option PROJ ECT gt BUILD ALL A new window appears The last sentence is the most important because it tells us whether compiling has succeeded or not Clearly BUILD SUCCEEDED message means that no error occurred and compiling has been successfully done In case an error occurs it is necessary to click twice on the message referring to it in the Output window which automatically switch you over to assembly program directly to the line where the error has occurred http www mikroe com en books picmcubook appa 18 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller m Proba MPLAB DECENT Cae Ad 7 Release Y Ei up hA 58 Checksum x265H MProbamew v EH amp Gli Proba mca TIE E source Files AOS EE Blink acm PEOgEAm a zetovan e pinova porta B na logicku jedinicu Header File Verzija 1 0 Datum 25 04 2007 BCU PICL6F amp 87 Pisac Petar Petrovic 3 Object Fies Library Files C Linker Scripts PROCESSOR L amp f amp B7 C Other Files finclude pLl f amp B7 inc e Daklar amp acija i konfigurisanja mikrckonterolera CONFIG CP OFF amp NWDT OFF a PURTE ON 4 XT 05 T Deklarmcija promenjivih mE Cblock Oni Pacetuak PRAMI 1 ande Nena pro menijivih A Zrruktura programshe nemorije DEG Ds 00 i Beget vector Hain Pozle rcezeta skoci na
80. signal with frequency Fosc 4 will appear on the OSC2 pin Furthermore that frequency becomes operating frequency of the microcontroller i e the speed of instruction execution VCC E External oscillator If it is required to synchronize the operation of several microcontrollers or if for some reason it is not possible to use any of the previous schematics a clock signal may be generated by an external oscillator Refer to the figure below Es agr cm UL ES E A ADDITIONAL COMPONENTS Regardless of the fact that the microcontroller is a product of modern technology it is of no use without being connected to additional components Simply the appearance of voltage on the microcontroller pins mean nothing if not used for performing certain operations turn something on off shift display etc This section intentionally covers only the most commonly used additional components in practice such as resistors transistors LED diodes LED displays LCD displays and RS232 communication circuits SWITCHES AND PUSH BUTTONS There is nothing simpler than switches and push buttons This is definitely the simplest way of detecting the appearance of a voltage on the microcontroller input pin and there is no need for additional explanation of how these components operate Nevertheless it is not so simple in practice Then what is it all about http www mikroe com en books picmcubook appb 4 of 54 5 3 2009 11 36 02 AM mikr
81. the CCP1 pin 0 1 1 1 Capture mode http www mikroe com en books picmcubook ch5 7 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules Interrupt request arrives and bit CCPIIF is set on match Bit CCPIIF is set and timers 1 or 2 registers are cleared 1 0 0 0 1 0 0 1 1 0 1 0 1 0 if 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 Every 16th rising edge on the CCP1 pin Compare mode Output and CCP1IF bit are set on match Compare mode Output is cleared and CCPIIF bit is set on match Compare mode Compare mode PWM mode Pins P1A and P1C are active high Pins P1B and P1D are active high PWM mode Pins P1A and P1C are active high Pins P1B and P1D are active low PWM mode Pins P1A and P1C are active low Pins P1B and P1D are active high PWM mode Pins P1A and P1C are active low Pins P1B and P1D are active low Table 5 5 Modes of Operations CCP2 Module Excluding the different names of registers and bits this module is a very good copy of the CCP1 module setup in normal mode previously discussed There is only one true difference between their modes when CCP2 operates in Compare mode That difference refers to the timer T1 reset signal Namely if A D converter is enabled at the moment the values of the TMR1 and CCPR2 registers match the timer T1 reset signal will automatically start A D conversion Logic Pin RC2 CCP2 CCP2M3 TRISC 1 CCP2M2 CC
82. the effect might be spectacular ANODE ET IL 20 ili 2 mA y Flat on CATHODE body flange LED DISPLAY Basically LED display is nothing more than several LEDs moulded in the same plastic case There are many types of displays composed of several dozens of built in diodes which can display different symbols The most commonly used is so called 7 segment display It is composed of 8 LEDs 7 segments are arranged as a rectangle for symbol displaying and there is an additional segment for decimal point displaying In order to simplify connection anodes or cathodes of all diodes are connected to the common pin so that there are common anode displays and common cathode displays respectively Segments are marked with the letters from a to g plus dp as shown in figure below On connecting each diode is treated separately which means that each must have its own current limiting resistor http www mikroe com en books picmcubook appb 7 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples Here are a few important things that one should pay attention to when buying LED displays e Depending on whether anodes or cathodes are connected to the common pin there are common anode displays and common cathode displays The figure above shows a common anode display Looking at physical features there is no difference between these displays at all so it
83. the figure 7 11 shows a simplified schematic of the circuit affected by the bits of this register http www mikroe com en books picmcubook ch7 10 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules C121N0 C12IN1 C121N2 C121N3 Comparator C2 E co C20 UT C2Vint Fig 7 11 Comparator C2 Schematic Diagram C20N Comparator C2 Enable bit enables comparator C2 e 1 Comparator C2 is enabled and e 0 Comparator C2 is disabled C20UT Comparator C2 Output bit is comparator C2 output If C2POL 1 comparator output inverted e 1 Analog voltage at ClVin is lower than analog voltage at C1Vin and e 0 Analog voltage at ClVin 4 is higher than analog voltage at C1Vin If C2POL 0 comparator output non inverted e 1 Analog voltage at ClVin 4 is higher than analog voltage at C1Vin and e 0 Analog voltage at C1Vin is lower than analog voltage at C1Vin C20E Comparator C20utput Enable bit e 1 Comparator C20UT output is connected to the C20UT pin and e 0 Comparator output is internal only n order to enable the C20UT bit to be present on the pin two conditions must be met C20N 1 comparator must be on and the corresponding TRIS bit 20 pin must be configured as output C2POL Comparator C2 Output Polarity Select bit enables comparator C2 out put state to be inverted e 1 Comparator C2 output is inverted and
84. the first pulse triggered by contact bounce This solution is more expensive SPDT switch but the problem is definitely solved In addition to these hardware solutions there is also a simple software solution When a program tests the state of an input pin and detects a change the check should be done one more time after a certain delay If the program confirms http www mikroe com en books picmcubook appb 5 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples the change it means that a switch push button has changed its position The advantages of such solution are obvious it is free of charge effects of noises are eliminated and it can be applied to the poorer quality contacts as well RELAY A relay is an electrical switch that opens and closes under the control of another electrical circuit It is therefore connected to output pins of the microcontroller and used to turn on off high power devices such as motors transformers heaters bulbs etc These devices are almost always placed away from the boards sensitive components There are various types of relays but all of them operate in the same way When a current flows through the coil the relay is operated by an electromagnet to open or close one or many sets of contacts Similar to optocouplers there is no galvanic connection electrical contact between input and output circuits Relays usually demand both higher
85. the operation of one particular model belonging to high middle class It is about PIC16F887 powerful enough to be worth attention and simple enough to be easily presented to everybody Table of Contents Next Chapter http www mikroe com en books picmcubook ch0 30 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview e TOC e Introduction e Ch e Ch e Ch e Ch e Ch e Ch e Ch e Ch e Ch E O O N O Ui A UW N e App A e App B e App C Chapter 1 PIC16F887 Microcontroller Device Overview The PIC16F887 is one of the latest products from Microchip It features all the components which modern microcontrollers normally have For its low price wide range of application high quality and easy availability it is an ideal solution in applications such as the control of different processes in industry machine control devices measurement of different values etc Some of its main features are listed below RISC architecture o Only 35 instructions to learn o All single cycle instructions except branches Operating frequency 0 20 MHz Precision internal oscillator o Factory calibrated o Software selectable frequency range of 8MHz to 31KHz Power supply voltage 2 0 5 5V o Consumption 220uA 2 0V 4MHz 11uA 2 0 V 32 KHz 50nA stand by mode Power Saving Sleep Mode Brown out Reset BOR with software control option
86. to receive new data LCD Connecting Depending on how many lines are used for connecting the LCD to the microcontroller there are 8 bit and 4 bit LCD modes The appropriate mode is selected at the beginning of the operation in this process called initialization 8 bit LCD mode uses outputs DO D7 to transfer data as explained on the previous page The main purpose of 4 bit LED mode is to save valuable I O pins of the microcontroller Only 4 higher bits D4 D7 are used for communication while others may be unconnected Each piece of data is sent to the LCD in two steps four higher bits are sent first normally through the lines D4 D7 and four lower bits are sent afterwards Initialization enables the LCD to link and interpret received bits correctly Microcontroller Can be connected In 4 bit mode is LI to Ground MI BEN left unconnected HA o sv Contrast 330 LED backlight l I 3535353332235 ooo Data is rarely read from the LCD it is mainly transferred from the microcontroller to LCD so it is often possible to save an extra I O pin by simple connecting R W pin to the Ground Such saving has its price Messages will be normally displayed but it will not be possible to read the busy flag since it is not possible to read the display as well Fortunately there is a simple solution After sending a character or a
87. up resistors configurable by software Usually each I O port is under control of another SFR which means that each bit of that register determines the state of the corresponding microcontroller pin For example by writing logic one 1 to one bit of that control register SFR the appropriate port pin is automatically configured as input It means that voltage brought to that pin can be read as logic 0 or 1 Otherwise by writing zero to the SFR the appropriate port pin is configured as an output Its voltage OV or 5V corresponds to the state of the appropriate bit of the port register Memory Unit Memory is part of the microcontroller used for data storage The easiest way to explain it is to compare it with a filing cabinet with many http www mikroe com en books picmcubook ch0 14 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers drawers Suppose the drawers are clearly marked so that it is easy to access any of them It is easy enough to find out the contents of the drawer by reading the label on the front of the drawer Each memory address corresponds to one memory location The content of any location becomes known by its addressing Memory can either be written to or read from There are several types of memory within the microcontroller Write Read Read Only Memory ROM ROM Read Only Memory is used to permanently save the program being execu
88. used to temporarily hold the data written to the SSPRS until the received data is ready Upon receiving all 8 bits of data that byte is moved to the SSPBUF register This double buffering of the received data SSPBUF allows the next byte to start reception before reading the data that was just received Any write to the SSPBUF register during transmission reception of data will be ignored Since having been the most accessed this register is considered the most important from the programmers point of view Namely if mode settings are neglected data transfer via SPI actually means to write and read data from this register while another acrobatics such as moving registers are automatically performed by hardware SSPSR Fig 6 14 SPI Mode In short Prior to initializing the SPI it is necessary to specify several options Master mode SCK pin is the clock output Slave mode SCK pin is the clock input Data input phase middle or end of data output time SMP bit Clock edge CKE bit Baud Rate only in Master mode and Slave select mode Slave mode only http www mikroe com en books picmcubook ch6 15 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules Step 1 Data to transmit should be written to the buffer register SSPBUF Immediately after that if the SPI module operates in master mode the microcontroller will automatical
89. window is very complicated which normally affects the price From our point of view unfortunately negative Flash memory This type of memory was invented in the 80s in the laboratories of INTEL and were represented as the successor to the UV EPROM Since the contents of this memory can be written and cleared practically an unlimited number of times the microcontrollers with Flash ROM are ideal for learning experimentation and small scale manufacture Because of its popularity the most microcontrollers are manufactured in flash versions today So if you are going to buy a microcontroller the type to look for is definitely Flash Random Access Memory RAM Once the power supply is off the contents of RAM Random Access Memory is cleared It is used for temporary storing data and intermediate results created and used during the operation of the microcontroller For example if the program performs an addition of whatever it is necessary to have a register representing what in everyday life is called the sum For that purpose one of the registers in RAM is called the sum and used for storing results of addition Electrically Erasable Programmable ROM EEPROM The contents of the EEPROM may be changed during operation similar to RAM but remains permanently saved even upon the power supply goes off similar to ROM Accordingly an EEPROM is often used to store values created during operation which must be permanently saved For
90. 1 3 PIC16F887 Block Diagram Pin Description As seen in Fig 1 1 above the most pins are multi functional For example designator RA3 AN3 Vref Y C1IN 4 for the fifth pin specifies the following functions e RA3 Port A third digital input output e AN3 Third analog input e Vref Positive voltage reference e C1IN Comparator Clpositive input This small trick is often used because it makes the microcontroller package more compact without affecting its functionality These various pin functions cannot be used simultaneously but can be changed at any point during operation The following tables refer to the PDIP 40 microcontroller General purpose input Port E RE3 MCLR Vpp 1 Reset pin Low logic level on this pin resets microcontroller Vpp Programming voltage RAD General purpose I O port A ANO A D Channel 0 input ULPWU Stand by mode deactivation input C121NO Comparator C1 or C2 negative input RAT General purpose I O port A RA1 AN1 C12IN1 3 AN1 A D Channel 1 C121N1 Comparator C1 or C2 negative input RA General purpose I O port A AN2 A D Channel 2 A D Negative Voltage Reference RAO ANO ULPWU C12INO 2 RA2 AN2 Vref CVref C2lN A vref input CVref Comparator Voltage Reference Output C2IN Comparator C2 Positive Input AN3 A D Channel 3 Vref A D Positive Voltage Reference Input C1IN Comparator C1 Positive Input RA4 General purpose I O port A RAA TOCKI C1OUT 6 TOCKI Timer TO Clock Input CTOUT Comparator C1 Output
91. 1 Input banko Macro for bank O selection endm Eod ene tee dete output macro argl arg2 MIE LCI O Ole O che bank1 Bank Containing IRIS registers oci argil arg Clear the specified bit 0 0utput banko Macro for bank O selection endm End of macro Macro with arguments may be called in the following way output TRISB 7 Pin RBY is configured as output When calling this macro the first specified argument TRISB is replaced by the first argument argl in macro definition Similarly number 7 is replaced by the argument arg2 and the following code is generated BSE SIATUS REO Set RPO bit BANKI bet MEAN SU REI Reset RPO bit BANK1 bet RESI 7 PIC OIE Meneses RB els Ole joe ber STATUS REO Clear RPO bit BANKO DCE STATUS REI Clear RPI bit BANKO It is clear at first sight that the program becomes more legible and flexible by using macros The main disadvantage of macro is that it occupies a lot of memory space because every macro name in a program is replaced by its predefined code Owing to the fact that programs often use macro everything is more complicated if it is long calle macro label T Macro calle local Exit Define local Label within macro lone ae CO mo to Exit call label If C 1 call subroutine at address Label out of macro e Local Label within macro endm PUDO Cue macro http www mikroe com en books piemcubook appa 8 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Micr
92. 10h 11h 12h 13h 14h 15h 16h 17h 18h 18h 14h 18h 18h 10h 1Eh 1Fh 20h TFh Name CCP1CON RESTA RCREG CCPR2L CCPR2H CCP2CON _ ADRESH ADCONO General Purpose Registers 96 bytes Bank 0 CCPR1TH TXREG Addr 80h 81h 82h 83h 84h 85h 86h Bh 88h 89h SAR 8Bh 88h DA SEh SFh 90h 91h 92h 93h 94h 95h 96h 97h 96h 99h SAh 9Bh 9Ch 9Dh SEh 8Fh AOR FFh Name OPTION REG ADCON1 General Purpose Registers 80 bytes Bank 1 Addr 100h 101h 102h 103h 104h 105h 106h 10h 108h 109h 10Ah 10Bh 10Ch 10Dh T Eh 10Fh 110h 1 Fh Table 1 2 Address Banks http www mikroe com en books picmcubook ch1 10 of 14 5 3 2009 11 31 25 AM Name INDF TMRO PCL STATUS FSR WDTCON PORTB CM1CONO CM2CONO CM2CON1 PCLATH INTCON EEDAT EEADR EEDATH EEADRH General Purpose Registers 96 bytes Bank 2 Addr 180h 181h 18h 183h 184h 185h 186h 18h 188h 188h 18Ah 18Bh 18Ch 18Dh 18Eh 18Fh 190h 1EFR Name INDF OPTION REG PCL STATUS FSR SRCON TRISB BAUDCTL ANSEL ANSELH PCLATH INTCON EECON1 EECON2 Not Used Not Used General Purpose Registers 96 bytes Bank 3 mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview SFRs bank 0
93. 4 3 Postscaler Rate TMR2ON Timer On bit turns the timer TMR2 on e 1 Timer T2 is on and e O Timer T2 Is off T2CKPS1 T2CKPSO Timer2 Clock Prescale bits determine prescaler rate T2CKPSI T2CKPSO Prescaler Rate 0 0 eA 0 1 1 4 1 X 1 16 Table 4 4 Prescaler Rate When using the TMR2 timer one should know several specific details that have to do with its registers Upon power on the PR2 register contains the value FFh Both prescaler and postscaler are cleared by writing to the TMR2 register Both prescaler and postscaler are cleared by writing to the T2CON register and On any reset both prescaler and postscaler are cleared Previous Chapter Table of Contents Next Chapter http www mikroe com en books picmcubook ch4 12 of 12 5 3 2009 11 32 57 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules TOC Introduction en il Ch Ch Ch Ch Ch Ch Ch Ch App A App B App C O O N oO Ui A W N Chapter 5 CCP Modules The abbreviation CCP stands for Capture Compare PWM The CCP module is a peripheral which allows the user to time and control different events Capture Mode allows timing for the duration of an event This circuit gives insight into the current state of a register which constantly changes its value In this case it is the timer TMRI register Compare Mode compares values contained in two registers at some point One of them is the timer TMR1 regi
94. 5 7 q 50 Ei zr RJ O If the program contains variables it is good to monitor their values as well Each variable is assigned a window Watch Windows by clicking VIEW gt WATCH option After all variables and registers of interest become available on the simulator working area the process of simulation can start The next instruction may be either Step into or Step over depending on whether you want to step into subroutine or not The same instructions may be set by using keyboard push buttons lt F7 gt or F8 generally all important instructions have the corresponding pushbuttons on the keyboard Previous Chapter Table of Contents Next Chapter http www mikroe com en books picmcubook appa 21 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples e TOC e Introduction e Ch 1 e Ch 2 e Ch 3 e Ch 4 e Ch 5 e Ch 6 e Ch 7 e Ch 8 e Ch 9 e App A e App B e App C Appendix B Examples The purpose of this chapter is to provide basic information about microcontrollers that one needs to know in order to be able to use them successfully in practice This chapter therefore does not contain any super interesting program or device schematic with amazing solutions Instead the following examples are more proof that program writing is neither a privilege nor a talent issue but the ability of simply putting puzzle pieces together using directives
95. 5 1 CCP1 Module In Compare mode if enabled by software the timer TMR1 reset may occur on match Besides the CCP1 module can generate PWM signals of varying frequency and duty cycle Bits of the CCP1CON register controls the CCP1 module CCP1 in Capture mode In this mode the timer register TMR1 consisting of TMR1H and TMRI1L is copied to the CCP1 register consisting of CCPR1H and CCPRIL in the following situations Every falling edge 1 0 on the RC2 CCP1 pin Every rising edge 0 1 on the RC2 CCP1 pin Every 4th rising edge 0 1 on the RC2 CCP1 pin and Every 16th rising edge 0 1 on the RC2 CCP1 pin The combination of the four bits CCP1M3 CCP1MO of the control register determines which of these events will trigger 16 bit data transfer In addition the following conditions must be met e RC2 CCP1 pin must be configured as input and e TMR1 module must operate as timer or synchronous counter 4 Flag bit CCP1IF Prescaler 1 1 1 4 146 Pin RC2 CCP1 CCP1M2 CCP1M1 CCP1MO Fig 5 2 CCP1 in Capture mode The flag bit CCP1IF is set when a capture is made If it happens and if the CCPIIE bit of the PIE register is set then an interrupt occurs When the Capture mode is changed an undesirable capture interrupts may be generated In order to avoid that both a http www mikroe com en books picmcubook ch5 2 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontr
96. 6 instructions and ability to directly address 64Kb of memory Due to low price 6502 became very popular so it was installed into computers such as KIM 1 Apple I Apple Il Atari Commodore Acorn Oric Galeb Orao Ultra and many others Soon several companies began manufacturing the 6502 Rockwell Sznertek GTE NCR Ricoh Commodore took over MOS Technology In the year of its prosperity 1982 this processor was being sold at a rate of 15 million processors per year Other companies did not want to give up either Frederico Faggin left Intel and started his own company Zilog Inc In 1976 Zilog announced the Z80 When designing this microprocessor Faggin made a crucial decision The 8080 had already been developed and he realized that many would remain loyal to that processor because of the great expenditures which rewriting of all the programs would result in Accordingly he decided that a new processor had to be compatible with the 8080 i e it had to be able to perform all the programs written for the 8080 Apart from that many other features have been added so that the Z80 was the most powerful microprocessor at that time It was able to directly address 64Kb of memory had 176 instructions a large number of registers a built in option for refreshing dynamic RAM memory a single power supply greater operating speed etc The Z80 was a great success and everybody replaced the 8080 by the Z80 Certainly the Z80 was commercially the most successful 8
97. 7 d 0 1 Status affected C DC Z Number of cycles 1 EXAMPLE label SUBWF REG Before instruction execution REG 3 W 2 C x A x After IAMSErUCElOMm REG dy MS 2 C 1 D result Is positive Before instruction execution REG 2 W 2 C x Z x http www mikroe com en books picmcubook ch9 30 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set After instruction REG 0 W 2 C 1 2 1 result is O Before instruction execution REG 1 W 2 C x Z x E OPA After instruction REG OxFF W zs 0 result is negative SWAPF Swap Nibbles in f Syntax label SWAPF f d Description The upper and lower nibbles of register f are swapped If d w or d 0 the result is stored in register W If d f or d 1 the result is stored in register f Operation f 0 3 gt d 4 7 f 4 7 gt d 0 3 Operand 0 lt f lt 127 d 0 1 Status affected Number of cycles 1 EXAMPLE 1 label SWAPF REG w Before instruction execution REG 0xF3 Pel IN CrO lm TL ODDS REG O0xF3 i Ube Sis EXAMPLE 2 label SWAPF REG Before instruction execution RECS OR TE E ESTEE DI E aie mE T OU REG 0x3F http www mikroe com en books picmcubook ch9 31 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set XORLW Exclusive OR literal with W Syntax label XORLW k
98. 7 D6 D5 DA D3 D2 D1 DO Execution Time Clear display 0 0 0 0 0 0 0 0 0 5 1 64mS Cursor home 0 0 0 0 0 0 0 0 1 X 1 64mS Entry mode set 0 0 0 0 0 0 0 1 I D S 40uS Display on off p 0 0 0 0 0 0 1 D U B 40uS az 0 0 0 0 0 1 bic mt X X 40uS Function set 0 0 0 0 1 DL N F X X 40uS Set CGRAM CA 0 0 0 1 CGRAM address 40uS Set DDRAM ATA 0 0 1 DDRAM address 40uS ee BUSY nag g 1 BF DDRAM address Write to CGRAM or DDRAM il 0 D7 D6 D5 D4 D3 D2 D1 DO 40uS Read from CGRAM or DDRAM 1 1 D7 D6 D5 D4 D3 D2 D1 DO 40uS I D 1 Increment by 1 R E Ye shit aac O Decrement by 1 O Shatt lert SA Ds pila Slob Om DL 1 8 bit interface O Display chiit orf O 4 bit interface D 1 Display on N 1 Display in two lines O Display ofr O Display in one line U Il Cursor on F 1 Character format 5x10 dots x Cursor off 0 Character format 5x7 dots B l1 cursor blink on D C 1 Display sh tt OSC USO o lia OEE OS Cursor shite What is Busy flag Compared to the microcontroller the LCD is an extremely slow component Because of this it was necessary to provide a http www mikroe com en books picmcubook appb 15 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples signal which would upon command execution indicate that the display is ready for the next piece of data That signal called the Ge flag can be read from the line D7 When the voltage on this line is OV BF 0 the display is ready
99. 73 0 53 a7 10417 0 00 47 10417 0 00 23 19 2k 19 23k 0 16 51 19 2k 0 00 47 19 23k 0 16 25 19 23k 0 16 12 57 6k 58 82k 2 12 16 57 6k 0 00 15 55 56k 3 55 8 115 2k 111 1k 3 55 B 115 2k 0 00 T Table 6 2 Determining Baud Rate BAUDCTL Register http www mikroe com en books picmcubook ch6 11 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules ABDOVF RCIDL SCKP BRGi6 WUE ABDEN Bit is unimplemented Readable Writable bit Readable bit After reset bit is cleared After reset bit is set Fig 6 11 BAUDCTL Register ABDOVF Auto Baud Detect Overflow bit is only used in asynchronous mode during baud rate detection e 1 Auto baud timer overflowed and e 0 Auto baud timer did not overflow RCIDL Receive Idle Flag bit is only used in asynchronous mode e 1 Receiver is idle and e 0 START bit has been received and receiving is in progress SCKP Synchronous Clock Polarity Select bit acts differently depending on EUSART mode Asynchronous mode e 1 Transmit inverted data to the RC6 TX CK pin and e 0 Transmit non inverted data to the same pin Synchronous mode e l Synchronization on rising edge of the clock and e 0 Synchronization on falling edge of the clock WUE Wake up Enable bit e 1 Receiver waits for a falling edge on the RC7 RX DT pin to start waking up the microcontroller from sleep mode
100. 8th OPTION REG RBPU INTEDG Tocs Tose PSA Ps2 Ps PSO PCL Least Signif icant Byte of Program Counter Cm ws we wipe m 9 3 De FR indirect Data alioli Address Pointer Cam mss reser vis usas usa mas mis yes mess ue EIE ms p o o E o ses risen riser Tris n PCLATH UpperSbits ofthe Program Counter toon ae eee re wt eee mr wr er n PE ADE RCE mae SSPIE CCPIIE TMR21E TMRIE HERE I i cones a eos OSCCON IRCF2 IRCF IRCFO osts HTS LTS scs Pose rw rosa runa runt Tuno e meebo ages 0 Synchronous Serial Port 15 C made Address dos mia osea se CKE Con e s ww u a emnon een poes roce poea poca pace roer roc i esmen f sms smo sme sme sra A D Result Register Low Byte Apo aom veci veo Table 1 4 SFR Bank 1 La f zm http www mikroe com en books picmcubook ch1 12 of 14 5 3 2009 11 31 25 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview SFRs bank 2 Address Name Bi7 Bie Bits Bis Bia Biz Bit Bito Indirect register TMRO Timer TO Register Least Significant Byte of the Program Counter 104h FSR Indirect Data Memory Address Pointer 105 WDTCON WDTPS3 WDTPS2 W
101. A O AO edo A M NI M M A d ME I M E M ML LM MM D M MM M E MES D E MMC M END CO program Macro digbyte digbyte MACRO argo LOCAL Ios OI LOCAL pisce als LOCAL Erri Cim E Dago Sae Digi Sl e e Dig Clee Dig movf argo w movwft Digtemp movlw LOO Boxe 2 E De subwf Digtemp f Ioue me STATUS C GTG EXIT decf Dieta E addwf Digtemp T Excel mov lw sede eE Dag E subwf Digtemp f DEESE Sl Ais Cc goro Boie decf aber dg addwf Digtemp f Eus MOVE Digtemp w movwf DIGO ENDM Macro digbyte is used to convert the number from digital to decimal format Besides digits of such decimal number are stored into special registers in order to enable them to be displayed on LED displays EXAMPLE 14 Sound generating using macros The generation of sound is a task commonly assigned to the microcontroller Basically it all comes to generating a pulse sequence on one output pin While doing so the proportion of logic zero 0 to logic one 1 duration determines the tone pitch and by changing different tones different melodies arise In this example any press on push buttons T1 and T2 generates a sound The appropriate instructions are stored in macro beep containing two arguments m Frequency the greater number the higher tone BEEP MACRO freq duration E Duration the greater number is the longer it lasts http www mikroe com en books picmcubook appb 44 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online
102. A and SCL Afterwards this bit is automatically cleared by hardware and e 0 Repeated START condition is not initiated http www mikroe com en books picmcubook ch6 22 of 27 5 3 2009 11 34 00 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules SEN START Condition Enabled Stretch Enabled bit In 12C Master mode only e 1 Initiate START condition on pins SDA and SCL Afterwards this bit is automatically cleared by hardware and e 0 START condition is not initiated IC in Master Mode The most common case is when the microcontroller operates as a master and the peripheral component as a slave This is why this book covers just this mode It is also considered that the address consists of 7 bits and device contains only one microcontroller one master device In order to enable MSSP module in this mode it is necessary to do the following Set baud rate SSPADD register turn off slew rate control by setting the SMP bit of the SSPSTAT register and select master mode SSPCON register After the preparation has been finished and module has been enabled SSPCON register SSPEN bit one should wait for internal electronics to signal that everything is ready for data transmission i e the SSPIF bit of the PIRI register is set This bit should be cleared by software and after that the microcontroller is ready to start communication with peripherals SSPADD xda Y Baud Rate ssP
103. AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules In Short In order to establish serial communication in I C mode the following should be done Setting Module and Sending Address e Value to determine baud rate should be written to the SSPADD register e SlewRate control should be turned off by setting the SMP bit of the SSPSTAT register e In order to select Master mode binary value 1000 should be written to the SSPM3 SSPMO bits of the SSPCON1 register e The SEN bit of the SSPCON2 register should be set START condition e he SSPIF bit is automatically set at the end of START condition when the module is ready to operate It should be cleared e Slave address should be written to the SSPBUF register and e When the byte is sent the SSPIF bit interrupt is automatically set when the acknowledge bit has been received from the Slave device Data Transmit e Data is to be send should be written to the SSPBUF register e When the byte is sent the SSPIF bit interrupt is automatically set upon the acknowledge bit has been received from Slave device and e In order to inform the Slave device that transmit is complete STOP condition should be initiated by setting the PEN bit of the SSPCON register Data Receive e In order to enable receive the RSEN bit of the SSPCON2 register should be set e he SSPIF bit signals data receive When data is read from the SSPBUF CS the ACKEN bit
104. Book PIC Microcontrollers Appendix B Examples VCC 5V a RB7 u D Di i T1 1 o i U i O i VCC GND s c x TI al Co i Co i n ii nl D 4MHz 2x20 30pF i GND Example 14 RT D D US ORE RR EU A EE Header eA Ke A acr OK SIA RAAT AY NT AS TASAS IN SN LIN IN KRAK AK A tN Defining vaclasgleg LA Program a US A AGB ARRAS AN A A UP NUR AR ANNA US aS UA IAS clio El Ob AC HICAT Auxiliary variables for macro pausems irren que EOS PRESCWalLt Beep_TEMP1 7 IBellonas CO Macro SES Beep_TEMP2 Beep_TEMP3 endc define BEEPport PORTD 2 Speaker pin tdeirine ISS tees MESS ID expand Ps hia uM M M x M MX I uU uu Uu x UL M Rte ORG USADO gt RESET vector address goto main PRUNUS tO pro ran Start abel marin E MK CU O E I DUM E MU I QE AUN remaining code goes here include Toause ner include lone soige IMEN include beep inc main banksel ANSEL Selects bank containing ANSEL GE ANSEL HAS OUEST Sc digital http www mikroe com en books picmcubook appb 45 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples cla banksel mov Iw movwt banksel e Loop buUrE On DIO TOMO E Easa BEEP BERE BEEP BEEP goto Blay BEEE BEEP BERE BEEP GEO ANSELH TRISD lo oi TRIOD PORTI PO RW Ay mnk T ALIE IU OT Macro Beep Pu ush ouccom 1 JE Bossi ated oU IE LE OX 2
105. Book PIC Microcontrollers Introduction World of Microcontrollers In order to make conversion of a hexadecimal number to decimal each hexadecimal digit should be multiplied with the number 16 raised by its position value For example ASTE number in hexadecimal system e 4 14 H16 716 112 31096223256 768 10 167 10 4096 40960 41854 same number in decimal system el Fig 0 5 Hexadecimal to decimal number conversion Hexadecimal to Binary Number Conversion It is not necessary to perform any calculation in order to convert hexadecimal numbers to binary numbers Hexadecimal digits are simply replaced by the appropriate four binary digits Since the maximum hexadecimal digit is equivalent to decimal number 15 we need to use four binary digits to represent one hexadecimal digit For example E4 11100100 ol E 4 Fig 0 6 Hexadecimal to binary number conversion http www mikroe com en books piemcubook ch0 7 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers sculcaelcl E C tive table bel tains the values of numbers 0 255 in three different numberi t omparative table below contains the values of numbers 0 in three different numbering systems 0 0 0 0 0 00 00 0 1 0 0 0 0 1 Marking Numbers 20 0 0 0 0 2 3 0 00 0011 3 The hexadecimal numbering system is along w
106. C16F887 microcontroller are described in this chapter Since their bits control several different circuits within the chip it is not possible to classify them into some special group These bits are described along with the processes they control STATUS Register IRP RP1 RPO TO PD Z DC C Legend Readable Writable bit Readable bit only After reset bit is cleared After reset bit is set After reset bit i amp unknown Fig 2 1 STATUS Register The STATUS register contains the arithmetic status of the W register the RESET status and the bank select bits for data memory One should be careful when writing a value to this register because if you do it wrong the results may be different than expected For example if you try to clear all bits using the CLRE STATUS instruction the result in the register will be 000xx1xx instead of the expected 00000000 Such errors occur because some of the bits of this register are set or cleared according to the hardware as well as because the bits 3 and 4 are readable only For these reasons if it is required to change its content for example to change active bank it is recommended to use only instructions which do http www mikroe com en books picmcubook ch2 1 of 12 5 3 2009 11 32 08 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 2 Core SFRs not affect any Status bits C DC and Z Refer to Instruction Set Summary e IRP Bit selects re
107. C2 W 0x00 ae OI cs MI eto DLE Zoe 10 http www mikroe com en books picmcubook ch9 21 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set EXAMPLE 2 label MOVF INDF f Before instruction execution W 0x17 FSR 0xC2 register at address 0xC2 contains the value 0x00 After instruction W 0x17 HS Ue gls ie Medus esteem ms the value 0x00 a cd MOVLW Move literal to W Syntax label MOVLW k Description 8 bit literal k is moved to register W Operation k gt W Operand 0 lt k lt 255 Status affected Number of cycles 1 EXAMPLE 1 label MOVLW Ox5A Vr Een Las cito Lon MEOS S EXAMPLE 2 Const equ 0x40 http www mikroe com en books picmcubook ch9 22 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set label MOVLW Const Before instruction execution W 0x10 PS db us ISI TE Jg ET ESSO a0 MOVWE Move W to f Syntax label MOVWF f Description The content of register W is moved to register f Operation W gt f Operand 0 x f lt 127 Status affected Number of cycles 1 EXAMPLE 1 label MOVWF OPTION REG Before instruction execution OPTION REG 0x20 W 0x40 AFter instruction OPTION PREC 0x10 W 0x40 EXAMPLE 2 label MOVWF INDF Betore TASE UCET ON execution Ns ESRO CO register address 0x 2Z conchis http www mikroe com en bo
108. Cad RAT gal O Tak CC NP OG S TO AN A Cat ak AS TES a lez aeneus be done o using macro eos betore access Ne Ne Ne Ne TAg LCD KAA AAAA KAANAK AG ah E To KE ACA EAS al TAP WAS aS Va WAP Uae AT AE AGE ASA QUARE AEG AGRAR ON LAG UC REOR TAD Tat Tah Al ae Wah R AARAA LA TAPIA LA E at ad Vad A Tat TL AR TA Ea LE MACRO DEL STATUS REO Bank0 ber STATUS REI E ECDPOr EEUE MONT EC DPOrCEUL AW movwf SB cae o sus STATUS RPO Banki DCF SPINS RE CILE DRS ALO Dase Wakelin Oui IC POE SIS RPO gt Bank http www mikroe com en books picmcubook appb 48 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples Der SAO FPI Function set 4 bit mode change movlw To D CORTE UNE movwf ie DEUT swapf CNS movwf I5 CDD ON TES UTE DCE Enoc ta RS movf I5 DID D BU 7 W movwf en pol OSE TC DOS t EXE EDN movf CODO Ede Buin W movwf Cupo PECE ECDPDPOrCEUL EN MOVE nou W movwf Ecol euet Delaylms I ms delay Function set display mode set ledemnd joy OG IAC LAGS eeu t Delaylms ms delay DDii pilla ON Ob on ENS NIE qs ciel 5 2990 XIII ON cov Delaylms 7 T ms delay Entry Mode Set ihe eine le ORONO TI Ie cali Delaylms He ms delay Display Clear eden OOO OOO pausems 40 40 ms delay Function set 4 bit mode change movlw Or OOTOOOOQE movwf CD SE swap I DUI W movwf LOCDPOrC BUT DEE CIDE R MONE CNO BU W movwf IMG Dro jee DSE Doma
109. DTPSt WDTPSO SWDTEN RBO CM2CON1 MC1OUT MC20UT CIRSEL C2RSEL 11688 C2SYNC 10d PCLATH Upper 5 bits of the Program Counter 1OBh INTCON GE PEE Toe INTE Ree TOF NTF RBIF EEDAT1 EEDATO EEADR1_ EEADRO EEDATH1 EEDATHO tOFh EEADRH JERADRH4 EEADRH3 EEADRHO Table 1 5 SFR Bank 2 SFRs bank 3 Address Name Bu ene Bis Bi Bio e Bii Bio Indirect Register PSO Least Significan Byte of the Program Counter _183n_ STATUS IRP RP RPO TO PD z w C Indirect Data Memory Address Pointer 185h SRCON SRI SRO_ C1SEN C2REN PULSS PULSR FVREN TRISB1 TRISBO 187h BAUDCTL ABDOVF RCIDL SCKP BRG16 WUE ABDEN 89h ANSELH ANS13 ANS12 ANS11 ANS10 ANS9 ANS8 19Ah PCLATH Upper 5 bits of the Program Counter INTF RBIF ocn eecont eeren w RD EEPROM Control Register 2 Table 1 6 SFR Bank 3 STACK A part of the RAM used for the stack consists of eight 13 bit registers Before the microcontroller starts to execute a subroutine CALL instruction or when an interrupt occurs the address of first next instruction being currently executed Is pushed onto the stack i e onto one of its registers In that way upon subroutine or interrupt execution the microcontroller knows from where to continue regular program exe
110. EAS ak Cat eal OS oS AA ROGA CE IK ROIG OK DE Cal AR US ad RACK rah at TARAS Wak DATOS Cia ra UNA NA IE e KK KK KK KK KK KK KK KK KK KK KKK KK KKK KK KK KK KKK KK KKK KKK KKK KKK KK KKK PROGRAM START QUIE GI 0x0000 banksel TRT E CLr E ERTSE movlw I5 11019 0 1L LOO movwf TRESA banksel ANSEL movlw P OOOO IL ALONE movwf ANSEL elr ANSELH banksel ADCON1 DSE ADCON1 ADFM E PEF ADCON1 VCFG1 DSE ADCON1 VCFGO banksel ADCONO movlw EAU MON WE ADCONO Nees banksel ADCONO lene a SO ADCONO T OO LOGS http www mikroe com en books picmcubook appb 38 of 54 5 3 2009 11 36 02 AM Address Or Lille Cire Program Ste bc Selects bank containing register TRISB Apo B pins aro Conrigured ae OuEDUEs Pins RA2 and RA3 are configured as inputs Selects bank containing register ANSEL Inputs AN2 and AN3 are analog while euo qum ced eese cr Selects bank including register ADCONI ali letra o ole sabe Voltage Vss is used as Vref RA3 pin voltage is used as Vref Selects bank containing register ADCONO AD Converter wees clock Fose 2 AD channel On RA pin ahs Used Or On eese sa AD converter is enabled Tests bit GO DONE Conversion in progress remain in mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples banksel ADRESL MOVE ADRESL w E banksel POROS movwf PORTE DSE ADCONO T Goro loop end 7 EXAMPLE 12 Using EEPROM memory Toop Lower byte of conversion
111. EN movf TENSO rebut movwf ECDPDOTE Der DIO ede BU EN movf ECDPOrtBEUI W movwf EC Dio late Sen Delaylms 1 ms delay Function set display mode set edema OOO OO eau Delaylms 1 ms delay DSi ON OnE Comzmel Edema Or OCOOTIOOE een Delaylms 1 ms delay Entry Mode Set edema SAO 0 TOILET OA cM Delaylms 1 ms delay Display Clear de al OT 10 0118 8 fOWOHO T pausems 40 40 ms delay ENDM ALAS ZO Al A BOE TAS Vo A A WAS Vas Tad US RASA E WS TAL TA VAS AAAA AN US TAS lO Fal aS Las lOs Val aS La AR US LS tal oS VS WAS AS AS Coe Vad AS WSUS LAL US Ad E AGRO ROG AGRO OS aS LAS AR US TAT OS TAS lcacl as the same as ledeme oc lcdcmd sends command to LCD see the table on the previous page EE Mus Ta M M M M A EE EQ SM S E E M E MM M E gl RE jedem MACRO CO ECPbcCommoancs Send command Co LCD http www mikroe com en books picmcubook appb 49 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples itc ome LCDdata LCDwr Sendw me Ne Ne Ne Ne Ne lcdtext S wake http www mikroe com en books picmcubook appb 50 of 54 5 3 2009 11 36 02 AM Macia NS Pest wricing 1S os encia SES Que CUISINE OOS LIE ION PAE DE Cal CAP IAS OF ta Tah Wah Ranas TUS Par RS Cal at Vat ah ZA TAR OS Lah tra ak Tat a TAR CA Ral RAS CARAS Tah Mal RCM ah atl RC ead Wak RO ZAS Rah O oS A REI A BA BOR EA AS mov lw LCDcommand cou He De ome END
112. EXAMPLE label RETLW 0x43 Before instruction execution W x pO x TOS Eco Oi Steves After Sn Su eti om W 0x43 DS PO HOS bop oO sE lla TOS EOD lt n Seach http www mikroe com en books picmcubook ch9 25 of 35 5 3 2009 11 35 12 AM TOS 1 mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set REIURN Return from Subroutine Syntax label RETURN Description Return from subroutine The value from the top of stack is loaded to the program counter This is a two cycle instruction Operation TOS program counter PC Operand Status affected Number of cycles 2 EXAMPLE label RETURN Before instruction execution PC x TOS EOD Of i o NE ox Mewes bs pate proa e MOS top Ol i e e TOS ECE O oO Seco m EOS i RLF Rotate Left f through Carry Syntax label RLF f d Description The content of register f is rotated one bit to the left through the Carry flag If d w E 0 the result is stored in register W If d f ord 21 the result is stored in register f Operation f n gt d n 1 f 7 gt C C gt d 0 Operand 0 lt f lt 127 d 0 1 Status affected C Number of cycles 1 http www mikroe com en books picmcubook ch9 26 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set c f Register Fig 9 1
113. FET Driver FET Driver pa PB eee FET Driver ints Fig 5 15 Full Bridge Mode Full Bridge Forward Configuration In Forward mode the following occurs e Logic one 1 appears on the P1A pin pin is high active e Pulse sequence appears on the P1D pin and e Logic zero 0 appears on the P1B and P1C pins pins are low active http www mikroe com en books picmcubook ch5 12 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules Figure below shows the state of the P1A P1D pins during one full PWM cycle Period Pulse Width L3 Fig 5 16 Forward Mode Full Bridge Reverse Configuration The same occurs in Reverse mode except of the pins functions e Logic one 1 appears on the P1C pin pin is active high e Pulse sequence appears on the P1B pin and e Logic zero 0 appears on the P1A and P1D pins pins are active low Period Pulse Width PIA P1D Fig 5 17 Reverse Mode PWMICON Register STRC PWM Restart Enable bit e 1 Upon auto shutdown the PWM module is automatically reset while the ECCPASE bit of the ECCPAS register is cleared e 0 In order to restart PWM module upon auto shutdown the ECCPASE bit must be cleared in software PDC6 PDCO PWM Delay Count bits 7 digit binary number determines the number of instruction cycles 4 Tosc added as time delay during the activation of PWM output
114. Hz and setting the System Clock Source SCS bit of the OSCCON register afterwards As seen in figure below everything is performed using bits of the OSCCON register http www mikroe com en books picmcubook ch8 7 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits HFINTOSC Postscaler P O Se a 4 4 SS SO 46 5 Wien S T OSCCON Register IRCF2 IRCF1 IRCFO SCS Fig 8 13 Internal Oscillator settings 2 The low frequency oscillator LFINTOSC is uncalibrated and operates at 31 kHz It is enabled by selecting this frequency bits of the OSCCON register and setting the SCS bit of the same register Two Speed Clock Start up Mode Two Speed Clock Start up mode is used to provide additional power savings when the microcontroller operates in sleep mode What Is this all about When configured to operate in LP XT or HS modes the external oscillator will be switched off on transition to sleep in order to reduce the overall power consumption of the device When conditions for wake up are met the microcontroller will not immediately start operating because it has to wait for clock signal frequency to become stable Such delay lasts for exactly 1024 pulses After that the microcontroller proceeds with program execution The problem is that very often only a few instructions are performed before the microcontroller is set up to Sleep mode
115. Legend RAW Readable Writable bit 0 After reset bit is cleared Fig 7 4 ADCONO Register ADCS1 ADCSO A D Conversion Clock Select bits select clock frequency used for internal synchronization of A D converter lt also affects duration of conversion ADCS1 ADCS2 Clock 0 0 Fosc 2 0 1 Fosc 8 1 0 Fosc 32 1 a RC Table 7 2 A D Conversion Select Bits Clock is generated by internal oscillator which is built in converter CHS3 CHSO Analog Channel Select bits select a pin or an analog channel for conversion i e voltage measurement http www mikroe com en books picmcubook ch7 4 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules CHS3 CHS2 CHS1 CHSO Channel Pin 0 0 0 0 0 RAO ANO 0 0 0 1 1 RA1 AN1 0 0 1 0 2 RA2 AN2 0 0 1 1 3 RA3 AN3 0 1 0 0 4 RA5 AN4 0 1 0 1 5 REO AN5 0 1 1 0 6 RE1 AN6 0 1 1 1 7 RE2 AN7 1 0 0 0 8 RB2 AN8 1 0 0 1 9 RB3 AN9 1 0 1 0 10 RB1 AN10 1 0 1 1 del RB4 AN11 1 1 0 0 12 RBO AN12 1 1 0 1 13 RB5 AN13 1 1 1 0 CVref 1 1 1 1 Vref 0 6V Table 7 3 Analog Channel Status Bits GO DONE A D Conversion Status bit determines current status of conversion e 1 A D conversion is in progress and e 0 A D conversion is complete This bit is automatically cleared by hardware when the A D conversion is completed ADON A D On bit enables A D converter e 1 A D converter is enabled and e O AJ D converter is disabled
116. M mikroElektronika Free Online Book PIC Microcontrollers Chapter 2 Core SFRs SFRs INTCON PIE1 PIE2 PIR1 PIR2 and 10OCB EEPROM b Timer 0 OSCILLATOR lls 77e oe A D converter ulia USART receiver picco transmitter pio RIE MSSP SPI 12C Transmission E c Error re ot kala CCP1 module EGP 16 CCP2 module bero Waking up Timer 1 bec Timer 2 bei Analog LL LL lU uai comparator 1 Pie ra 1 ae Interrupt LOO IH oH Analog e comparator 2 ge poe E Pin RAO E Fig 2 9 Interrupt SFRs INTCON Register The INTCON register contains various enable and flag bits for TMRO register overflow PORTB change and external INT pin interrupts Git PEIE Tore INTE RBIE TOF INTF RBIF Legend RW Readable Writable bit 0 After reset bit is cleared x After reset bit is unknown Fig 2 10 INTCON Register e GIE Global Interrupt Enable bit controls all possible interrupt sources simultaneously o 1 Enables all unmasked interrupts o 0 Disables all interrupts e PEIE Peripheral Interrupt Enable bit acts similar to GIE but controls interrupts enabled by peripherals It means http www mikroe com en books picmcubook ch2 5 of 12 5 3 2009 11 32 08 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 2 Core SFRs that it does not affect interrupts triggered by the timer TMRO or by
117. M movwf men bet Ono Ulin a RS movf EDO Re Suh W movwf TE IDID UIS SEO LCDwr movwf ED DSi Cno RS movf EC DID I BU P W movwf POPOTE GOEOD LCDwr swapf ACID Sila W cu d Sendw mov E LCD sell senaW JC EE UNICA andlw OxOF movwf LCDtemp movlw OxFO andwf EO OPOrE ERE E MOVE SDE TW iorwf JE CDI Ot BUE E MOVE ICID oct ui I W movwf Te CODO ONSE ceu Delaylms Ios IEOIBrergasie SURE EN movf EC DPOrCEUL 7 Ww movwf ES Byeteneie DOE T DIOE de But EN movf I5 C IDs BUI W movwf ECDPOTE canmi Delaylms SE UNICA MACRO select text Toren Message ocal Swale local Exit local i 0 SEO SL SEE Message I 3E GE Del 0 IF select 1 ikedend o LO COO CC ELSE IF select 2 Escenas OOO ENDIE ENDIF WEE a E call Message i addlw 0 Oz EXIT call CDI EA AS TSE ToS TITS Woh CaS US CS VaR aS KREIS AS TST TAS Tah AR Uo Car ak A TA TAL AS TARTAS AR TAE Unk TA LA Tal TAN LA TAN Pak Vas AR Valk War Valk AS Tak OS Tal Tal AS RAS ak MAS La ak Vat AS AS Tal lcdtext writes text containing 16 characters which represents a The first argument select selects the line in which If select is O Lex writing m SEU E S com Es macro writ Ss tet rom tas OE current position Text 2s specified roar gomen conste one o ar Sas Create lookup table from arguments Repeat conditional program compiling 16 times Read lookup table and place value in W mp S Ee Greece cnp abiere displaying Won ECD mikroElektronika F
118. M E module presents itself as a convenient A jf A zd solution 1 Fil i J LAA X Fig 6 1 Remote Control and Plane SU y 3 1 j E A e The EUSART system integrated into the PIC16F887 microcontroller has the following features Full duplex asynchronous transmit and receive Programmable 8 or 9 bit character length Address detection in 9 bit mode Input buffer overrun error detection and Half duplex communication in synchronous mode master or slave http www mikroe com en books picmcubook ch6 1 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules EUSART Asynchronous Mode The EUSART transmits and receives data using standard non return to zero NRZ format As seen in figure 6 2 below this mode does not use clock signal while the data format being transferred is very simple Idle State STOP bit START bit y START bit y 8 or 9 bit data MERE y Fig 6 2 EUSART Asynchronous Mode Briefly each data is transferred in the following way e In idle state data line has high logic level 1 e Each data transmission starts with START bit which is always a zero 0 e Each data is 8 or 9 bit wide LSB bit is first transferred and e Each data transmission ends with STOP bit which always has logic level which is always a one 1 EUSART Asynchronous Transmitter Interrupt RCG TX pin Control s n
119. MR2 belongs to peripheral modules Global interrupt enabled Remain here gel Ont o ia WU Since the CCP modules have a wide range of possibilities they are commonly used in practice This example illustrates the use of CCP1 module in PWM mode Bits of the CCP1CON register determine that the module operates as a single output PWM The same bits determine the PWM frequency to be 4 88 kHz To make things more interesting the duration of the output P1A PORTC 2 pulses may be changed by means of push buttons symbolically called DARK and BRIGHT Push buttons are tested in interrupt routine initiated by the timer TMR1 Any change affects the LED diode so that it changes light intensity Note that port B does not use external resistors because internal pull up resistors are enabled The whole process of generating PWM signal is performed behind the scenes which enables the microcontroller to do other things http www mikroe com en books picmcubook appb 35 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples vcc J 10K RESET i lt 3 U MI C I ql F DARK VEC O 70 T Qu i l at BRIGHT GND 7 J BMHz GND 2x20 30pF GND a LED 330R GND Example 10 CCk ck ck ck ck ck ck ck kk ke ke kk KK KKK Header XXX Xkkokokokck kk kck ck ck Ck kckck Ck kk k ck Ck Ck k k ck Ck Ck ck ck ck Ck Ck ck ck AA
120. NTS AND SETTINGS MARKO MIE DESKTOP TOUCHPANEL BIGPICSP 15 TOLICHPANEL HEX Device FIC16FSS Operation None Fig 8 16 Enabling Fail Safe Clock Monitor OSCTUNE Register Modifications in the OSCTUNE register affect the HFINTOSC frequency but not the LFINTOSC frequency Furthermore there is no indication during operation that shift has occurred Loc 7 TUNA TUN3 TUN2 TUNI TUNO Legend Bit is unimplemented RW Readable Writable bit 0 After reset bit is cleared Fig 8 17 OSCTUNE Register TUN4 TUNO Frequency Tuning bits By combining these five bits the 8MHz oscillator frequency shifts In this way the frequencies obtained by its division in the postscaler shift too TUN4 TUN3 TUN2 TUNI TUNO Frequency 0 1 F 1 1 Maximal 0 1 1 1 0 0 1 1 0 1 0 0 0 0 1 0 0 0 0 0 Calibrated 1 1 1 1 0 0 1 1 0 0 1 0 0 0 0 Minimal Table 8 2 Frequency Tuning Bits EEPROM EEPROM is neither part of program memory ROM nor data memory RAM but a special memory segment Even these memory locations are not easily and quickly accessed as other registers they are of great importance because the EEPROM data are permanently saved after the power supply goes off EEPROM data can be also changed at any moment Because of these exceptional features each byte of EEPROM is valuable The PIC16F887 microcontroller has 256 locations of data EEPROM controlled by the bits of the following registers http www mikr
121. Ne Ne Ne Ne Ne Ne Ne Address Oi the Eres Program Mice ruc tom Selects memory bank containing register OSCCON Selocts internal oscillator LE INTOSC with the frequency of 31KHz Mie odo mi altres uses Lnternal oscillator Selects bank containing register TRISB Ao B pins are econ igure l aS SD Selects bank containing register PORTB Binary number 01010101 is written to W Number is moved to PORTB Number hFF is moved to W Number is moved to variable counterl Variable counter I result is O Continue remain im loop is decremented by 1 NOE Binary number 10101010 is moved to W Number is moved to PORTB Number hFF is moved to W Number is moved to variable counterl Variable counter Ie rocule is O exea ue gt remain in loop2 is decremented by 1 IO Go to label loop End Or progran AAA RARA Header FAX AAA kkk kk k k kk k kk KKK K Kk k k kk k k k k k k kK k k k k e KK KK KKK KKK KKK KKK KK KK KK KK KR KK KK KR KK KKK KK KK KK KK DEFINING VARIABLES God oc C20 Block of variables starts at address 20h counterl Variable counterl at address 20h counter2 Variable counter2 at address 21h endc uL NL UN A DEM E M EK A Quee 0x0000 Addross of secs cn cis Hm meses blot SIEG banksel TRIOE Selects bank containing register TRISB elicit TRISB cedes TRIB banksel Ol Ie selects bank containing register PORTB TOO http www mikroe com en books picmcubook appb 23 of 54 5 3 2009 11 36 02 AM
122. OE Comparator C1 Output Enable bit http www mikroe com en books picmcubook ch7 9 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules e l Comparator CLOUT output is connected to the C1OUT pin and e 0 Comparator output is internal only n order to enable the C1OUT bit to be present on the pin two conditions must be met CLON 1 comparator must be on and the corresponding TRIS bit 20 pin must be configured as output C1POL Comparator C1 Output Polarity Select bit enables comparator C1 out put state to be inverted e 1 Comparator C1 output is inverted and e 0 Comparator C1 output is non inverted C1R Comparator C1 Reference Select bit e 1 Non inverting input ClVin is connected to reference voltage C1Vref and e 0 Non inverting input ClVin is connected to the C1IN pin C1CH1 C1CHO Comparator C1 Channel Select bit C1CH1 C1CHO Comparator C1Vin input 0 0 Input C1Vin is connected to the C12INO pin 0 1 Input C1Vin is connected to the C12IN1 pin 1 0 Input C1Vin is connected to the C12IN2 pin 1 1 Input C1Vin is connected to the C12IN3 pin Table 7 4 Comparator C1 CM2CONO Register _C20N C20UT C20E C2POL C2R C2CH1 C2CHO Bit is unimplemented Readable Writable bit Readable bit After reset bit is cleared Fig 7 10 CM2CONO Regsiter Bits of this register are in control of comparator C2 Similar to the previous case
123. ORG OOOO First instruction address goro main une to ale msc Ma wd A M KU DK Iu M d UI MA UNS ORG 0x0004 interrupt vector address movwft w temp Move w register to w temp register movf STATUS W Move STATUS register to status temp movwf SEE bs ESMO register mov f PCLATH w Move PCLATH register to pclath temp movwft pclath temp register p Src CE D ice api so Mene os BANKSEL TMRO movlw O movwt TMRO DEL ECON 1 Omer Det PORTA O0 Der PORTA 1 perse One O OO If com goto Msdon Lsdon PANCE One f movlw HIGH Ph ediwo T SO movwt PCLATH digbyte Dyal movf DG aw cak Bcdto seg Place LI mask on the PORTD movwt PORTED IOS Ie PORTA 1 Gero ISR end Msdon inci One f movlw HESSE Se movwt E NAM http www mikroe com en books picmcubook appb 42 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples digbyte Dial MOVE DIGO W ceu Bcdto seg Place TO mask on the PORT movwf BORTD list PORTA O0 SIONES Rem End of Interrupt E OUI ISR end MOVE pclath_temp w PCLATR register Ss Given tes Original movwt PCA itn state MOVE status temp w SNP NU seu sie Is given ICS Original movwt STATUS state swapf w temp f W register 1s given Wks original 7 state swapf w_temp w retfie Return from interrupt routine main banksel ANSEL Selects bank containing ANSEL GET TE ANSEL OA pins ace digital uL ess ANSELH BANKSEL TRISA mov w AAA RAO ane RAI Ware GConiigur
124. OTO 0xTA In addition to the preceding instructions Microchip has also introduced some other instructions To be more precise they are not instructions as such but macros supported by MPLAB Microchip calls them Special Instructions since all of them are in fact obtained by http www mikroe com en books picmcubook ch9 33 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set combining already existing instructions Instruction ADDCF ADDDCF B BC BDC BNC BNDC BNZ BZ CLRC CLRDC CLRZ MOVFW SETC SETDC SETZ SKPC SKPDC SKPNC SKPNDC SKPNZ SKPZ SUBCF SUBDCF Tour f d f d E d f d Description Add with carry Add with Digit Carry Branch Branch on Carry Branch on Digit Carry Branch on No Carry Branch on No Digit Carry Branch on No Zero Branch on Zero Clear Carry Clear Digit Carry Clear Zero Move File to W Set Carry Set Digit Carry Set Zero Skip on Carry Skip on Digit Carry Skip on No Carry Skip on No Digit Carry Skip on Non Zero Skip on Zero Subtract Carry from File Subtract Digit Carry from File Test File Equivalent Instruction BTFSC INCF BTFSC INCF GOTO BTFSC GOTO BTFSC GOTO BTFSS GOTO BTFSS GOTO BTFSS GOTO BTFSC GOTO BCF BCF BCF MOVF BSF BSF BSF BTFSS BTFSS BTFSC BTFSC BTFSC BTFSS BTFSC DECF BTFSC DECF MOVF
125. P2M1 CCP2MO 4 Flag bit CCP2IF CCPR2 Fig 5 9 CCP2 Module http www mikroe com en books picmcubook ch5 8 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules Similar to the pervious module this circuit is under control of the bits of the control register This time it is the CCP2CON register CCP2CON Register gt gt DC2B1 DC2B0 CCP2M3 CCP2M2 CCP2M1 CCP2M0 Legend Bit is unimplemented RAW Readable Writable bit 0 After reset bit is cleared Fig 5 10 CCP2CON Register DC2B1 DC2BO PWM Duty Cycle Least Significant bits are only used in PWM mode representing two least significant bits of a 10 bit number This number determines PWM signal s duty cycle The rest of bits 8 in total are stored in the CCPR2L register CCP2M3 CCP2MO CCP2 Mode Select bits select CCP2 mode CCP2M3 CCP2M2 CCP2MI CCP2MO Mode 0 0 0 0 Module is disabled reset 0 0 0 de Unused 0 0 1 0 Unused 0 0 1 1 Unused 0 1 0 0 ea le mode Every falling edge on the CCP2 pin 0 1 0 1 ADs mode Every raising edge on the CCP2 pin 0 1 1 0 Capture mode Every Ath rising edge on the CCP2 pin 0 1 1 1 Capture mode Every 16th rising edge on the CCP2 pin 1 0 0 0 Compare mode Output and CCP2IF bit are set on match 1 0 0 1 Compare mode Output is cleared and CCP2IF bit is set on match Compare mode 1 0 1 0 Interrupt is generated CCP2IF bit is set and CCP2 pin is unaf
126. PBRG value dec Error Actual Rate Fosc 18 432 MHz Actual Error SPORG value of Rate dec 300 0 00 Fosc 2 MHz SPBRG Error o 0 108 0 16 0 16 0 16 0 00 Actual value Rate dec 416 103 51 12 11 Fosc 11 0592 MHz Actual Error SPORG value Rate n dec Fosc 1 MHz Actual Error I value Rate o 300 5 0 16 1202 0 16 2404 0 16 110417 0 00 SYNC 0 BRGH 1 BRG16 10r SYNC 1 BRGH16 1 Fosc 20 MHz Fosc 8 MHz Actual Error SPORG value Rate va dec 300 0 00 6666 1200 0 01 4166 1200 000 3839 1200 0 02 1666 2400 0 02 2082 2400 000 1919 2401 0 04 832 9597 0 03 520 9600 000 479 9615 0 16 207 10417 0 00 4 79 10425 0 08 441 10417 0 191 19 23k 0 16 259 19 2k 0 00 239 19 23k 0 16 103 Of 4 K 0 22 86 of 5k 0 00 f9 of 14k 0 79 34 16 0 95 115 2k 0 00 117 6k 2 12 16 BRG16 1 or SYNC 1 BRGH16 1 Fosc 2 MHz Fosc 1 MHz pono iin Actual Error o Actual Error sie Actual Error Dm Actual Error HE Rate 96 e Rate value Rate E Rate 2 ue dec dec dec dec 300 300 0 01 3332 300 0 00 3071 299 9 0 02 1666 300 1 004 832 1200 1200 0 04 832 1200 000 767 1199 0 08 416 1202 016 207 2400 2398 008 416 2400 000 383 2404 0 16 207 2404 0 16 103 9600 9615 0 16 103 9600 0 00 96 9615 0 16 51 9615 0 16 25 10417 10417 0 00 95 104
127. PWH N AA 330R GND i LED 32 AA ag 8MHz 330R E 2x20 30pF T i LED Z _330R l FF idi GND When switching on every other LED diode on the port B emits light That is enough to indicate that the microcontroller is properly connected and operates normally This example gives the description of a correctly written header and a few initial directives They represent a part of the program used in all programs described in this book To skip repetitiveness it will not be written in the following examples but is considered to be at the beginning of every program marked as a Header http www mikroe com en books picmcubook appb 19 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples Y skew ww e x3 A A AAA EE ENAERE 007 Name Test asm E Date November 19 E Version 1 00 Programmer James Jones skew We e e cee eee ee ao oo ee E Description ake ce ee heo X e e aa oe We dece cec ceo coro e e de ec XI e ecce ce eA A WW ee oe Testing microcontroller eee ee EE EEE ee eee ea aaa A D list p 16f887 Type of microcontroller finclude lt p1613897 inc gt Defines all SFRs and bits within the PICIGOFBB errorlevel 302 Disables message Register in operand not in bank QO Ensure that bank bits are correct L pee de ar a o od dr de e e e e e A o dr e e e o rd e rd e e Ar A i _ CONFIG CONFIG HS OSC amp WDT
128. ROSISDO RC3ISCKISCL RCA SDI SDA ROO RDS RDI RD2 Fig 1 1 PIC16F887 PDIP 40 Microcontroller http www mikroe com en books picmcubook chl 2 of 14 5 3 2009 11 31 25 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview E aka 287 El L S 25 Gozo lou e ux AB ous uoc es of A eS 3 G C D O O D O C C 0 E E D E E m gm dU C DX AUDI LULEEU DU HELL LI DE we RC7T IRXIDT Cod RD4 a mC RcoTOSOTICKI Pal mmi Co DCZ RA amp OSCZ CLKOUT AT ROBPIC Coo HOC RAT OSCI CLKIN i RD7TiP1D Com M Wo M0 vaa Ves CJ IL IDFOO M0 vdd Vdd Com OC RENANT REWANIZINT Coo p OD RENANG RB1 AN10 C121N3 Co OCT REOANS RB2 ANB C TII RAS ANA SSIC2OUT RB3ANS PGM C121N2 Cy OCO RAATOCKI C1OUT C EDO L ILI LOM Cm REJMCLRYpp rr RESANIXTIG Coo RADANU U ULPWNLJC TAND RB amp TICSPCLK RBTICSPDAT RAT ANT C121N1 RAZ AN 2Vref CVref C21N RA 3J AN3IVre f 01 1N Fig 1 2 PIC16F887 QFN 44 Microcontroller Oscillator 0 20MHz Internal Oscillator pene eae F y Program 2E i Memory 8K Converter E Vref de CCP PWM modules RESET rs ly oo v U http www mikroe com en books piemcubook ch1 3 of 14 5 3 2009 11 31 25 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview Fig
129. Rest assured that design and development of devices mainly consists of the following method test correct repeat Of course the more you are in it the more complicated it becomes since the puzzle pieces are put together by both children and first class architects BASIC CONNECTING As seen in the figure below in order to enable the microcontroller to operate properly it is necessary to provide e Power Supply e Reset Signal and e Clock Signal http www mikroe com en books picmcubook appb 1 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples o 6 12V 3l O vec a 4 wif E lt I LM7805 ol M y 1 100uF 10uF 100nF o 10K GND oa i MCLR OT Re RAG Reg RA1 res RESET I RA2 RBA RA3 RB3 RA4 RB Ras U rel REO C Reo l RE1 vdd RE C vss I i Ddd TI Ro I 00 Vss co rol GND osci RDS Osc RDA RCO re 4MHz RC Rce RC2 RCS L RC3 RCA 20 30pF 20 30pF m RE fl RO RD I GND Clearly it is about simple circuits but it does not have to always be like that If the target device is used for controlling expensive machines or maintaining vital functions everything gets more and more complicated However this solution is sufficient for the time being POWER SUPPLY Even though the PIC16F887 can operate at different supply voltages why to test Murphy s low A 5DC pow
130. S register is cleared TO bit of the same register is set The WDT and its prescaler are cleared Operation 0 gt WDT 0 gt WDT prescaler 1 gt TO 0 gt PD Operand Status affected TO PD Number of cycles 1 EXAMPLE label SLEEP Before instruction execution WDT counter x WDT prescaler x Afer Ss UICE WDI eomm c 0x00 WDT prescaler 0 TO 1 PD 0 SUBLW Subtract W from literal Syntax label SUBLW k Description The content of register W is subtracted from the literal k The result is stored in register W Operation k W gt W Operand 0 lt k lt 255 Status affected C DC Z Number of cycles 1 http www mikroe com en books picmcubook ch9 29 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set EXAMPLE label SUBLW 0x03 Before wNnstcucrtg oH execution W Ox0l C x x Aftor SEINS T rre c Ni O estt als eoe Before instruction execution W Ox03 C x A x After instruction W 0x00 C 1 2 I result Xs 0 Before instruction execution W Ox04 C xX Z x After instruction W OxFF C 0 Z2 0 result is negative SUBWF Subtract W from f Syntax label SUBWF f d Description The content of register W is subtracted from register f If d w or d 0 the result is stored in register W If d f ord 1 the result is stored in register f Operation f W gt d Operand 0 x f lt 12
131. SEL Ie IS SERE IEEE MOVENT IS 10 O TE TEL HIE V BANKSEL PORTE MOVWE PORTS http www mikroe com en books picmcubook appa 5 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller EXAMPLE OF HOW TO WRITE A PROGRAM The following example illustrates what a simple program written in assembly language looks like Program to initialize port B and set its pins to logic one 1 Version 1 0 Date 03 05 2007 MCU 16F887 Programmer John Smith Configuring microcontroller PROCESSOR 16f 887 include picl6fB8B7inc _CONFIG CP OFF amp WDT OFF amp PWRTE ON amp XT OSC Start of program ORG 0x00 Reset vector goto Main Interrupt vector No interrupt routine Main Start of program banksel TRISB Select bank containing TRISB clrf TRISB Port B is configured as output PORTB Salect bank containing PORTE Oxff w 1111 1111 PORTE PORTB 1111 1111 Li Go to label LI or remain here End End of program Apart from the regular rules of assembly language there are also some unwritten rules which should be observed during program writing One of them is to write in a few words at the beginning of a program what the program s name is what it Is used for version release date type of the microcontroller it is written for and the name of the programmer Since this information is not of importance for the assembler it is written as a comm
132. STAT 1 IL Y siew rate SSPCON 110 00 V Master Mode ssPcoN UE v Enable e TS 2 V Fig 6 27 I C in Master Mode Data Transmission in I C Master Mode Each clock condition on the SDA pin starts with logic zero 0 which appears upon setting the SEN bit of the SSPCON2 register Even enabled the microcontroller has to wait a certain time before it starts communication It is the so called Start condition during which internal preparations and checks are performed If all conditions are met the SSPIF bit of the PIR1 is set and data transfer starts as soon as the SSPBUF register is loaded http www mikroe com en books picmcubook ch6 23 of 27 5 3 2009 11 34 00 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules Since maximum 112 integrated circuits may simultaneously START share the same transmission line the first data byte must SSPCON2 TT I fs 7 contain address which matches only one slave device Each sequence component has its own address listed in the proper data sheet The eighth bit of the first data byte specifies direction of data transmission the microcontroller is to PIR1 Ila j send or receive data In this case it is all about data receive and the eighth bit therefore is logic zero 0 Fig 6 28 Data Transmission in PC Master Mode When address match occurs slave Address the microcontroller has to wait for th
133. Some memory locations are directly connected to the characters on display It works quite simply it is enough to configure the display to increment addresses automatically shift right and set the starting address for the message that should be displayed for example 00 hex After that all characters sent through lines DO D7 will be displayed as a message format we are used to from left to right In this very case displaying starts from the first field of the first line because the address is 00 hex If more than 16 characters are sent then all of them will be memorized but only the first sixteen characters will be visible In order to display the rest of them a shift command should be used Virtually everything looks as if the LCD display is a window which shifts left right over memory locations containing different characters In reality this is how the effect of message shifting on the screen has been created DDRAM Memory First Line Addresses 00 27 hex jer pape pahshez pepe pa pecho efr o pas aos aso jer os se ss sae e seo n sn eo se sf on off eso Second Line Addresses 40 67 hex If the cursor is on it appears at the location which is currently addressed In other words when a character appears at the cursor position it will automatically move to the next addressed location http www mikroe com en books picmcubook appb 13 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers
134. TX CK pins are automatically configured as input and output respectively and e 0 Serial port disabled RX9 9 bit Receive Enable bit e 1 Receiving 9 bit data via EUSART system and e 0 Receiving 8 bit data via EUSART system SREN Single ReceiveEnable bit is used only in synchronous mode when the microcontroller operates as master e 1 Single receive enabled and e 0 Single receive disable CREN Continuous Receive Enable bit acts differently depending on EUSART mode Asynchronous mode e 1 Receiver enabled and e 0 Receiver disabled Synchronous mode http www mikroe com en books picmcubook ch6 7 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules e l Enables continuous receive until the CREN bit is cleared and e 0 Disables continuous receive ADDEN Address Detect Enable bit is only used in address detect mode e 1l Enables address detection on 9 bit data receive and e 0 Disables address detection The ninth bit can be used as parity bit FERR Framing Error bit e l On receive Framing Error is detected and e 0 No framing error OERR Overrun Error bit e 1 On receive Overrun Error is detected and e 0 No overrun error RX9D Ninth bit of Received Data can be used as address or parity bit EUSART Baud Rate Generator BRG If you carefully look at the asynchronous EUSART receiver or transmitter dia
135. a Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits e TOC e Introduction e Ch e Ch e Ch e Ch e Ch e Ch e Ch ee e Ch 1 O O N DD Ui A W N e App A e App B e App C Chapter 8 Other MCU s Circuits AS seen in figure below clock signal may be generated by one of two built in oscillators LP XT HS RC RCIO EC mode External Oscillator HFINTOSC 8 MHz LFINTOSC 31 kHz Internal Oscillator Power up Timer IRCFA IRCFO SCS Watchdog Ti i incer EN OSCCON Register Programmer Fail Safe Clock Config word Monitor Fig 8 1 Two built in oscillators http www mikroe com en books picmcubook ch8 1 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits An External oscillator is installed within the microcontroller and connected to the OSC1 and OSC2 pins It is called external because it relies on external circuitry for the clock signal and frequency stabilization such as a stand alone oscillator quarts crystal ceramic resonator or resistor capacitor circuit The oscillator mode is selected by bits of bytes sent during programming so called Config Word Internal oscillator consists of two separate internal oscillators The HFINTOSC is a high frequency internal oscillator which operates at 8MHz The microcontroller can use clock source generate
136. a POCUCA EXAMPLE 15 Using LCD display This example illustrates the use of the alphanumeric LCD display The program itself is very simple because macros are used usually the effort of creating Macros pays off in the end Two messages written on two lines change on display The second message is intended to display the current temperature Since no sensor is installed the measurement is not really carried out the variable temp appears on the display instead of the measured temperature In reality the current temperature or some other measured value would be displayed Data lines 1109 i ie Control lines VEC j I 10K 33 Es RESET mikroelektronika Beograd 88391 Old AMHz Re 20 30pF T 20 30pF RE Tes J RD GND URDI Example 15 SOROR ASQ ROGO ARA ARCA ASAT O ALA aS LA eal AS Las LA O Header KARANAA IG ICE OK AS LARA OK IND DOG AN AN RTI AGUA GORGE A ACE Y DEFINING VARIABLES IN PROGRAM CELOS 597 gt Block of variables starts al address 20h Arent Belongs to macro pausems ISO unte LOS emt LEDS GE P Belongs oed os Ce PEDECeMO http www mikroe com en books picmcubook appb 47 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples DPO DUT ECD Port Burrer Digtemp Belongs tro macro clics pes Dejo Panel Da Digo Temp ENDC ATENEO dto c ICID Sous qe EQU PORTB LCD is om PORTE 4
137. affect the ADC result Device frequency characteristics are shown in the table above The values in the shaded cells are outside of recommended range How to Use A D Converter In order to enable the A D converter to run without problems as well as to avoid unexpected results it is necessary to consider the following e A D converter does not differ between digital and analog voltages In order to avoid errors in measurement or chip damage the pins should be configured as analog inputs before conversion starts The bits used for this purpose are stored in the TRIS and ANSELH registers e When the port with analog inputs marked as CHO CH13 is read the corresponding bits will be driven to logic zero 0 and http www mikroe com en books picmcubook ch7 3 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules e Roughly speaking voltage measurement in the converter is based on comparing input voltage with internal scale which has 1024 marks 210 1024 The lowest scale mark stands for the Vref voltage whilst the highest mark e for the Vref voltage Figure 7 3 below shows selectable referent voltages and their minimum and maximum values as well VCC D 3V 4 3 2 VREF 2V L Analog Input 1 Voltage Vin E GND 0V GND 0 3V Fig 7 3 How to Use The A D Converter ADCONO Register ADCS1 ADCSO CHS3 CHS2 CHS1 CHSO GOIDONE ADON
138. al function registers SFR Even though both groups of registers are cleared when power goes off and even though they are manufactured in the same way and act in the similar way their functions do not have many things in common http www mikroe com en books picmcubook chl 8 of 14 5 3 2009 11 31 25 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview Fig 1 6 SFR and General Purpose Registers General Purpose Registers General Purpose registers are used for storing temporary data and results created during operation For example if the program performs a counting for example counting products on the assembly line it is necessary to have a register which stands for what we in everyday life call sum Since the microcontroller is not creative at all it is necessary to specify the address of some general purpose register and assign it a new function A simple program to increment the value of this register by 1 after each product passes through a sensor should be created Therefore the microcontroller can execute that program because it now knows what and where the sum which must be incremented is Similarly to this simple example each program variable must be preassigned some of general purpose register SFR Registers Special Function registers are also RAM memory locations but unlike general purpose registers their purpose is predetermined during manufacturi
139. all number of instructions is specific to the RISC microcontroller because they are well optimized from the aspect of operating speed simplicity in architecture and code compactness The only disadvantage of RISC architecture is that the programmer is expected to cope with these instructions Instruction Description Operation Flag CLK E Data Transfer Instructions MOVLW k Move constant to W k gt w 1 MOVWF f Move W to f W gt f 1 MOVF f d Move f to d f gt d Z 1 D CLRW Clear W 0 gt W Z 1 CLRF f Clear f 0 gt f Z 1 2 SWAPF f d Swap nibbles in f AGAIN 1 177 http www mikroe com en books picmcubook ch9 1 of 35 5 3 2009 11 35 12 AM ADDLW k ADDWF f d SUBLW k SUBWEF f d ANDLW k ANDWF f d ANDWF f d IORLW k IORWF f d XORWF f d XORLW k INCF f d DECF f d RLF f d RRF f d COMF f d ct ee ee BSF f b Eva poa BTFSS f b DECFSZ f d INCFSZ f d GOTO k CALL k RETURN RETLW k mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set Arithmetic logic Instructions Add W and constant W gt W Add W and f W gt d Subtract W from constant k W gt W Subtract W from f f W gt d Logical AND with W with constant W AND k gt W ee AND with W with W AND f d i AND with W with W AND f d Logical OR with W with constant IA Logical OR with W with f W OR f gt d Logical exclusive OR with W with constant W XOR k gt W Logical exclusive OR with W with f S
140. an four units six tens and seven hundreds Simple Could it be described in a bit more complicated way Of course it could 4 60 700 Even more complicated Naturally 4 1 6 10 7 100 Could this number look a bit more scientific The answer is yes 4 10 0 6 10 1 7 10 2 What does it actually mean Why do we use exactly these numbers 100 101 and 102 Why is it always about the number 10 That is because we use ten different digits 0 1 2 8 9 In other words because we use base 10 number system i e decimal number system Hundreds second position in number Tens first position in number o Units zeroth position in number 764 4 60 700 1100 10 764 4 1 610 7 100 The number 64 represented in three different ways 764 4 10 6 10 7 10 AUT Base 10 number system Fig 0 2 The number 764 represented in three different ways Binary Number System What would happen if only two digits would be used 0 and 1 Or if we would not know to determine whether something is 3 or 5 times greater than something else Or if we would be restricted when comparing two sizes i e if we could only state that something exists 1 or does not exist 0 Nothing special would happen we would keep on using numbers in the same way but they would look a bit different For example 11011010 How many pages of a book does the number 11011010 include In order to learn that follow the same logic lik
141. and is provided in Help PROCESSOR Directive This directive must be written at the beginning of each program It defines the type of the microcontroller which the program is written for For example Processor Loro http www mikroe com en books piemcubook appa 3 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller EQU directive This directive is used to replace a numeric value by a symbol In this way some a specific location in memory is assigned a name For example MAXIMUM EQU H 25 This means that a memory location at address 25 hex is assigned the name MAXIMUM Every appearance of the label MAXIMUM in the program will be interpreted by the assembler as the address 25 MAXIMUM H 25 Symbols may be defined this way only once in a program That this directive is mostly used at the beginning of the program ORG directive This directive specifies a location in program memory where the program following directive is to be placed For example ORG ITE B START M ORG 0x1000 TABLE P This program starts at location 0x100 The table containing data is to be stored at location 1024 1000h END directive Each program must be ended by using this directive Once a program encounters this directive the assembler immediately stops compiling For example END EnO E Progr amn INCLUDE directive The name of this directive fully indica
142. and so called Brown out reset occurs In that case prior to the microcontroller stops operating there is a serious danger that circuits which operate at higher voltages start perform unpredictable It can also causes fatal changes in the program itself because it is saved in on chip flash memory Fig 8 21 Brown Out Reset at Gradual Loss Of Power O Power Supply Valtage Time Noises http www mikroe com en books picmcubook ch8 14 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits This is a special kind of Brown out reset which occurs in Ium B n industrial environment when the power supply voltage blinks Unam for a moment and drops its value beneath minimal level Even Umin AN EE EF short such noise in power line may catastrophically affect the operation of device ES Fig 8 22 Noises E a 0 Time MCLR pin Logic zero 0 on the MCLR pin causes immediate and regular reset It is recommended to be connected as shown in figure below The function of additional components is to sustain pure logic one 1 during normal operation If their values are such to provide high logic level on the pin only upon T reset is over the microcontroller will immediately start operating This feature may be very useful when it is necessary to synchronize the operation of the microcontroller with additional electronics or the operation of several microcontrollers
143. ansmitter thereafter If an error occurs on receive it will be signalled by switching the LED diode on The easiest way to test device operation in practice is by using a standard Windows program called Hyper Terminal http www mikroe com en books picmcubook appb 51 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples Communication Cable Transmit Tx GNO 88391 Old Example 16 e RADI M MU E ey Header DR BRE AS AREA RACE ARCA Val Tari eae LAr WAL Wak Uae Vas Val Wak We ROSE RACER QUA A S BECA GRE AL ARAS AS uF DEFINING VARIABLES IN PROGRAM w temp EQU 0s 7D Variable for saving W register status_temp EQU Ox7E Variable for saving STATUS register pPelath temp EQU Ox7E Variable for saving PCLATH w register colo IQ 2 10 s Block of var tables starts et address 20 R Dort Variable at address 20 N POrt B Variable at address 21 h RS232temp v Varlable at address 22 h Roce ine Variable at address 23 h endc End omo ee of variables I AM C ME TD UK AM pU E UM A SUE UU E A E ORG 0x0000 Reset vector nop goto main Go to beginning Of program label mem gordo E E oN ee EGG ME P EM EM I ME E E M IE IC m E ME E E Mn arn aE Ze ORG 0x0004 interrupt vector address movwf WESS Save value of W register MOV E STATUS W Save value of STATUS register movwf Seu Ds Camo MOVE PCLATH w Save value of PCLATH register movwf pclath temp Jil S MM M Ra E Eu
144. aracters each It displays all the letters of alphabet Greek letters punctuation marks mathematical symbols etc In addition it is possible to display symbols made up by the user Other useful features include automatic message shift left and right cursor appearance LED backlight etc LCD DISPLAY Along one side of a small printed board there are pins used for connecting to the microcontroller There are in total of 14 pins marked with numbers 16 if the backlight is built in Their function is described in the table bellow Function Pin Number Name Logic State Description Ground 1 Vss OV Power supply 2 Vdd V Contrast 3 Vee 0 Vdd http www mikroe com en books picmcubook appb 11 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples 4 RS Control of operating gt R W 6 E DO 8 D1 9 D2 10 D3 Data commands a 12 D5 13 D6 14 D7 LCD screen RAN a Eh leE From 1 to 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 DO D7 are interpreted as commands DO D7 are interpreted as data Write data from controller to LCD Read data from LCD to controller Access to LCD disabled Normal operating Data commands are transferred to LCD Bit 0 LSB Bit 1 Bit 2 Bit 3 Bit 4 Bit 5 Bit 6 Bit 7 MSB The LCD screen consists of two lines with 16 characters each Every character consists of 5x8 or 5x11 dot matrix This book covers the 5x8 character di
145. ation the timer TMR2 Postscaler cannot be used for generating longer PWM periods PWM Resolution PWM signal is nothing more than the pulse sequence with varying duty cycle For one specified frequency number of pulses per second there is a limited number of duty cycle combinations This number is called resolution measured by bits For example a 10 bit resolution will result in 1024 discrete duty cycles whereas an 8 bit resolution will result in 256 discrete duty cycles etc In relation to this microcontroller the resolution is specified by the PR2 register The maximal value is obtained by writing number FFh PWM frequencies and resolutions Fosc 20MHz PWM Frequency 1 22kHz 4 88kHz 19 53kHz 78 12kHz 156 3kHz Timer Prescale 16 4 1 1 1 PR2 Value FFh FFh FFh 3Fh 1Fh Maximum Resolution 10 10 10 8 7 Table 5 2 PWM Frequencies and Resolutions PWM frequencies and resolutions Fosc 2 8MHz PWM Frequency 1 22kHz 4 90kHz 19 61kHz 76 92kHz 153 85kHz Timer Prescale 16 4 1 1 1 PR2 Value 65h 65h 65h 19h OCh Maximum Resolution 8 8 8 6 5 Table 5 3 PWM Frequencies and Resolutions CCP1CON Register http www mikroe com en books picmcubook ch5 6 of 15 5 3 2009 11 33 21 AM 208 3kHz 1 17h 200 0kHz 1 09h mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules Pim Pimo DCIB1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1MO Legend RAW Readable Writable bit 0 After reset bit is cleared
146. ause it counts internal clock pulses Since the whole electronics TMR1ON 4 uses these pulses there is no need for synchronization TMR1CS Pulses to count Prescaler 1 2 4 8 TICKPSO t TICKPS1 Fig 4 8 TMR1 in timer mode yw re we TMR E ui TMRIF The microcontroller s clock oscillator does not run during sleep mode so the timer register overflow cannot cause any interrupt Timer TMR1 Oscillator The power consumption of the microcontroller is reduced to the lowest level in Sleep mode The point is to stop the oscillator Anyway it is easy to set the timer in this mode by writing a SLEEP instruction to the program A problem occurs when it is necessary to wake up the microcontroller because only an interrupt can do that Since the microcontroller sleeps an interrupt must be triggered by external electronics It can all get incredibly complicated if it is necessary the wake up occurs at regular time Intervals http www mikroe com en books picmcubook ch4 7 of 12 5 3 2009 11 32 57 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 4 Timers TIOSCEN TMR1CS Q d B A A i A E uU E c E i l Prescaler y 1 2 4 8 Synchronization sE a TICKPSO a T1CKPS1 Clock H Fig 4 9 Timer TMR1 Oscillator In order to solve this problem a completely independent Low Power quartz oscillator ab
147. bank 1 in order to enable access to the TRISB register to configure port B as output banksel TRISB The main program ends by selecting memory bank 0 and setting all port B pins to logic one 1 moviw OxFF movwf PORTB It is necessary to create a loop to keep program from getting lost in case an error occurs For this purpose there is an endless loop executed all the time while the microcontroller is switched on ena is required at the end of every program to inform the assembler that there are no more commands to be compiled DATA FILES RESULTING FROM PROGRAM COMPILING The result of compiling a program written in assembly language are data files The most important and most commonly used data files are e Executive data file Program Name HEX e Error data file Program Name ERR and e List data file Program Name LST The first file contains compiled program which is loaded into the microcontroller Its contents give no information of importance to the programmer so it will not be discussed here The second file contains errors made in writing process and detected by the compiler during compiling process Errors can be detected in list data file which takes more time so the error data file is more suitable for long programs The third file is the most useful for the programmer It contains lots of information on commands and variables locations in on chip memory as well as error signalization There is a symbol table at the end of
148. bit microprocessor at that time Besides Zilog other new manufacturers such as Mostek NEC SHARP and SGS appeared soon The Z80 was the heart of many computers such as Spectrum Partner TRS703 Z 3 and Galaxy In 1976 Intel came up with an upgraded version of the 8 bit microprocessor called the 8085 However the Z80 was so much better that Intel lost the battle Even though a few more microprocessors appeared later on the market 6809 2650 SC MP etc the die had already been cast There were no such great improvements which could make manufacturers to change their mind so the 6502 and Z80 along with the 6800 remained chief representatives of the 8 bit microprocessors of that time Microcontroller versus Microprocessor A microcontroller differs from a microprocessor in many ways The first and most important difference is its functionality In order that the microprocessor may be used other components such as memory must be added to it Even though the microprocessors are considered to be powerful computing machines their weak point is that they are not adjusted to communicating to peripheral equipment Simply In order to communicate with peripheral environment the microprocessor must use specialized circuits added as external chips In short microprocessors are the pure heart of the computers This is how it was in the beginning and remains the same today http www mikroe com en books picmcubook ch0 2 of 30 5 3 2009 11 28 39 AM mikr
149. by one bit left toward bit 7 or right toward bit 0 The bit shifted from the register is moved to the flag C which is automatically moved to the bit on the opposite side of the register Bit oriented Instructions Instructions BCF and BSF clear or set any bit in memory Although it seems to be a simple operation it is not like that CPU first reads the entire byte changes one its bit and rewrites the whole byte to the same location Program Control Instructions http www mikroe com en books picmcubook ch9 3 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set The PIC16F887 executes instructions GOTO CALL RETURN in the same way as all other microcontrollers do A difference is that stack is independent from internal RAM and has 8 levels The RETLW k instruction is identical to RETURN instruction with exception that a constant defined by instruction operand is written to the W register prior to return from subroutine This instruction enables Lookup tables to be easily created by creating a table as a subroutine consisting of RETLWK instructions where the literals k belong to the table The next step is to write the position of the literals k 0 1 2 3 n to W register and call the subroutine table using the CALL instruction Table below consists of the following literals k0 k1 k2 kn Main movlw 2 wrceite mumber 2 to accumulator Gell Lookup romp i
150. caler assignment from TMRO to the watch dog timer the following instruction sequence must be executed in order to avoid reset BANKSEL TMRO CLEWD aT CLEAR WDT CERE TMRO CLEAR TMRO AND PRESCALER BANKSEL OPTION REG Bol CP DIONE EG PSAT EPRE CACER To S SB DUE ID TOTTE WDT CLRWDT CLEAR WDT MOV LW lo TE ELLE Oem nq BIE PS E SOTAND A TEAR ANDWE JETER Teac PEI TIENES JU C TION EOC UOTE PETRUS IORLW oe OOO CO BETS ers ape ERI SO EN MOVWE OP TIONZREG PRESCALER RATE TO W232 Likewise when changing the prescaler assignment from the WDT to the TMRO the following instruction sequence must be executed http www mikroe com en books picmcubook ch4 4 of 12 5 3 2009 11 32 57 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 4 Timers BANKSEL TMRO CERWDT CLEAR WDT AND PRESCALER BANKSEL OPTTON REG MOVLW OO O RSS DNI SETS pep ANDWE OP TEE BOIS W CLEAR THEM AFTERWARDS BY INSTRUCTION LOGICAL AND7 IORLW ib OOO OC Oia PRESCALER RATE TS 1 16 MOVWE OE TTONEREG In order to use TMRO properly it is necessary To select mode e Timer mode is selected by the TOCS bit of the OPTION REG register TOCS O timer 1 counter e When used the prescaler should be assigned to the timer counter by clearing the PSA bit of the OPTION REG register The prescaler rate is set by using the PS2 PSO bits of the same register and e When using interrupt the GIE and TMROIE bits of the INTCON register should be set
151. certainly many advantages in using elements for frequency stabilization but sometimes they are really unnecessary It is mostly sufficient that the oscillator operates at frequency not precisely defined so that embedding of such expensive elements means a waste of money The simplest and cheapest solution in these situations is to use one resistor and one capacitor for the operation of oscillator There are two modes RC mode In RC mode the RC circuit is connected to the OSC1 pin as shown in figure The OSC2 pin outputs the RC oscillator frequency divided by 4 This signal may be used for calibration synchronization or other application requirements Fig 8 9 RC Mode RCIO mode Similar to the previous case the RC circuit is connected to the OSCI pin This time the available OSC2 pin is used as additional general purpose I O pin Fig 8 10 RCIO Mode OBC Pin NO In both cases it is recommended to use components as shown in figure The frequency of such oscillator is calculated according to the formula f 1 T in which f frequency Hz T R C time constant s R resistor resistance Q C 2 capacitor capacity F Internal Clock Modes The internal oscillator circuit consists of two separate oscillators that can be selected as the system clock source The HFINTOSC oscillator is factory calibrated and operates at 8 MHz Its frequency can be user adj usted via software using bits of the OSCTUNE register and The LFINTOSC
152. cimal number conversion is performed in macro digbyte Counter may be reset to its starting value 99 at any moment by pressing the pushbutton COUNTER RESET VCC 5V COUNTER RESET ps GND vC RE D VCC 5 mM ce u MCU RESET GND MA oe 8839L Old 5 E d o e ml v 4MHz 3 2x20 30pF LI GND http www mikroe com en books picmcubook appb 41 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples Example 13 P IQ M aD UM RA I UM Header OBRA RA BORGO AE SOR TAY Wal Tal Wal Yak A Wal Wal Wal Za WAR VAY Wak Yar Wal Yak US aS US Yak Way A RAS Wak Was TA Wal Wal Wak A PE SSS SI D oS Und cd SPS Qa Mud S ES Ls STASIS Uo eS st cgo ui C os PSS TAS LL LLG Ce a UA oS AS Tah C D d aS Dd ud aS HS EA spits al Aa DEFINING VARIABLES IN PROGRAM w temp EQU Ox7D Variable for saving W register status temp HOU OE A Variable tor saving 9IAIUS register Pelari tenp HOU sce Variable for saving PCLATH register PIENO 0532 0 Block of variables starts at address 20h Digtemp Digo FN ables To di playing digilis ce Lob Dael Dibopz Danes py encata lo les 16012 Cli ego diceva mer eb epis so c IM SIs Dyal Counter value One Auxiliary variable which determines which asp lay as to orc swa eehedmon ENDE 2E On block Of variables POCNE EOU THO 7 Initial Counter vilus Ts J9 include DEOD e ao o I NM RIA D A A NU IM EU QU A AU UE
153. cleared in software o 0 Comparator C2 output has not changed e CIIF Comparator C1 Interrupt Flag bit o 1 Comparator C1 output has changed bit CLOUT This bit must be cleared in software o 0 Comparator C1 output has not changed e EEIF EE Write Operation Interrupt Flag bit o 1 EEPROM write completed This bit must be cleared in software o 0 EEPROM write is not completed or has not started e BCLIF Bus Collision Interrupt Flag bit o 1 Le bus collision has occurred in the MSSP when configured for 12C Master mode This bit must be cleared in software o 0 No bus collision has occurred e ULPWUIF Ultra Low power Wake up Interrupt Flag bit o 1 Wake up condition has occurred This bit must be cleared in software o 0 No Wake up condition has occurred e CCP2IF CCP2 Interrupt Flag bit o 1 CCP2interrupt condition has occurred unit for capturing comparing and generating PWM signal Depending on operating mode capture or compare match has occurred In both cases the bit must be cleared in software This bit is not used in PWM mode o 0 No CCP2 interrupt condition has occurred PCON register The PCON register contains only two flag bits used to differentiate between a power on reset brown out reset Watchdog Timer Reset and external reset through MCLR pin ULPWUE SBOREN POR BOR Legend Unimplemented bit RW Readable Writable bit 0 After reset bit is cleared http
154. co uns lookup table EEO O a a TEO a ao cum cios eiacl XE oe a Sue rent address PCL retlw kO0 edm from Subroutine accumulator Contains k0 retiw kil ETT retlw k2 p En MM IPS retlw kn scent rr Brom Subroutine accumulator contains kn The first line of the subroutine instruction ADDWF PCL simply adds a literal k from W register and table start address which is stored in the PCL register The result is real data address in program memory Upon return from the subroutine the W register will contain the addressed literal k In this case it is the k2 literal RETFIE RETurn From IntErrupt represents a return from interrupt routine In contrast to the RETURN instruction it may automatically set the GIE bit Global Interrupt Enable When an interrupt occurs this bit is automatically cleared Only the program counter is pushed to the stack which means that there is no auto save of registers status and the current status either The problem is solved by saving status of all important registers at the beginning of interrupt routine These values are retrieved to these registers immediately before leaving the interrupt routine Conditional jumps are executed by two instructions BTFSC and BTFSS Depending on the state of bit being tested in the f register the following instruction will be skipped or not Instruction Execution Time All instructions are single cycle instructions The only exception may be c
155. coming in that way a part of several bytes which together form Config Word During programming the bytes of Config Word are written to the microcontroller s ROM memory and stored in special registers which are not available to the user On the basis of these bits the microcontroller knows what to do although it is not explicitly specified in the written program AT H5 EL RAG as 140 R as CLEIN INTOSCI O RAB as 1 0 RA as 10 INTOSC RAS as CLEOUT RA as 1 0 ACIO RAS as VO AA as RC AC AAG as CLEOUT RA as RC Ex mikroElektronika PicFLASH v7 07 with mikrolCD File Device Buffer Windows USB About History Configuration Bits n Code Probect Oscillator y F gt Nore T Watchdog Timer Enabled r C DOOUR 1FFFh All Data EE Protect Disabled wine protection Off M ee C 0000h O0FFh Protected C DOOUh O7FF Protected Int Ext Switchover Enabled C 0000h OFFFh Protected Fail amp afe Clk Monitor Enabled hal Low Voltage Program Enabled Calibiati i In Circuit Debugger ICO Disabled 7 e Pr i Cal Word Brown out Reset Sel cet to d O F ID Locations Program Memory Size 8 E Device Status Idle Type A EEPROM Sue 256 Bytes Address Oh Revision http www mikroe com en books picmcubook ch8 3 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits EEPROM Size 256 Bytes Address Oh Rievion Fi
156. cution This address is cleared upon return to the main program because there is no need to save it any longer and one location of the stack is automatically available for further use It is important to understand that data is always circularly pushed onto the stack It means that after the stack has been http www mikroe com en books picmcubook ch1 13 of 14 5 3 2009 11 31 25 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview pushed eight times the ninth push overwrites the value that was stored with the first push The tenth push overwrites the second push and so on Data overwritten in this way is not recoverable In addition the programmer cannot access these registers for write or read and there is no Status bit to indicate stack overflow or stack underflow conditions For that reason one should take special care of it during program writing Interrupt System The first thing that the microcontroller does when an interrupt request arrives is to execute the current instruction and then stop regular program execution Immediately after that the current program memory address is automatically pushed onto the stack and the default address predefined by the manufacturer is written to the program counter That location from where the program continues execution is called the interrupt vector For the PIC16F887 microcontroller this address is 0004h As seen in Fig 1 7 below
157. d at that frequency or after being divided in prescaler and The LFINTOSC is a low frequency internal oscillator which operates at 31 kHz Its clock sources are used for watch dog and power up timing but it can also be used as a clock source for the operation of the entire microcontroller The system clock can be selected between external or internal clock sources via the System Clock Select SCS bit of the OSCCON register OSCCON Register The OSCCON register controls the system clock and frequency selection options It contains the following bits frequency selection bits IRCF2 IRCF1 IRCFO frequency status bits HTS LTS system clock control bits OSTA SCS Le IRCF2 IRCF1 IRCFO osts HTS LTS scs Bit is unimplemented Readable Writable bit Readable bit After reset bit is cleared After reset bit is set Fig 8 2 OSCCON Register IRCF2 0 Internal Oscillator Frequency Select bits Combination of these three bits determines the divider rate The clock frequency of internal oscillator is also determined in this way IRCF2 IRCF1 IRCFO Frequency OSC 1 1 1 8 MHz HFINTOSC 1 1 0 4 MHz HFINTOSC 1 0 1 2 MHz HFINTOSC ij 0 0 1 MHz HFINTOSC 0 1 1 500 kHz HFINTOSC 0 1 0 250 kHz HFINTOSC 0 0 1 125 kHz HFINTOSC 0 0 0 31 kHz LFINTOSC Table 8 1 Internal Oscillator Frequency Select Bits OSTS Oscillator Start up Time out Status bit indicates which clock source is currently in use This bit is readable only e 1 Ext
158. d on falling edge of clock pulse 1 0 http www mikroe com en books picmcubook ch6 19 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules CKP 1 e 1 Data is transmitted on falling edge of clock pulse 1 0 and e 0 Data Is transmitted on rising edge of clock pulse 0 1 D A Data Address bit is used in I2C mode only e 1 Indicates that the last byte received or transmitted was data and e 0 Indicates that the last byte received or transmitted was address P Stop bit is used in I C mode only e 1 STOP bit was detected last and e 0 STOP bit was not detected last S Start bit is used in IC mode only e 1 START bit was detected last and e 0 START bit was not detected last R W Read Write bit is used in IC mode only This bit holds the R W bit information following the last address match This bit is only valid from the address match to the next Start bit Stop bit or not ACK bit In 12C slave mode e 1 Data read and e O Data write In 12C master mode e 1 Transmit is in progress and e 0 Transmit is not in progress UA Update Address bit is used in 10 bit 12C mode only e l Indicates that it is necessary to update the address in the SSPADD register and e 0 Address in the SSPADD register is correct and does not need to be updated BF Buffer Full Status bit During data receive in SPI and I C modes e 1l
159. d program and passes it into the microcontroller PIC Flash for example Start up this program The settings are simple and there is no need for additional explanations the type of the microcontroller frequency and clock oscillator etc e Connect the PC and programmer via a USB cable e Load the HEX code using command File Load HEX and e Click the Write push button and wait http www mikroe com en books piemcubook appe 5 of 7 5 3 2009 11 36 25 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix C Development Systems mikroblektronika PicFLASH v7 07 with mikrolCD Ele Device Buffer Windows LSB About Hetory A PICIOFSE o m EPICIe amp FBS Oscillator IHTOSCID RAE a 1D R s 1 0 iis Watchdog Timer Deabled DODOh TFFFh All Power Up Timer Enabled verify Blank FLASH Program Memory Data EE Protect Ocabled r Wie prolechon ON Brown Out Detect EOD Disabled QO000h ODFFh Protected r DOOth OF FF RK Protected Int Emskt Switchover Disabled Enc Reload HEX C 0000A OFFFh Prictecled Fail safe Cik Monitor Enabled Save HEX Low Voltage Program cabled Calibration weed Protect Cal Word In Circuit Debugger CD Disabled Brown out Reset Sel oti to 21 ID Locations FFF 3FFF 3FFF 3FFF Program Memory See B K Device Status bdie EEPROM See 256 Bytes Address Oh File DAPIC PROJEKT PRIMER L HEX Device PIC L6FBE Operation None Tha
160. dave lines on REO SS RS EQU RS line connected to REA EN EOU gt EN Tine connected to RBD a AD E PL UI C Ic Du x RTI EDAM AAA ORG OOO Reset vector address nop Gp main Go to beginning or the program dese A RS MS M EM M ES M EM M S SE E M E I dE E MEE E E S E E E E include UI e include ccoo ie include Pause vine RR ONU E TOP RO cs anaes LDAP UE main banksel ANSEL Selects bank containing ANSEL el ANSEL ANM pins abe digital GL ear ANSELH Det S TARUS REO TEANO ey O Der SPATIO REI movlw WE movwf temp Move arbitrary value to variable SEO eso layed om uel ike e boote s ECD initialization LOOO EE Ox On e a erste BOE lon eo clear TCD lcdtext 1 mikroelektronika Write text from the begin Ming of the First Line lcdtext 2 Beograd Write text from the beginning of the second line pausems 221910100 2 sec delay edema OSO y Instruciion Lo clear LCD lcatext 1 Temperatura Write text from the begun 7 Ming Orte First lane lcdtext 2 temp Write text from the beginning of the second line lcdbyte temp Write variable dec aci ze O er Welke text atter cursor pausems OOO 2 sec delay GOLO Loop ES ncs us US ES ost us E uq ts sra us rus Causis E USS TATA us UAE UAE TAS rr tug ug ES us usus ta tus ce tap cst end RC ELO Ou TOS COE HE GI LCD inc Daf Ua Eat aS AUN CaF ah uI OSA EK uS eS Tak Rak a Pah ak Wak RPG IR A QUARC AUDI Gal al Cah eas Gal Ca Tak ak ah a Tat ARTS aS a ACIE eal Tae AIO ARDEN CA
161. de there are no clock inputs to use for synchronization However the prescaler will continue to run if there are clock pulses on the pins since it is just a simple frequency divider http www mikroe com en books picmcubook ch4 8 of 12 5 3 2009 11 32 57 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 4 Timers TMR1ON B T1SYNC Pulses to count om Fr m ma um cum cam as mm cum c m ow Mn i 1 Prescaler s cem TIAM e oe TMRAH TMRIL J J A Ea g i x ENER Synchronization e gt ES IMRi 8 TICKPSO E TICKPS1 Clock sar 3 l w ce I1 j Fig 4 11 Counter Mode TICKI 4 This counter registers a logic one 1 on input pins It is otal important to understand that at least one falling edge must be registered prior to the first increment on rising F edge Refer to figure on the left The arrows in figure 4 11 ir Ar t 4 denote counter increments TICKI 0 Counter on T1CON Register Legend RW Readable Writable bits 0 After reset bit is cleared Fig 4 12 T1CON Register T1GINV Timerl Gate Invert bit acts as logic state inverter on the T1G pin gate or the comparator C2 output C20UT gate It enables the timer to mea sure time whilst the gate is high or low e l Timer 1 counts when the pin T1G or bit C2OUT gate is high 1 and e 0 Timer 1 counts when the pin TIG or bi
162. down approximately 250 times more Because of this the microcontroller uses internal oscillator LFINTOSC with the frequency of 31kHz instead of the external oscillator with quartz crystal 8MHz You have noticed that the clock signal source has changed on the fly If you want to make sure of it remove quartz crystal prior to switching the microcontroller on What will happen The microcontroller will not start operating because the config word loaded with the program requires the use of the crystal on switching on If you remove the crystal later during the operation it will not affect the microcontroller at all qux 10K RESET LS C STOP f Pp 2x20 30pF ul GND AJA LED y 330R 88391 Old AN LED 330R AA LED 330R LED 330R GND Example 2 SIRO AGUA A A RA RAE A ROCA uS ua US S AER Ab A IB BS Yak Vad Unk IAEA Tal Cah Ae RAR AAN A PAS u Pal ORAE AGAS SKK QUARC ARS ARA UAE E UA Pal Cah RIA uS S US ES DAUD Fal TAS a Header o xu uM M C E x M E A I E O vo OS gb sb dE dE db EV vo mo vd Us EE DE A E E E EA A A A A bd SS HS SS ES STS TS sb vy sb gb bob gcc DEFINING VARIABLES cole 70x20 Block of variables starts at address 20h counter Variable counterl at address 20h endc http www mikroe com en books picmcubook appb 22 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples i
163. e but not the contents of the port bits By clearing some bit of the TRIS register bit 0 the corresponding port pin is configured as output Similarly by setting some bit of the TRIS register bit 1 the corresponding port pin is configured as input This rule is easy to remember 0 Output 1 Input http www mikroe com en books picmcubook ch3 1 of 10 5 3 2009 11 32 31 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 3 I O Ports MICROCONTROLLER Sensor 5V Fig 3 1 1 0 Ports Port A and TRISA Register Port A is an 8 bit wide bidirectional port Bits of the TRISA and ANSEL control the PORTA pins All Port A pins act as digital inputs outputs Five of them can also be analog inputs denoted as AN http www mikroe com en books picmcubook ch3 2 of 10 5 3 2009 11 32 31 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 3 I O Ports TRISA7 TRISAG TRISAS TRISA4 TRISA3 TRISA2 TRISA1 TRISAO Legend RAV Readable Writable bit x After reset bit is unknown 1 After reset bit is set Fig 3 2 Port A and TRISA Register Similar to bits of the TRISA register which determine which of the pins will be configured as input and which as output the appropriate bits of the ANSEL register determine whether the pins will act as analog inputs or digital inputs outputs e RAO ANO determined by bit ANSO of the ANSEL register e RA1 ANI determined by b
164. e 0 Slave mode Clock is generated from external source TX9 9 bit Transmit Enable bit 9 bit data transmission via EUSART system and 8 bit data transmission via EUSART system e l e 0 TXEN Transmit Enable bit e 1 Transmission enabled and e 0 Transmission disabled SYNC EUSART Mode Select bit e 1 EUSART operates in synchronous mode and e 0 EUSART operates in asynchronous mode http www mikroe com en books picmcubook ch6 6 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules SENDB Send Break Character bit is only used in asynchronous mode and only in case it is required to observe LIN bus standard e l Sending Break character is enabled and e 0 Break character transmission is completed BRGH High Baud Rate Select bit determines baud rate in asynchronous mode It does not affect EUSART in synchronous mode e 1 EUSART operates at high speed and e 0 EUSART operates at low speed TRMT Transmit Shift Register Status bit e 1l TSR register is empty and e O TSR register is full TX9D Ninth bit of Transmit Data can be used as address or parity bit RCSTA Register SPEN RX9 SREN CREN ADDEN FERR OERR RX9D Readable Writable bit Readable bit After reset bit is cleared After reset bit is unknown Fig 6 9 RCSTA Register SPEN Serial Port Enable bit e l Serial port enabled RX DT and
165. e 0 Comparator C2 output is non inverted C2R Comparator C2 Reference Select bit e 1 Non inverting input C2Vin is connected to reference voltage C2Vref and e 0 Non inverting input C2Vin is connected to the C2IN pin C2CH1 C2CHO Comparator C2 Channel Select bit http www mikroe com en books picmcubook ch7 11 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules C2CH1 C2CHO Comparator C2Vin input 0 0 Input C2Vin is connected to the C12IN0 pin 0 1 Input C2Vin is connected to the C12IN1 pin 1 0 Input C2Vin is connected to the C12IN2 pin 1 1 Input C2Vin is connected to the C12IN3 pin Table 7 5 Comparator C2 Channel Select Bit CM2CON1 Register MCTOUT MC2OUT CIRSEL C2RSEL TIGSS C2SYNC Legend Bit is unimplemented Readable Writable bit Readable bit After reset bit is cleared After reset bit is set Fig 7 12 CM2CON1 Register MCIOUT Mirror Copy of C1OUT bit MC20UT Mirror Copy of C20UT bit C1RSEL Comparator C1 Reference Select bit e 1l Selectable voltage CVref is used in voltage reference C1Vref source and e 0 Fixed voltage reference 0 6V is used in voltage reference C1Vref source C2RSEL Comparator C2 Reference Select bit e l Selectable voltage CVref is used in voltage reference C2Vref source and e 0 Fixed voltage reference 0 6V is used in voltage reference C2Vref source T1GSS Timerl Gate Source Select bit
166. e a software time delay a few milliseconds to ensure proper oscillator start up e Table below shows the recommended values of capacitors to suit the quartz oscillator These values do not have to be exact However the general rule is the higher the T1080 T1IOSI capacitor s capacity the higher the stability which at the same time prolongs the time needed for the oscillator stability 32 760 kHz Oscillator Frequency C1 C2 32 kHz 33 pF 33 pF El p LP 100 kHz 15 pF 15 pF icm xi 200 kHz 159 15pF GND http www mikroe com en books piemcubook ch4 6 of 12 5 3 2009 11 32 57 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 4 Timers Fig 4 7 Timer TMR1 Oscillator Timer TMR1 Gate Timer 1 gate source is software configurable to be the T1G pin or the output of comparator C2 This gate allows the timer to directly time external events using the logic state on the T1G pin or analog events using the comparator C2 output Refer to figure 4 7 above In order to time a signals duration it is sufficient to enable such gate and count pulses having passed through it TMRI in timer mode In order to select this mode it is necessary to clear the TMR1CS bit After this the 16 bit register will be incremented on every pulse coming from the internal oscillator If the 4MHz quartz crystal is in use it will be incremented every microsecond In this mode the T1SYNC bit does not affect the timer bec
167. e acknowledge data bit The slave device acknowledges address match by clearing the ASKSTAT bit of the SSPCON2 SDA pin register If the match properly occurred all bytes SSPBUF 0 x x x x x X x lt lt qn representing data are transmitted in the same way Data B ERA Dee SSPCON 2 register The so SSPCON2 Acknowledge called STOP condition occurs which enables the SDA pin to receive pulse condition Start Address Acknowledge Data Acknowledge Data Acknowledge Stop Data Fig 6 29 Data Transmission in JL IC Master Mode 7 SDA pin SSPBUF XXXXXXI Ann Data Reception in IC Master Mode Preparations for data reception are similar to those for data transmission with exception that the last bit of the first sent byte containing address is logic one 1 It specifies that master expects to receive data from addressed slave device With regard to the microcontroller the following events occur After internal preparations are finished and START bit is set slave device starts sending one byte at a time These bytes are stored in the serial register SSPSR Each data Is after receiving the last eighth bit loaded to the SSPBUF register from where it can be read By reading this register the acknowledge bit is automatically sent which means that master device is ready to receive new data At the end similar to data transmission data reception ends by setting the STOP bit htt
168. e between them Therefore it is very important to learn how to convert numbers from one numbering system to another i e how to turn a series of zeros and units into values understandable to us Binary to Decimal Number Conversion Digits in a binary number have different values depending on their position in that number Additionally each position can contain either 1 or 0 and its value may be easily determined by its position from the right To make the conversion of a binary number to decimal it is necessary to multiply values with the corresponding digits 0 or 1 and add all the results The magic of binary to decimal number conversion works You doubt Look at the example euer tr a Lae a n ue A a real It should be noted that for decimal numbers from 0 to 3 you only need two binary digits For greater values extra binary digits must be added Thus for numbers from 0 to 7 you need three digits for numbers from 0 to 15 four digits etc Simply speaking the largest binary number consisting of n digits is obtained when the base 2 is raised by n The result should be then subtracted by 1 For example if n24 24 1 16 1 15 Accordingly using 4 binary digits it is possible to represent decimal numbers from 0 to 15 including these two digits which amounts to 16 different values in total Hexadecimal to Decimal Number Conversion http www mikroe com en books picmcubook ch0 6 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online
169. e in the previous http www mikroe com en books picmcubook ch0 4 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers example but in reverse order Bear in mind that all this is about mathematics with only two digits 0 and 1 i e base 2 number system binary number system Seventh position in number Zeroth position in number Base 2 number system 11011010 1 27 1 2 0 27 1 2 1 2 027 1 2 0 02 MEME 11011010 128 64 0 16 8 0 2 0 218 Number 218 in binary system Number 218 in decimal system Fig 0 3 The number 218 represented in binary and decimal system Clearly it is the same number represented in two different ways The only difference is in the number of digits necessary for writing some number One digit 2 is used to write the number 2 in decimal system whereas two digits 1 and 0 are used to write that number in binary system Do you now agree that there are 10 groups of people Welcome to the world of binary arithmetic Do you have any idea where it is used Excepting strictly controlled laboratory conditions the most complicated electronic circuits cannot accurately determine the difference between two sizes two voltage values for example if they are too small lower than several volts The reasons are electrical noises and something called the real working environment unpredictable changes of power supply voltage te
170. e result EXAMPLE 1 MOVLW 10 MOVWF CNT PA CINE reso EN ws EN cU IS EUG E Lom uel exl DECFSZ CNT f decrement REG by one GOTO Loop okip wines nes a QU A O Jump here if OQ In this example instruction block is executed as many times as the initial value of the variable CNT is which in this example is 10 GOT O Unconditional Branch Syntax label GOTO k Description Unconditional jump to the address k Operation k PC 10 0 PCLATH 4 3 PC 12 11 Operand 0 x k lt 2047 Status affected Number of cycles 2 EXAMPLE LAB 00 GOTO LAB 01 Jump to LAB 01 http www mikroe com en books picmcubook ch9 17 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set IDEO m Program conteinucs Irom herc Before instruction execution PC LAB 00 address After uWnsteduccdomnm PC TAB 01 address INCF Increment f Syntax label INCF f d Description Increment register f by one If d w or d 0 the result is stored in register W If d f or d 1 the result is stored in register f Operation f 1 gt d Operand 0 lt f lt 127 d 0 1 Status affected Z Number of cycles 1 EXAMPLE 1 label INCF REG w Before instruction execution REG 0x10 W x Z 0 Boernetructuaome REG 0x10 W 0x11 2 0 EXAMPLE 2 label INCF REG f http www mikroe com en books picmcubook ch9 18 of 35 5 3 2009 11 35 12 AM
171. e separately discussed since each has specific functions features and organization ROM Memory ROM memory is used to permanently save the program being executed This is why it is often called program memory The PIC16F887 has 8Kb of ROM in total of 8192 locations Since this ROM is made with FLASH technology its contents can be changed by providing a special programming voltage 13V Anyway there is no need to explain it in detail because it is automatically performed by means of a special program on http www mikroe com en books picmcubook chl 7 of 14 5 3 2009 11 31 25 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview the PC and a simple electronic device called the Programmer Writing program in assembly language simulator tool Copy program compiling to to ROM Memory machine code ae 0 0 0 1 5 lia f ST k B Fig 1 5 ROM Memory Consept EEPROM Memory Similar to program memory the contents of EEPROM is permanently saved even the power goes off However unlike ROM the contents of the EEPROM can be changed during operation of the microcontroller That is why this memory 256 locations is a perfect one for permanently saving results created and used during the operation RAM Memory This is the third and the most complex part of microcontroller memory In this case it consists of two parts general purpose registers and speci
172. e terms of the icense agreement E Hu NN http www mikroe com en books picmcubook appa 11 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller MPLAB Tools v7 60 Setup Type Do you want to install the entire software Yes Next Select the setup type to install Please select a setup type Complete All program features wil be inslalled Flequres the most disk space Select which program heabures pou want installed Recommended For advanced users MPLAB Tools v7 60 Chonta Dastination Lecation Similar to other programs MPLAB should be also installed o MER EM KS Microchip into a folder It may be any folder on any hard disc If it is P not necessary to make changes select the specified address and click Next Setup will instal MPLAB Tools v7 60 in the following folder To install bo trus folder click Next To mstall to different holder click Browse and select another bolda Destination Folder C Program Filezddicroachips Another license another acceptance of options specified by the computer Next MPLAB Tools 60 Next Staal Copying Files Feval j Setup Status Salug rod Ser PN MICROCHIP Dog CO AGI MPLAB Took v7 50 i configunng pour new software installation FE E IF fe z CA AMiierochipuMPASM Suite Template Object AFSOS4G TMPO_LASM TTT http www mikroe com en books picmcuboo
173. e up interrupt CCP2IE CCP2 Interrupt Enable bit http www mikroe com en books picmcubook ch2 7 of 12 5 3 2009 11 32 08 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 2 Core SFRs o 1 Enables CCP2 interrupt o 0 Disables CCP2 interrupt PIR1 Register The PIR1 register contains the interrupt flag bits ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF_ Legend Unimplemented bit RW ReadableWritable bit R Readable bit 0 After reset bitis cleared Fig 2 13 PIR1 Register e ADIF A D Converter Interrupt Flag bit o 1 A D conversion is completed bit must be cleared in software o 0 A D conversion is not completed or has not started e RCIF EUSART Receive Interrupt Flag bit o 1 The EUSART receive buffer is full Bit is cleared by reading the RCREG register o 0 The EUSART receive buffer is not full e TXIF EUSART Transmit Interrupt Flag bit o 1 The EUSART transmit buffer is empty Bit is cleared by writing to the TXREG register o 0 The EUSART transmit buffer is full e SSPIF Master Synchronous Serial Port MSSP Interrupt Flag bit o 1 The MSSP interrupt condition during data transmit receive has occurred These conditions differ depending on MSSP operating mode SPI or 12C This bit must be cleared in software before returning from the interrupt service routine o 0 No MSSP interrupt condition has occurred e CCPIIF CCP1 Interrupt Flag bit o 1
174. each data file list containing all the symbols used in a program Other useful elements of list data file are memory usage maps and error statistics provided at the very end of the file list MACROS AND SUBROUTINES The same sequence of computing instructions is usually used repeatedly within a program Assembly language is very demanding The programmer is required to take care of the last little detail when writing a program because only one wrong command or label name may cause the program to not work properly or it may not work at all Therefore it is less tedious and less error prone to use a sequence of instructions as a single program statement which works properly for sure To implement this idea macros and subroutines are used MACROS A macro contains programmer defined symbols that stand for a sequence of text lines It is defined by using directive macro which names macro and arguments if needed Macro must be defined prior it is used Once a macro has been defined its name may be used in the program When the assembler encounters macro s name it replaces it by the appropriate sequence of instructions and processes them just as though they have appeared in the program Many different macro instructions are available for various purposes eliminating some of the repetitiveness of the programming as well as simplifying the writing reading and understanding of the program The simplest use of macros may be giving a name to an instruction s
175. eal solution would be the microcontroller wakes up periodically by itself which is not impossible at all The circuit which enables that is shown in figure on the right Fig 3 3 ULPWU Unit The principle of operation is simple A pin is configured as output and logic one 1 is brought to it That causes the capacitor to be charged Immediately after this the same pin is configured as an input The change of logic state enables an interrupt and the microcontroller is set to Sleep mode Afterwards there is nothing else to be done except wait for the capacitor to discharge by the leakage current flowing out through the input pin When it occurs an interrupt takes place and the microcontroller continues with the program execution in normal mode The whole sequence is repeated http www mikroe com en books picmcubook ch3 3 of 10 5 3 2009 11 32 31 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 3 1 O Ports Theoretically this is a perfect solution The problem is that all pins able EN to cause an interrupt in this way are digital and have relatively large leakage current when their voltage is not close to the limit values Vdd 1 Interrupt or Vss 0 In this case the capacitor is discharged for a short time since the current amounts to several hundreds of microamperes This is why the ULPWU ULPWU circuit able to register slow voltage drops with ultra low power consumption was designed Its output generates
176. ectronic circuit which can memorize the state of one byte http www mikroe com en books picmcubook ch0 11 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Fig 0 17 Register Special Function Register In addition to the registers which do not have any special and predetermined function every microcontroller has a number of registers whose function is predetermined by the manufacturer Their bits are connected literally to internal circuits such as timers A D converter oscillators and others which means that they are directly in command of the operation of the microcontroller Imagine eight switches which are in command of some smaller circuits within the microcontroller you are right Special Function Registers SFRs do exactly that http www mikroe com en books picmcubook ch0 12 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers 777777 SER register i Tes nn _ Fig 0 18 Special Function Register Input Output Ports In order to make the microcontroller useful it has to be connected to additional electronics i e peripherals Each microcontroller has one or more registers called a port connected to the microcontroller pins Why input output Because you can change the pin s function as you wish For example suppose you want your device to turn th
177. ed as eis pis and used tor J segment display multiplexing uic aput ol S Is Ete m enel EE deno movwf TRISA ellie TRISD BANKSEL CIE TIE ONES UE movlw OOOO TMRO is incremented each 32us Fclk 8MHz movwt ORTTONMEEG BANKSEL PORTA movlw eere us movwf Dyal 7 Dval contains counter value movlw Io ONO DII y lmitaaliwzes vyarvaele secerevying display movwf One dones cbr movwf PORTA movlw 100 movwf TMRO TMRO interrupt appr every 10ms DSi INICON CIE Global interrupt enabled psf JENSEN m ROTE Timer TMRO interrupt enabled bef NEO NAO Loop SS One 3 Falling edge encountered goto Dec Yes Go to Dec 1S LSS PORTA 2 Counter reset button pressed GORG RERS Yes Go to Reset ere e I Oxo Decrement Dval counter by 1 pee piss One 3 goto DOE movft Dyal PEES SPATU gt F Z TTD SO Ue OO goto Loop pl ae aks Es Eo Toes suo wee abone decf Dyal de If Dval not equal to 0 decrement it by 1 CIO o Loop scis oid sls PORTA 2 Wait for rising edge Goro ROSSE movlw LOVE movwf Dval Write initial value to counter goro Loop d EA M UD EA DERE UE M VA MM d DM MEE M UN DIES ORG Osc0S 010 osito te ls at Ene Eee OF toird page Dur can be placed at some other place it is impor http www mikroe com en books picmcubook appb 43 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples tant to have it all on one page cdi ose addwf CI E DT rc OS ISO lo O SS O el OO
178. ed to several meters SPI Serial Peripheral Interface Bus is a system for serial communication which uses up to four conductors usually three one for data receiving one for data sending one for synchronization and one alternatively for selecting the device to communicate with It is full duplex connection which means that data is sent and received simultaneously The maximum baud rate is higher than in I2C connection UART Universal Asynchronous Receiver Transmitter This connection is asynchronous which means that a special line for clock signal transmission is not used In some situations this feature is crucial for example radio connection or infrared waves remote control Since only one communication line is used both receiver and transmitter operate at the same predefined rate in order to maintain necessary synchronization This is a very simple way of transferring data since it basically represents conversion of 8 bit data from parallel to serial format Baud rate is not high up to 1 Mbit sec Oscillator http www mikroe com en books picmcubook ch0 19 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Even pulses coming from the oscillator enable harmonic and synchronous operation of all circuits of the microcontroller The oscillator module is usually configured to use quartz crystal or ceramic resonator for frequency stabilization Fu
179. eeded to establish serial communication while another half is stored in the device the data is exchanged with Even though the modules on both ends of the line are the same their modes are essentially different depending on whether they operate as a Master or a Slave If the microcontroller to be programmed controls another device or circuit peripherals it should operate as a master device A module defined as such will generate clock when needed i e only when data receive and transmit is required by the software It depends on the master whether the connection will be established or not Otherwise if the microcontroller to be programmed is a part of some peripheral which belongs to some more complex device for example LE then it should operate as a slave device As such it always has to wait for request for data transfer from master evice http www mikroe com en books picmcubook ch6 13 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules Fig 6 12 MSSP Module SPI Mode The SPI mode allows 8 bits of data to be transmitted and received simultaneously using 3 input output lines e SDO Serial Data Out transmit line e SDI Serial Data In receive line and e SCK Serial Clock synchronization line In addition to these three lines if the microcontroller exchanges data with several peripheral d
180. ektronika Free Online Book PIC Microcontrollers Appendix B Examples estaria PESTO mr AAA BEES o that ic is almost impossible to make Ele Desce afer Wireless LEE bmi pHubory MOSE RAS ec CLEDUT Fa EIE RCKI HAba WA a AC Device a stable oscillator which operates over a e a rociera wide frequency range the microcontroller Oscillator f must know which crystal is connected in Wakcha Timar F DOU 1FFFh AR fem J are order that it can adjust the operation of its Pr e Taar mm z wt me finternal electronics to it This is why all FLASH E am j j j Hate te EA S E aer aiaa programs used for chip loading contains an EE option for oscillator mode selection See Data EE Protect f Write probschon OF AA FOIT ER m wee above figure Loi C DOR 7FFh Poea Int Ext Switchover 7 Reload HEX C DOR OFFA Fiind or Loe Voltage Program naoded Ir Circuit Debugger CD Diraba Brianne Reset meh patin 21V Calibrator sas Protect Cal Word ID Locskon FF FFF 3FFF 3FFF Poyan Hera See EE Device S idie Tae EEPROM See 256 Bytes Ardas Di Fiaancn Piles CACKOXCLINENTS AMO SETTINGSUMARKO T MEKIDESET COPA TZOUICHPANEL BISFICA PIM TOUCHFANEL MEX Dorem PIC 15 ST Omer nicn ore Quartz resonator When a quartz crystal is used for frequency stabilization the built in oscillator operates at a very precise frequency which is isolated from changes in temperature and voltage power suppl
181. ent which always starts with semicolon and can be written in a new line or immediately after a command After writing this general comment it is time to select the microcontroller by using directive PROCESSOR This directive is followed by another one used to include all the definitions of the PIC16F887 microcontroller s internal registers in the program These definitions are nothing but the ability to address port B and other registers as PORTB instead of 06h which makes the program clearer and more legible In order that the microcontroller will operate properly a several parameters such as the type of oscillator state of the watch dog and internal reset circuit must be defined It is done by utilizing the following directive GONE STU P OERE CAWO TOFEL EWR TETON o OS When all necessary elements are defined the process of program writing can start First and foremost it is necessary to specify the address from which the microcontroller starts when the power goes on org 0x00 as well as the address from which the program proceeds with execution if an interrupt occurs org 0x04 Since this program is very simple it is http www mikroe com en books piemcubook appa 6 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller enough to use command goto Main in order to direct the microcontroller to the beginning of the program The next command selects memory
182. equence being repeated Let us take for example global interrupt enable procedure SFRs bank selection macro name macro argl arg2 Sequence of instructions endm The following example shows four macros The first two macros select banks the third one enables interrupt whereas the fourth one disables interrupt bank0 macro Macro bank0 ber STRESS RPO Reset RPO bit lice SALAMIS PEPI Reset RP1 bit endm ERG Or Macro me Ne Ne a http www mikroe com en books picmcubook appa 7 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller bankl macro Macro Danki DSi MS lATUS SIS Set RPO bit Der o MATUS RPI Reset RP1 bit endm End or macro enableint macro Global interrupt enable To pM NN Set bit endm EN o Or Ide disableint macro Global interrupt disable lox ETE NIIT Reset bit endm End of ma ro Ne Ne Ne Ne Ne No No Ne Ne N Macros defined in this way are saved in a particular data file with extension INC which stands for INCLUDE data file As seen these four macros do not have arguments However macros may include arguments if needed The following example shows macros with arguments Pin is configured as input if the corresponding bit of the TRIS register is set to logic one bank1 Otherwise it is configured as output input macro argl arg2 laico TEST eTERE beroda Pank Comi aaa eS SOS Ee SS sita se Set the specified bit
183. er TMR1ON Timer1 On bit e 1 Enables Timer TMR1 and e 0 Stops Timer TMRI In order to use the timer TMR1 properly it is necessary to perform the following e Since it is not possible to turn off the prescaler its rate should be adjusted by using bits TICKPS1 and T1CKPSO of the register T1CON Refer to table 4 2 e The mode should be selected by the TMRICS bit of the same register TMR1CS O the clock source is quartz oscillator 1 the clock source is supplied externally e By setting the T1OSCEN bit of the same register the timer TMRI is turned on and the TMR1H and TMRIL registers are incremented on every clock input Counting stops by clearing this bit e he prescaler is cleared by clearing or writing the counter registers and e By filling both timer registers the flag TMRIIF is set and counting starts from zero Timer TMR2 Timer TMR2 module is an 8 bit timer which operates in a very specific way http www mikroe com en books picmcubook ch4 10 of 12 5 3 2009 11 32 57 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 4 Timers PWM Unit Synchronous serial port Prescaler 1 1 1 4 1 16 T2CKPS1 ll Postscaler T2CKPSO m ISE TZOUTPSO TZOUTPS1 TZOUTPS2 TZOUTPS3 Fig 4 13 Timer TMR2 The pulses from the quartz oscillator first pass through the prescaler whose rate may be changed by combining the T2CKPS1 and T2CKPSO bits The output of the prescaler is then used to
184. er and if d 1 the prescaler will be cleared 3 If the PC is modified or test result is logic one 1 the instruction requires two cycles Data Transfer Instructions Data Transfer within the microcontroller takes place between working register W called accumulator and a register which represents any location of internal RAM regardless of whether it is about special function or general purpose registers First three instructions move literal to W register MOVLW stands for move Literal to W move data from W register to RAM and from RAM to W register or to the same RAM location with change on flag Z only Instruction CLRF clears f register whereas CLRW clears W register SWAPF instruction swaps nibbles within f register one nibble contains four bits Arithmetic logic Instructions Similar to most microcontrollers PIC supports only two arithmetic instructions addition and subtraction Flags C DC Z are automatically set depending on the results of addition or Subtraction The only exception is the flag C Since subtraction is performed as addition with negative value the flag C is inverted after subtraction It means that the flag C is set if it is possible to perform operation and cleared if the larger number is subtracted from smaller one Logic one 1 of the PIC is able to perform operations AND OR EX OR inverting COMF and rotation RLF and RRF Instructions which rotate a register actually rotate its bits through the flag C
185. er supply is shown above The circuit uses a cheap integrated three terminal positive regulator LM7805 provides high quality voltage stability and quite enough current to enable microcontroller and peripheral electronics to operate normally enough in this case means 1Amp RESET SIGNAL In order that the microcontroller can operate properly a logic one VCC must be applied on the reset pin it explains the connection pin resistor 10K VCC The push button connecting the reset pin MCLR to GND is not necessary However it is almost always provided because it enables the microcontroller safe return to normal operating conditions if something goes wrong By pushing this button OV is brought to the pin the microcontroller is reset and program execution starts from the beginning The 10K resistor is there to allow OV to be applied to the MCLR pin via the push button without shorting the 5VDC rail to ground CLOCK SIGNAL Even though the microcontroller has a built in oscillator it cannot operate without external components which stabilize its operation and determine its frequency operating speed of the microcontroller Depending on which elements are in use as well as their frequencies the oscillator can be run in four different modes LP Low Power Crystal XT Crystal Resonator HS High speed Crystal Resonator and RC Resistor Capacitor http www mikroe com en books picmcubook appb 2 of 54 5 3 2009 11 36 02 AM mikroEl
186. ernal clock oscillator is in use and e 0 One of internal clock oscillators is in use HFINTOSC or LFINTOSC http www mikroe com en books picmcubook ch8 2 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits HTS HFINTOSC Status bit 8 MHz 125 kHz indicates whether high frequency internal oscillator operates in a stable way e 1 HFINTOSC is stable and e 0 HFINTOSC is not stable LTS LFINTOSC Stable bit 31 kHz indicates whether low frequency internal oscillator operates in a stable way e 1 LFINTOSC is stable and e 0 LFINTOSC is not stable SCS System Clock Select bit determines which oscillator is to be used as a clock source e 1 Internal oscillator is used for system clock e 0 External oscillator is used for system clock and The oscillator mode is set by bits in Config Word which are written to the microcontroller memory during programming External Clock Modes In order to enable the external oscillator to operate at different speeds and use different components for frequency stabilization it can be configured to operate in one of several modes Mode selection is performed after the program writing and compiling First of all it is necessary to activate the program on PC used for programming In this case PICflash Click on the oscillator combox and select one option from the drop down list After that the appropriate bits will be set be
187. ers Congratulations on your choice However it is not as easy to choose the right microcontroller as it may seem The problem is not a limited range of devices but the opposite Before you start designing some device based on the microcontroller think of the following how many input output lines will need for operation Should it perform some other operations than to simply turn relays on off Does it need some specialized module such as serial communication A D converter etc When you create a clear picture of what you need the selection range is considerably reduced then it is time to think of price Is your plan to have several same devices Several hundred A million Anyway you get the point If you think of all these things for the very first time then everything seems a bit confusing For that reason go step by step First of all select the manufacturer i e the family of the microcontrollers you can easily obtain After that study one particular model Learn as much as you need do not go into details Solve a specific problem and something incredible will happen you will be able to handle any model belonging to that family http www mikroe com en books picmcubook ch0 28 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Remember learning to ride a bicycle after several unavoidable bruises at the beginning you will manage to keep balance and w
188. es a short optical transmission path to transfer a signal between elements of circuit while keeping them electrically isolated This isolation makes sense only if diodes and photo sensitive elements are separately powered In this way the microcontroller and expensive additional electronics are completely protected from high voltage and noises which are the most common cause of destroying damaging or unstable operation of electronic devices in practice The most frequently used optocouplers are those with phototransistors on their outputs Additionally optocouplers with internal base to pin 6 connection there are also optocouplers without it the base may be left unconnected http www mikroe com en books picmcubook appb 10 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples 48V Q The R C network represented by the broken line in the figure above denotes optional connection which lessens the effects of noises by eliminating very short pulses LCD DISPLAY This component is specifically manufactured to be used with microcontrollers which means that it cannot be activated by standard IC circuits It is used for displaying different messages on a miniature liquid crystal display The model described here is for its low price and great capabilities most frequently used in practice It is based on the HD44780 microcontroller Hitachi and can display messages in two lines with 16 ch
189. essed increment CCPIL by 1 ECT as given its Original Content STATU gt T bs vem ses o cR c oe Rs W 1s given Tes origina content Selects ea c exo eese abimaligve e TE IL Clears interrupt flag TMRIIF Accelerates timer TMRO counting Global interrupt enabled Return from interrupt routine KK KK KK KK KK KK KK KK KK KK KKK KK KKK KK KKK KK KKK KKK KKK KKK KKK KKK KKK KKK MAIN PROGRAM tuos Op banksel ela cla banksel Seu BSE DSi banksel cla banksel OEE BOF DEL DSE banksel DST DSE DSi movlw banksel movwf movlw banksel movwt banksel movlw movw ft ajo mo end EXAMPLE 11 Using A D converter ANSEL ANSEL ANSELH OPTION_REG GOESUNS REG 7 WPUB 0 WPUB 1 TRITSC TIS IE TERON EEC ONA EMRIGE TIC ON EKF Ss TECON cds T ECON EME ION PrE E da INTC ON PETE DINAN ON GA BETTE LOI TZCON IAS ON EA AE PR2 PRZ Cer Econ B OUOMONC A ONG CCPECON LOS Ne oe Ne Ne Ne Ne Ne Ne Ne Ne Ne Ne Ne Seabee Or e Malm EO OMS Selects bank containing register ANSEL Clears registers ANSEL and ANSELH All pins are digital Selects 2 VILL Eee SIE AOS Selects bank containing register ANSEL resistors enabled resistors enabled IB pino 10 eva 1 bank containing register DRISC A aer O Pins aro Concigured Es Oc OX DLE Selects Dank containing registr TICON TMR1 operates as a timer Prescaler rate is 1 8 Activates cimer
190. ethod should be applied Do you remember the story about the timers About interrupts This example makes links between them in a practical way The schematic is still the same as well as the challenge It is necessary to provide delay long enough to notice changes on a port This time the timer TMRO with the assigned prescaler is used for that purpose Interrupt occurs on every timer register overflow and interrupt routine increments the number in port B by 1 The whole procedure is performed behind the scenes of the whole process which enables the microcontroller to do other things http www mikroe com en books picmcubook appb 24 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples 204 255 0 1 2 3 VCC 5V 10K RESET GND vcc RE2 i Ddd Vss U osc2 RCO ome HI rez RC3 2x20 30pF Y O c TI Co Co gt GND Pay attention to a few details e Even though it is unnecessary in this case the contents of the most important registers W STATUS and PCLATH must be saved at the beginning of the interrupt routine e Interrupt causes the appropriate flag bit to be automatically set and the GIE bit to be automatically cleared At the end of the interrupt routine do not forget to return these bits to the state they had prior to the interrupt occurring and e At the end of the interrupt rutine important re
191. etwork consisting of 16 resistors which form voltage divider The voltage source is selectable through both ends of that divider through the VRSS bit of the VRCON register In addition the voltage fraction provided by resistor ladder network may be selected through the bits VRO VR3 and used as voltage reference See figure below http www mikroe com en books picmcubook ch7 7 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules VREN C1RSEL C2RSEL Vret CVref Vref 0 6V Fig 7 7 VREF The comparator voltage reference has 2 ranges with 16 voltage levels in each range Range selection is controlled by the VRR bit of the VRCON register The selected voltage reference may be output to the RA2 AN2 pin Even though the main idea was to obtain varying voltage reference for the operation of analog modules a simple A D converter is obtained in that way too This converter is very useful in some situations It s operation is under control of the VRCON register Comparators and Interrupt Operation The flag bit CMIF of the register PIR is set on every change of logic state on any comparator s output The same changes also cause an interrupt if the following bits are set CMIE bit of the PIE register PEIE bit of the INTCON register and GIE bit of the INTCON register If interrupt is enabled any change on the comparator s output can wake up the microcontrolle
192. evices the forth line SS may be also used Refer to figure 6 13 below SS Slave Select is additional pin used for specific device selection It is active only in case the microcontroller is in slave mode i e when the external master device requires data exchange When operating in SPI mode MSSP module uses in total of 4 registers e SSPSTAT status register e SSPCON control register e SSPBUF buffer register and e SSPSR shift register not directly available The first three registers are writable readable and can be changed at any moment while the forth register since not available is used for converting data into serial format http www mikroe com en books picmcubook ch6 14 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules Selected peripheral device to accomplish SPI communication with Fig 6 13 SPI Mode As seen in figure 6 14 the central part of the SPI module consists of two registers connected to pins for receive transmit and synchronization Shift register SSPRS is directly connected to the microcontroller pins and used for data transmission in serial format The SSPRS register has its input and output and shifts the data in and out of device In other words each bit appearing on input receive line simultaneously shifts another bit toward output transmit line The SSPBUF register Buffer is a part of memory
193. f Register EXAMPLE 1 label RLF REG w Boeforo nol rU Clon e o E em REG sit ae C 0 AEC ains Tc lon PEs S ORB Wu o 1100 1d 90 C 1 EXAMPLE 2 Label RLF REG Before instruction execution REG 1110 0110 AICC mns TG tons z 1100 LONG RRF Rotate Right f through Carry Syntax label RRF f d Description The content of register f is rotated one bit right through the Carry flag If d w or d 0 the result is stored in register W If d f or d 1 the result is stored in register f http www mikroe com en books picmcubook ch9 27 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set Operation f n gt d n 1 f 0 gt C C gt d 7 Operand 0 x f lt 127 d gt 0 1 Status affected C Number of cycles 1 f Register Fig 9 2 f Register EXAMPLE 1 label RRF REG w Before instruction execution REG 1110 0110 W x C 0 PS ci OUS EEUU shoe IRE III OG Wie UIS G 0 EXAMPLE 2 label RRF REG f Before instruction execution REG 1110 0110 C 0 Atter Instruction REC Oil COll C 0 http www mikroe com en books picmcubook ch9 28 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set SLEEP Enter Sleep mode Syntax label SLEEP Description The processor enters sleep mode The oscillator is stopped PD bit Power Down of the STATU
194. f one byte can be combined in 256 different ways the largest decimal number which can be represented by one byte is 255 one combination represents zero A nibble is referred to as half a byte Depending on which half of the byte we are talking about left or right there are high and low nibbles High nibble Low nibble A Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 MSB Most Significant Bit LSB Least Significant Bit Fig 0 8 High and Low nibbles Logic Circuits Have you ever wondered what electronics within some digital integrated circuits microcontrollers or processors look like What do the circuits performing complicated mathematical operations and making decisions look like Do you know that their seemingly complicated schematics comprise only a few different elements called logic circuits or logic gates The operation of these elements is based on the principles established by British mathematician George Boole in the middle of the 19th century even before the first bulb was invented In brief the main idea was to express logical forms through algebraic functions Such thinking was soon transformed into a practical product which far later evaluated in what today is known as AND OR and NOT logic circuits The principle of their operation is known as Boolean algebra As some program instructions used by the microcontroller perform the same way as logic gates except in the form of commands the princi
195. f the PIE1 register is set an interrupt will be generated Besides the flag is set regardless of whether an interrupt is enabled or not Also it cannot be cleared by software but by writing new data to the TXREG register e Control electronics gushes data toward the TX pin in rhythm with internal clock START bit 0 data STOP bit 1 e When the last bit leaves the TSR register the TRMT bit of the TXSTA regis ter is automatically set and e f the TXREG register has received a new character data in the meantime the whole procedure is repeated immediately after the STOP bit of the previous character has been transmitted Sending 9 bit data is enabled by setting the TX9 bit of the TXSTA register The TX9D bit of the TXSTA register is the ninth and Most Significant data bit When transferring 9 bit data the TX9D data bit must be written before writing the 8 least significant bits into the TXREG register All nine bits of data will be transferred to the TSR shift register immediately after the TXREG write is complete EUSART Asynchronous Receiver FERR CREN OERR X RCIDL RSR Register RETIRA pin ees nm T Control Synchronization TETTE TUI Pin Fosc KITE ECJUMDDEN ESIPODDEN erore lol o Baud Rate Generator Fig 6 4 EUSART Asynchronous Receiver Similar to the activation of EUSART transmitter in order to enable the receiver it is necessary to define the fo
196. f this seemingly bizarre combination ust look how perfectly everything fits the story about binary numbers http www mikroe com en books picmcubook ch0 5 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers P io same number in hexadeci _ mal system 8 digit binary numbe 1010 1111 Fig 0 4 Binary and Hexadecimal number The largest number that can be represented by 4 binary digits is the number 1111 It corresponds to the number 15 in decimal system That number is in hexadecimal system represented by only one digit F It is the largest onedigit number in hexadecimal system Do you see how skillfully it is used The largest number written with eightdigits is at the same time the largest twodigit hexadecimal number Bear in mind that the computer uses 8 digit binary numbers BCD Code BCD code is actually a binary code for decimal numbers only It is used to enable electronic circuits to communicate in a decimal number system with peripherals and in a binary system within their own world It consists of fourdigit binary numbers which represent the first ten digits 0 1 2 3 8 9 Even though four digits can give a total of 16 possible combinations only the first ten are used Number System Conversion The binary numbering system is the most commonly used the decimal system is the most understandable while the hexadecimal system is somewher
197. fected on match Compare mode 1 0 1 1 CCP2IF bit is set Timer 1 registers are cleared A D conversion is started if the A D converter is on on match 1 1 X X PWM mode Table 5 6 CCP2CON Register In short Setup CCP1 module for PWM operation http www mikroe com en books picmcubook ch5 9 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules In order to setup the CCP module for PWM operation the following steps should be taken Disable the CCP1 output pin It should be configured as input Set the PWM period by loading the PR2 register Configure the CCP module for the PWM mode by combining bits of the CCPICON register Set the PWM signal s duty cycle by loading the CCPRIL register and using bits DC1B1 and DC1BO of the CCP1CON register e Configure and start timer TMR2 o Clear the TMR2IF interrupt flag bit of the PIR1 register o Set the timer TMR2 prescale value by loading bits T2CKPS1 and T2CKPSO of the T2CON register o Start the timer TMR2 by setting the TMR2ON bit of the T2CON register e Enable PWM output pins after one PWM cycle has been finished o Wait for the timer TMR2 overflow TMR2IF bit of the PlR1register is set and o Configure the appropriate pin as output by clearing bit of the TRIS register CCP1 in Enhanced Mode The enhanced mode is available on CCP1 only Basically this module does not differ from the one previously described and enhancemen
198. gister bank It is used for indirect addressing o 1 Banks 0 and 1 are active memory location 00h FFh o 0 Banks 2 and 3 are active memory location 100h 1FFh e RP1 RPO Bits select register bank They are used for direct addressing RP1 RPO Active Bank 0 0 Bank0 0 1 Bankl 1 0 Bank2 1 1 Bank3 Table 2 1 e TO Time out bit o 1 After power on or after executing CLRWDT instruction which resets watch dog timer or SLEEP instruction which sets the microcontroller into low consumption mode o 0 After watch dog timer time out has occurred e PD Power down bit o 1 After power on or after executing CLRWDT instruction which resets watch dog timer o 0 After executing SLEEP instruction which sets the microcontroller into low consumption mode e Z Zero bit o 1 The result of an arithmetic or logic operation is zero o 0 The result of an arithmetic or logic operation is different from zero e DC Digit carry borrow bit is changed during addition and subtraction if an overflow or a borrow of the result occurs o l Acarry out from the 4th low order bit of the result has occurred o 0 No carry out from the 4th low order bit of the result has occurred e C Carry Borrow bit is changed during addition and subtraction if an overflow or a borrow of the result occurs i e if the result is greater than 255 or less than O o l Acarry out from the most significant bit of the result has occurred o 0 No carry out from the mo
199. gisters should be given the original content Example 4 a eg c LA Gan S E M RA Header DEA ROBA VAL VAS VS Wal VAL WAL Tal TAN Wah VAS AS TAS A Tah CAS tad VAR Tah A Wall as AC RO ION War UA Wak Val ah Ul Yak VAL TAS wah RAS Ua wav BARCA Way as PS BSNS ce Sl Sa tos a LS os DEFINING VARIABLES AGERE US ToS WSUS Tk oS TAS RAS VO US CoS OE AEGRO TS TS TAS US I WAS VS US VOSS TAS TS US TSU IS TS TS US US OS eS ello els 0x20 w_temp pclath temp SCENE US EGITTO endc e KK KK OK KK OK KK KK KK KK KK 7 START OF MEG 0x0000 goro main BILOCk ene Variable Variable Variable ho Ne Ne Ne variables starts at address 20h at address 20h at address 21h at address 22h PROGRAM DRAK KE RO ROCA US U LAS RC KERN ACRI A Val WAL Gal I Uae AS AS A T TA S Address Or eg i eibi eue TON crion Go to label main A E AS INTERRUPT ROUTINE SAT US GAS AS VAS TS US TAL IS I US US UWS US AS IAS IAS AS US US VAS VAS US OS US TS US VAS DAT TAX YAT TAS US p IENE SE bong NASNONE Ou Saves value in register W Saves value in register STATUS Dig 0x0004 movwf w temp MONE STATUS movwf Status temp movf PCLATH Saves value in register PCLATH http www mikroe com en books picmcubook appb 25 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples movwf pclath_ temp banksel PORTE 2 eB PORTE banksel TENDS CONI Ioue INECON IME Oi MONE pclath temp w movwf PCLATH movf stat
200. gram you will see in both cases that clock signal from the local timer BRG is used for synchronization The same clock source is also used in synchronous mode This timer consists of two 8 bit registers comprising one 16 bit register Baud Rate Generator Registers A SPBRGH Register SPBRG Register MEE i A bit 15 bit8 bit 7 bit Fig 6 10 EUSART Baud Rate Generator BRG A number written to these two registers determines the baud rate Besides both the BRGH bit of the TXSTA register and the BRGH16 bit of the BAUDCTL register affect clock frequency The formula used to determine Baud Rate is given in the table below Bits SYNC BRG1G BRGH BRG EUSART Mode Baud Rate Formula 0 0 0 8 bit asynchronous Fosc 64 n 1 0 0 1 8 bit asynchronous Fosc 16 n 1 0 1 0 16 bit asynchronous Fosc 16 n 1 0 1 16 bit asynchronous Fosc 4 n 1 1 0 X 8 bit asynchronous Fosc 4 n 1 1 1 X 16 bit asynchronous Fosc 4 n 1 Table 6 1 Baud Rate The following tables contain values that should be written to the 16 bit register SPBRG and assigned to the SYNC BRGH http www mikroe com en books picmcubook ch6 8 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules and BRGH16 bits in order to obtain some of the standard baud rates The formulas used to determine the Baud Rate
201. h means that Carry has Not occurred ADDWF Add W and f Syntax label ADDWF f d Description Add the contents of the W and f registers http www mikroe com en books picmcubook ch9 5 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set If d w or d 0 the result is stored in the W register If d f or d 1 the result is stored in register f Operation W f gt d Operand 0 x f lt 127 d 0 1 Status affected C DC Z Number of cycles 1 EXAMPLE 1 label ADD ue on Before instruction execution W 0x1 REG 0xC2 After Instruction Ww xD REG 0xC2 CO N Carry NOCT S ses Tinie resul as Maximum o bit long EXAMPLE 2 label ADDWF INDF Before instruction execution W 0x17 FSR 0xC2 Register at address 0xC2 contains the value 0x20 After instruction W 0x17 FSR 0xC2 Register at address UxC2 contains the value 0x37 ANDLW AND literal with W Syntax label ANDLW k Description The content of the register W is AND ed with the 8 bit literal k It means that the result will contain one 1 only if both corresponding bits of operand are ones 1 The result is stored in the W register http www mikroe com en books picmcubook ch9 6 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set Operation W AND k gt W Operand 0 lt k lt 255 Status affected Z
202. hannel 9 PGM Programming enable pin C121N2 Comparator C1 or C2 Negative Input 37 RB4 General purpose I O port B AN11 A D Channel 11 RB5 General purpose I O port B 38 AN13 A D Channel 13 T1G Timer T1 External Input RB6 General purpose I O port B ICSPCLK Serial programming Clock RA General nurnose VO nort R 39 http www mikroe com en books picmcubook chl 6 of 14 5 3 2009 11 31 25 AM Table 1 1 cont Pin Assignment Central Processor Unit CPU I m not going to bore you with the operation of the CPU at this stage however it is important to state that the CPU is manufactured with in RISC technology an important factor when deciding which microprocessor to use RISC Reduced Instruction Set Computer gives the PIC16F887 two great advantages e he CPU can recognizes only 35 simple instructions In order to program some other microcontrollers it is necessary to know more than 200 instructions by heart e he execution time is the same for all instructions except two and lasts 4 clock cycles oscillator frequency is stabilized by a quartz crystal The Jump and Branch instructions execution time is 2 clock cycles It means that if the microcontroller s operating speed is 20MHz execution time of each instruc tion will be 200nS i e the program will be executed at the speed of 5 million instructions per second Fig 1 4 CPU Memory Memory This microcontroller has three types of memory ROM RAM and EEPROM All of them will b
203. he bit depends on the position it has in the binary number Therefore there is no point talking about units tens etc Instead here it is about the zero bit rightmost bit first bit second from the right etc In addition since the binary system uses two digits only 0 and 1 the value of one bit can be 0 or 1 Don t be confused if you find some bit has value 4 16 or 64 It means that bit s values are represented in decimal system Simply we have got so much accustomed to the usage of decimal numbers that these expressions became common It would be correct to say for example the value of sixth bit in binary number is equivalent to decimal number 64 But we are human and habits die hard Besides how would it sound number one onezero one zero Byte A byte or a program word consists of eight bits grouped together If a bit is a digit it is logical that bytes represent numbers All mathematical operations can be performed upon them like upon common decimal numbers As is the case with digits of any other number byte digits do not have the same significance The largest value has the leftmost bit called the most significant bit MSB The rightmost bit has the least value and http www mikroe com en books picmcubook ch0 8 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers is therefore called the least significant bit LSB Since eight zeros and units o
204. hey offer so many things at low prices and it is only up to you to choose Therefore select the field you are interested in and study only what you need to know Afterwards when you completely understand hardware operation study SFRs which are in control of it there are usually a few of them To reiterate during program writing and prior to changing some bits of these registers do not forget to select the appropriate bank This is why they are listed in the tables above Previous Chapter Table of Contents Next Chapter http www mikroe com en books picmcubook ch1 14 of 14 5 3 2009 11 31 25 AM zh he Boum mikroElektronika Free Online Book PIC Microcontrollers Chapter 2 Core SFRs e TOC e Introduction e Ch 1 e Ch e Ch e Ch e Ch e Ch e Ch e Ch e Ch e App A O O N nD Ui A W N e App B Chapter 2 Core SFRs Features and Function The special function registers can be classified into two categories e Core CPU registers control and monitor operation and processes in the central processor Even though there are only a few of them the operation of the whole microcontroller depends on their contents e Peripheral SFRs control the operation of peripheral units serial communication module A D converter etc Each of these registers is mainly specialized for one circuit and for that reason they will be described along with the circuit they are in control of The core CPU registers of the PI
205. i teme SEE Uomo ende 0x20 Ne Ne Ne Ne Ms ou S N MD D LM EM Us Ox OOQ E main Org goto V AMA QA I D D AA org 0x0004 movwf w temp MOVE STATUS movwt SEE DIS E i MONT PCLATH movwf Pellach Cempe banksel PORTE INGEE PORTE movf Pelath Emp movwf PCLATH http www mikroe com en books picmcubook appb 33 of 54 5 3 2009 11 36 02 AM Bloc OT Variable Variable Variable variables starts at address 20h at address 20h at address 21h at address 22h PROGRAM SIFAR a WS WL TD AT TF TAS WAL VAL VAY TAT a TAS TAC a BAL AD UAT LAT RAS A S VAY Vat address Ch ENG FEES progra net rice Lom Jump to labels mE INTERRUPT ROUTINE CAS YAS Wah A RAE AS CRAB NCC REN ROMA CRAB RABIA SB ak Wal Wal Yar AC AS Mak Yar Val Yak VAL Tah UA IME IOI Se Veco Save register W Save register STATUS Save register PCLATH Sel chs Dank containing PORTE Register PORTB is incremented by 1 PCEATH 1s Qiyo n teo original COoOntent mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples mov f Status temp w AS AS cc mec Qo qe SN CIS Side movwf STATUS swapf w temp f WNW is giv n its original content swapf w temp w banksel BETRI Selects Dank containing PIRI DOCE IE TEIL TMRLIIE C lears Interrupt flag TMRIIFE ous INTCON GIE Global interrupt enabled retfie Return from interrupt routine KK KK KK KK KK KK KK KK KK KKK ok ok KK ck ck KK KK KK KK KK KKK KKK KKK KKK KKK KKK MAIN PROGRAM
206. ice It is commonly about another microcontrollers or specialized cheap integrated circuits belonging to the new generation of so called smart peripheral components memories temperature sensors real time clocks etc Similar to serial communication in SPI mode data transfer in I C mode is synchronous and bidirectional This time only two pins are used for data transfer These are the SDA Serial Data and SCL Serial Clock pins The user must configure these pins as inputs or outputs through the TRISC bits Perhaps it is not directly visible By observing particular rules protocols this mode enables up to 122 different components to be simultaneously connected in a simple way by using only two valuable I O pins Briefly everything works as follows Clock necessary to synchronize the operation of both devices is always generated by the master device microcontroller and its frequency directly affects baud rate There are protocols allowing maximum 3 4 MHz clock http www mikroe com en books picmcubook ch6 16 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules frequency so called high speed I C bus but the clock frequency of the most frequently used protocol is limited to 100 KHz There is no limit in case of minimal frequency When master and slave components are synchronized by the clock every data exchange is always initialized by master Once the MSSP
207. ika Free Online Book PIC Microcontrollers Chapter 4 Timers o TIOSCEN TMRICS A TISYNC p TMR1ON 1 I i i 1 I TDTTTIIITITIDP 1 i i 6 E i E e _ Frescaler IS i ma 1 2 4 8 BL c TMRIH TMRIL i Synchronization LR o L 1 TICKPSO o Lv TICKPS1 Clock E L L ul Tin TMRHIF Fin T1G Fig 4 6 Timer TMR1 Overview Timer TMRI1 Prescaler Timer TMR1 has a completely separate prescaler which allows 1 2 4 or 8 divisions of the clock input The prescaler is not directly readable or writable However the prescaler counter is automatically cleared upon write to the TMR1H or TMRIL register Timer TMR1 Oscillator RCO T10SO and RC1 T10SI pins are used to register pulses coming from peripheral electronics but they also have an additional function As seen in figure 4 7 they are simultaneously configured as both input pin RC1 and output pin RCO of the additional LP quartz oscillator low power This additional circuit is primarily designed for operating at low frequencies up to 200 KHz more precisely for using the 32 768 KHz quartz crystal Such crystals are used in quartz watches because it is easy to obtain one second long pulses by simply dividing this frequency Since this oscillator does not depend on internal clocking it can operate even in sleep mode It is enabled by setting the T1OSCEN control bit of the T1CON register The user must provid
208. ikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller A program written in assembly language consists of several elements being differently interpreted while compiling the program into an executable data file The use of these elements requires strict rules and it is necessary to pay special attention to them during program writing in order to avoid errors ASSEMBLY LANGUAGE SYNTAX As mentioned it is necessary to observe some specific rules in order to enable the process of compiling into executive HEX code to run without errors Compulsory rules explaining how sequences of expressions are put together to form the statements that make up an assembly language program are called syntax There are only several of them e Every program line may consist of a maximum of 255 characters Every program line that is to be compiled must start with a symbol label mnemonics or directive e Text following the mark 5 in a program line represents a comment which is ignored by the assembler not compiled and e All the elements of one program line labels instructions etc must be separated by at least one space character For the sake of better clearness a push button TAB is commonly used instead of it so that it is easy to delimit columns with labels directives etc in a program LABELS A label represents a textual version of some address in ROM or RAM memory Each label has to start in the first column
209. ikroe com en books picmcubook ch3 5 of 10 5 3 2009 11 32 31 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 3 I O Ports Legend RAW Readable Writable bit 0 After reset bit is cleared Fig 3 8 IOCB register Because of these features the port B pins are commonly used for checking push buttons on the keyboard because they unerringly register any button press Therefore there is no need to scan these inputs all the time Fig 3 9 Keyboard Example When the X Y and Z pins are configured as outputs set to logic one 1 it is only necessary to wait for an interrupt request which arrives upon any button press By combining zeros and units on these outputs it is checked which push button is pressed Pin RBO INT The RBO INT pin is a single true external interrupt source It can be configured to react to signal raising edge zero to one transition or signal falling edge one to zero transition The INTEDG bit of the OPTION REG register selects the signal RB6 and RB7 Pins You have probably noticed that the PIC16F887 microcontroller does not have any special pins for programming writing the program to ROM The Ports pins available as general purpose I O pins during normal operation are used for this purpose Port B pins clock RB6 and data transfer RB7 during program loading In addition it is necessary to apply a power supply voltage Vdd 5V and Vss 0V as well as voltage f
210. ill be able to easily ride any other bicycle And of course you will never forget the skill in programming just as you will never forget riding bicycles PIC microcontrollers PIC microcontrollers designed by Microchip Technology are likely the right choice for you if you are the beginner Here is why The real name of this microcontroller is PlCmicro Peripheral Interface Controller but it is better known as PIC Its first ancestor was designed in 1975 by General Instruments This chip called PIC1650 was meant for totally different purposes About ten years later by adding EEPROM memory this circuit was transformed into a real PIC microcontroller Nowadays Microchip Technology announces a manufacturing of the 5 billionth sample In order that you can better understand the reasons for its popularity we will briefly describe several important things Clock i ROM RAM Resolution of Compar 8 16 bit Serial PWM Family Kbytes bytes Pins is A D Inputs A D Converter ators Timers Comm Outputs Others Base Line 8 bit architecture 12 bit Instruction Word Length NENE ASES EA ARTO 4 8 pos 8 an 1x8 PIC12FXXX VIALE GEA 8 4 8 0 3 8 o 1x8 EEPROM PIC16FXXX E AA A NAAA 20 a 8 VA 1x8 EEPROM PICLGHVXXX 1 5 25 18 20 20 1x8 Vdd 15V Mid Range 8 bit architecture 14 bit Instruction World Length PIC12FXXX NATA PS HI A 8 20 0 4 10 1 1 ee 1 171 EEPROM PIC12HVXXX 1 75 64 8 20 0 4 10 1 de en PICLOFXXX IS RNA SNTE 20
211. increment the TMR2 register starting from 00h The values of TMR2 and PR2 are constantly compared and the TMR2 register keeps on being incremented until it matches the value in PR2 When a match occurs the TMR2 register is automatically cleared to 00h The timer TMR2 Postscaler is incremented and its output is used to generate an interrupt if it is enabled The TMR2 and PR2 registers are both fully readable and writable Counting may be stopped by clearing the TMR2ON bit which contributes to power saving As a special option the moment of TMR2 reset may be also used to determine synchronous serial communication baud rate The timer TMR2 is controlled by several bits of the T2CON register T2CON Register L7 TOUTPS3 TOUTPS2 TOUTPS1 TOUTPSO TMR2ON T2CKPS1 T2CKPSO Legend Bit is unimplemented RAW Readable Writable bit 0 After reset bit is cleared Fig 4 14 T2CON Register TOUTPS3 TOUTPSO Timer2 Output Postcaler Select bits are used to determine the postscaler rate according to the following table http www mikroe com en books picmcubook ch4 11 of 12 5 3 2009 11 32 57 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 4 Timers TOUTPS3 TOUTPS2 TOUTPS1 TOUTPSO Postscaler Rate 0 0 0 0 iat 0 0 0 1 2 0 0 1 0 Le 0 0 ir 1 1 4 0 1 0 0 5 0 if 0 1 1 6 0 1 1 0 T 0 1 1 1 1 8 fe 0 0 0 P9 1 0 0 1 1 10 1 0 if 0 AY 1 0 1 1 iz 1 1 0 0 A 1 de 0 1 1 14 1 1 1 0 MS 1 ik de 1 1 16 Table
212. ing STATUS register STATUS register ERPNER Y RPLRPO 6 Instruction 0 IRP A Bank Address A Indirect addressing 7 FSR register M M Bank Address 00 01 80h FFh Bank 0 Bank 1 Bank 2 Bank 3 Fig 2 18 Direct and Indirect addressing Previous Chapter Table of Contents Next Chapter http www mikroe com en books picmcubook ch2 12 of 12 5 3 2009 11 32 08 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 3 1 O Ports e TOC e Introduction e Ch 1 e Ch e Ch e Ch e Ch e Ch e Ch e Ch e Ch e App A O O N O wn A W N e App B e App C Chapter 3 1 O Ports Features and Functions One of the most important feature of the microcontroller is a number of input output pins used for connection with peripherals In this case there are in total of thirty five general purpose I O pins available which is quite enough for the most applications In order pins operation can match internal 8 bit organization all of them are similar to registers grouped into five so called ports denoted by A B C D and E They all have several features in common e For practical reasons many I O pins have two or three functions If a pin is used as any other function it may not be used as a general purpose input output pin and e Every port has its satellite i e the corresponding TRIS register TRISA TRISB TRISC etc which determines performanc
213. ins can be connected to pull up resistors e INTEDG Interrupt Edge Select bit o Q Interrupt on rising edge of INT pin 0 1 and o l Interrupt on falling edge of INT pin 1 0 e TOCS TMRO Clock Select bit o Q Pulses are brought to TMRO timer counter input through the RA4 pin and http www mikroe com en books picmcubook ch4 2 of 12 5 3 2009 11 32 57 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 4 Timers o l Internal cycle clock Fosc 4 e TOSE TMRO Source Edge Select bit o 0 Increment on high to low transition on TMRO pin and o 1 Increment on low to high transition on TMRO pin e PSA Prescaler Assignment bit o Q Prescaler is assigned to the WDT and o l Prescaler is assigned to the TMRO timer counter e PS2 PS1 PSO Prescaler Rate Select bit o Prescaler rate is adjusted by combining these bits As seen in the table 4 1 the same combination of bits gives different prescaler rate for the timer counter and watch dog timer respectively PS2 PS1 PSO TMRO WDT 0 0 0 1 2 t 0 0 1 1 4 12 0 1 0 1 8 1 4 0 1 1 1 16 1 8 1 0 0 1 32 1 16 1 0 1 1 64 es to 1 1 0 1 128 1 64 1 1 1 1 256 1 128 Table 4 1 Prescaler Rate The function of the PSA bit is shown in the two figures below z T D E OL Fig 4 3 The function of the PSA bit 0 http www mikroe com en books piemcubook ch4 3 of 12 5 3 2009 11 32 57 AM mikroElektronika Free Online Book PIC Microcont
214. iods of time In other words counting will be carried out faster A new cycle of accelerated counting starts after every register PR overflow Example 9 OkOk ck ck ckck ck ck kk ck ke ARA Header kk ok RK k kk kk kk kk Ck kk kk kk kk Ck kk k ck kk ck k ck kk ck ck ck kkk k k ok KKK KK KK KK ck ck ck KK IK KK KK KK KK KK KR KR KK OK OK KR KKK OK KK KK KK KK KK DEFINING VARIABLES led oes 0x20 w temp pclath temp Gub BIS T EC endc Block of variables starts at address 20h Variable at address 20h Variable at address 21h Variable at address 22h Ne Ne o Ne KK KK KK KK KK KK KK KK KK KK KKK KK KKK KK KKK KK KKK KK KKK KKK KKK KKK KK KKK KKK KK PROGRAM START ES 0x0000 Address Of ENS filter Progra TASErUCETOT GOTO main Sume v labe ke nian e KK KK KK KK KK KK KK KK KK KK KKK KK KKK KK KK KK KK KK KKK KKK KKK KKK KKK KKK TNTERRUPRTEROUTINE OTG 0x0004 7 Interrupt vector http www mikroe com en books picmcubook appb 34 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples movwt MOME movw f MOMIE movw ft banksel TAE E banksel decf MONE movwt MON IE movwt Swapft swapf banksel Deir lu ier Le w_temp STATUS Starts EENS PCLATH Perah Eomp PORTE PORTE BE PRZ pclath_temp w PCLATH SEGUE DIS E eo wi STATUS w_temp f WS eT PW IE ESTE PIRI TMR IE TEINS ON CIE me Ne Ne Ne xo Save register W Save register
215. ironment appears Save the document in the folder D PIC projects by using the File gt Save As command and name it Blink asm indicating that this program is to be an example of port diode blinking Obviously you can locate you files wherever you wish in whichever hard drive you wish Using a common directory to store all your different projects and subdirectories in makes good sense Example D Pic Projects LED EP Vash Pro Jece All associated files Event Count Project All associated files LEDS canino eo ec All associated files After the Blink asm is created and saved it should be included in the project by right MProbamew fo Sle click on the Source Files option in the Proba mcw window After that a small window with two options appears Select the first one Add Files Ld Proba mcp Zi Source Piles L Header Files D Object Files Library Files _ Linker Scripts Y cher Files Click on that option opens another window containing the folder PIC along with the document Blink asm See figure below Add Files to Project Look in E PIC projekti Blink asm MM Proba mcw Si C DAMAS File name L Header Files Files of hype Assembly Source Files asm CI Object Files n AA EI Library Fies Jump ta Project Directory C Linker Scripts E Other Files _ Remember this setting 9 Auto Let MPLAB IDE guess CO User File s were created especially
216. ister should be read in order to get information on possible errors which have occurred during transmission The ninth bit RX9D is always set and Received 8 bits stored in the RCREG register should be read It should be checked whether the combination of these bits matches the predefined address If the match occurs it is necessary to clear the ADDEN bit of the RCSTA register which enables further 8 bit data receive CNN IND Master Synchronous Serial Port Module MSSP module Master Synchronous Serial Port is a very useful but at the same time one of the most complex circuit within the microcontroller It enables high speed communication between a microcontroller and other peripherals or microcontroller devices by using few input output lines maximum two or three Therefore it is commonly used to connect the microcontroller to LCD displays A D converters serial EEPROMs shift registers etc The main feature of this type of communication is that it is synchronous and suitable for use in systems with a single master and one or more slaves A master device contains the necessary circuitry for baud rate generation and supplies the clock for all devices in the O SAD may in that way eliminate the internal clock generation circuitry The MSSP module can operate in one of two modes e SPI mode Serial Peripheral Interface e C mode Inter Integrated Circuit As seen in figure 6 12 below one MSSP module represents only a half of the hardware n
217. it A determines the P1A pin function e 1 PID pin has the PWM waveform with polarity controlled by the CCP1MO and CCP1MI bits and e 0 Pin is configured as general port Ainput output ECCPAS Register PSSBD1 PSSBDO Legend RAN Readable Writable bit 0 After reset bit is cleared Fig 5 19 ECCPAS Register http www mikroe com en books picmcubook ch5 14 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules ECCPASE ECCP Auto Shutdown Event Status bit indicates whether shut down of CCP module has occurred Shutdown state e 1 CCP module is in Shutdown state and e 0 CCP module operates normally ECCPAS2 ECCPASO ECCP Auto Shutdown Source Select bits select auto shutdown source ECCPAS2 ECCPAS1 ECCPASO Shutdown state source 0 0 0 Shutdown state disabled 0 0 1 Comparator C1 output change 0 1 0 Comparator C2 output change 0 1 1 Comparator C1 or C2 output change 1 0 0 Logic zero 0 on INT pin 1 0 1 Logic zero 0 on INT pin or comparator C1 output change 1 1 0 Logic zero 0 on INT pin or comparator C2 output change 1 tr 1 Logic zero 0 on INT pin or comparator C1 or C2 output change Table 5 7 ECCPAS Register PSSAC1 PSSACO Pins P1A P1C Shutdown State Control bits define logic state on output pins PLA and P1C when CCP module is in shutdown state PSSAC1 PSSACO Pins logic state 0 0 0 0 1 tr 1 X High impedance Tri state Table 5 8 A
218. it ANSI of the ANSEL register e RA2 AN2 determined by bit ANS2 of the ANSEL register e RA3 AN3 determined by bit ANS3 of the ANSEL register and e RA5 ANA determined by bit ANSA of the ANSEL register Each bit of this port has an additional function related to some of built in peripheral units These additional functions will be described in later chapters This chapter covers only the RAO pin s additional function since it is related to Port A only ULPWU Unit The microcontroller is commonly used in devices which have to operate periodically and completely independently using a battery power supply In such cases minimal power consumption is one of the priorities Typical examples of such applications are thermometers sensors for fire detection and similar It is known that a reduction in clock frequency reduces the power consumption so one of the most convenient solutions to this problem is to slow the clock down use 32KHz quartz crystal instead of 20MHz Setting the microcontroller to sleep mode is another step in the same direction However even when both measures are applied another problem arises How to wake the microcontroller and set it to normal mode It is obviously necessary to have an external signal to change logic state on some of the pins Thus the problem still exists This signal must be generated by additional electronics which causes higher power consumption of the entire device Microcontroller The id
219. it of the RCSTA register is set The consequences are the following Data already stored in the FIFO registers two bytes can be normally read No additional data will be received until the OERR bit is cleared and This bit is not directly accessed To clear it it is necessary to clear the CREN bit of the RCSTA register or to reset the whole EUSART system by clearing the SPEN bit of the RCSTA register Receiving 9 bit Data In addition to receiving standard 8 bit data the EUSART system supports 9 bit data reception On the transmit side the ninth bit is attached to the original byte just before the STOP bit On the receive side when the RX9 bit of the RESTA register is set the ninth data bit will be automatically written to the RX9D bit of the same register When this byte is received one should take care of how to read its bits the RX9D data bit must be read before reading the 8 least significant bits of the RCREG register Otherwise the ninth data bit will be automatically cleared http www mikroe com en books picmcubook ch6 4 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules RSR Register Fig 6 5 Receiving 9 bit Data Address Detection When the ADDEN bit of the RCSTAregister is set the EUSART module is able to receive only 9 bit data whereas all 8 bit data will be ignored Although it seems like a restriction such modes enable serial commu
220. ite Isn t Lestedl Documents contained in the project do not always need to be written in MPLAB Documents written by some other program may also be included in the project In this example there are no such documents J ust click Next http www mikroe com en books picmcubook appa 15 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller P Project Wizard Shep Four Add existing les bo pour project HC Hc D He E em F e G E eH 13 E z eg A Project Wizard El j Chek Finish lo create conliquee the project with these parameters Device PICTEFEST Toolsute Microchip MPASM Toolsube File DAPIC projekb Proba mcm Anew workspace vell be ciested and the new peojec added l hal workspace cem Hp Click FINISH to complete the project The window itself contains project parameters WRITING A NEW PROGRAM When the project is created a window shown in figure below appears Proba MPLAB IDE v7 60 il Dub LU sf m Shwe Release vici ak ll Kh 49 BE Checksum 0x26 a Se WD dc bark i http www mikroe com en books picmcubook appa 16 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller CREA Wo idc EXA The next step is to write a program Open a new document by clicking File gt New Text Editor in MPLAB env
221. ith binary and decimal number systems considered to be 4 0 0 0 0 0 1 0 0 4 the most important for us It is easy to make conversion of any hexadecimal number to binary and it is 510 0 0 0 0 1 0 1 5 alsoeasyto remember it However these conversions may cause confusion For example what does 60 0 00 6 the statement It is necessary to count up 110 products on assembly line actually mean Depending EOS on whether it is about binary decimal or hexadecimal the result could be 6 110 or 272 products 7 0 00 0 T respectively Accordingly in order to avoid misunderstanding different prefixes and suffixes are 8 0 0 0 8 directly added to the numbers The prefix or 0x as well as the suffix h marks the numbers in 9 0 0 0 0 g hexadecimal system For example hexadecimal number LOAF may look as follows 10AF Ox10AF or 10010 0 0 1 0 1 0 A ES binary numbers usually get the suffix or Ob whereas decimal numbers get the 11j0 ojo 01110 1 1 B 12 0 0 0 0 1 1 0 0 C 13 0 0 0 0 1 1 0 1 D 14 0 0 0 0 1 1 1 0 E 15 0 F 16 0 10 17 0 0 0 1 0 0 0 1 11 253 FD 254 FE 255 FF Bit Theory says a bit is the basic unit of information Let s forget this dry explanation for a moment and take a look at what it is in practice The answer is nothing special a bit is a binary digit Similar to decimal number system in which digits in a number do not have the same value for example digits in the number 444 are the same but have different values the significance of t
222. its of the ANSEL and ANSELH registers at the beginning of the program e f you use switches and push buttons as input signal source connect them to Port B pins because they have pull up resistors The use of these resistors is enabled by the RBPU bit of the OPTION REG register whereas the installation of individual resistors is enabled by bits of the WPUB register and e It is usually necessary to react as soon as input pins change their logic state How ever it is not necessary to write a program for changing pins logic state It is far simpler to connect such inputs to the PORTB pins and enable the interrupt on every voltage change Bits of the registers IOCOB and INTCON are in charge of that Previous Chapter Table of Contents Next Chapter http www mikroe com en books picmcubook ch3 10 of 10 5 3 2009 11 32 31 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 4 Timers e TOC e Introduction e Ch 1 e Ch e Ch e Ch e Ch e Ch e Ch e Ch e Ch e App A OU O N oO Ui A W N e App B e App C Chapter 4 Timers The timers of the PIC16F887 microcontroller can be briefly described in only one sentence There are three completely independent timers counters marked as TMRO TMR1 and TMR2 But it s not as simple as that Timer TMRO The timer TMRO has a wide range of applications in practice Very few programs dont use it in some way It is very convenient and easy to use for writing program
223. jump to specified address Ip M M QI A IE xU M uU AC EA A M UD EU aS CAT ad EXAMPLE 8 Using timer TMR1 and using interrupt http www mikroe com en books picmcubook appb 32 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples 16 bit timer TMRI is used in this example By occupying its registers TMR1L and TMR1H an interrupt occurs and the number on port B is incremented This has already been seen in the previous examples The difference is in the program delay which is a bit longer this time because the prescaler rate is 1 8 VCC 5V B 10K Fr a MCLR RAO RA1 RA RA3 RAS REO REA RE Ddd Vss OSC1 OSC2 J RCO RC1 RC RC3 RDO RD1 GND VEC V48839L Old 8MHz th 2x20 30pF GND Example 8 dot 255 0 1 2 3 RB7 RB6 RB5 RB4 RB3 RB2 RB1 RBO vdd BO Vss aa RD LED 330R RDG MA a i LED AA 330R RCT RCE LED AA 330R ROS BEEN RCA RD3 LED 330R i RDZ GND PIS px CR EE E d Header Cal WS Val TAL Al WAS Ts RARO ACA ROB BO Val TAR Val Wake VAL RO ACA TAP VAS RAS BO RA US US Wal Wal Wak ak eal Val AS TAS Wak BON RA aS IR D SM VSB a DEFINING VAR TABLES CR RR US US AS OS TAL US TS TOS TAS WS TOS US US HS TS US US ISDS TAL US TS AS US HS LAS US TS US US TALUS US OOS TAL OS AR OS US ello els w_temp pelat
224. k appa 12 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller E MPLAB lool v 60 Finally This is what you have been waiting for Click Finish The computer will be restarted along with the InstallShield Wizard Complete program saved on hard disc Everything is OK The Install Field Wizard has successtullg installed MPLAB Tools v7 60 Before you can use the program you must restart C Ma wil restait mp computer later Remove any daks from ther dies and then click Finish bo complete setup Da i ma Show FT tf ak O Checksum x 2dB qe EN utput FICLBF452 wn novzd c bank 0 As seen MPLAB is similar to most Windows programs Apart from the working area there are menus contains options File Edit etc toolbars contains different icons and a status bar at the bottom of the window Similar to Windows http www mikroe com en books picmcubook appa 13 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller there is a rule to have shortcuts for the most commonly used program options created in order to easily access them and speed up operation therefore These shortcuts are actually icons below the menu bar In other words all options contained in the toolbar are contained in the menu too PROJ ECT MAKING Follow these steps to prepare program f
225. k to external operation Similarly to the previous cases this module is enabled by changing configuration word just before the programming of chip starts This time it is done by selecting the Fail Safe Clk Monitor option Disabled Enabled d ix mikroElektromka PicFLASH v7 09 with mikrolCD se i File Device Buffer Windows USB About History Configuration Bits PICI6FAB7 Code Protect Oscillator HS Ay f None Read write Watchdog Timer Enabled F C ODOUh TFFFh All soo o mmm FLASH Program Memory etre ie o Man Data EE Protect Disabled Ka Wie protection Off mg f epo 0000h OOFFh Protected C O000h O7FFh Protected 0000h DFFFh Protected Low Voltage Program Enabled l w La Ion V Protect In Circuit Debugger CD Disabled m A EUN Cal Word E Brown out Reset Sel set to 4 v hd ID Locations 3FFF 3FFF 3FFF 3FFF Clear amr amr amp om Program Mery Size 8K DeviceStatus Idie ps progress http www mikroe com en books picmcubook ch8 10 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits Program Memory Size 8 K Dence Status Idle Type EEPROM Size 256 Bytes Address Dh Revision ithe tt File CADOCUME
226. ks picmcubook appb 30 of 54 5 3 2009 11 36 02 AM BLEME COCHE FOORE SE ende mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples mnel OE lolo ls of variables d D A E M E I E AU MEUM E ORG MO GOLO 0x000 mala Heset vector Sos juas e seems o Label met p I A uM A Uu E x Mu aM E E uM E E ES E Line ele Lnelucde oor su WJONDNE TE pls INC an A D M IM AA au I x mu I D als CoE AS ad main Eo banksel ele ce banksel psf bsf OPE TEE banksel ele Dill de BUE TOn goro Increment TTE CE MON E movwt Goro Decrement decf MON SE movwt eo e end Macro pausems ANSEL ANSEL ANSELH TRISB EES 0 TRS l TRISB PORTB emir Selects bank containing ANSEL All pins are digital PORT 0 0 Increment PORT 1 0 Decrement Loop cne NIE EAE W PORTE Loop Chir E eine W PORTS Loop Qe XE TOW O Opa call Hist ui ns pests n us ES os usus E E c rus Casus not cs ur LS usu Lg rS us USS RAS ts oe Sd os p ug ugs us strud tatus ts ra oss pausems MACRO argl 9551 dechi local local WOC b Tocal local movlw movwt mov Lw movwt mover Dit Sic goto Ctd decf GOEG MONE LOOP I dechi Delaylms Loop End Hagan etre rer Eten Low argl FOCHE LOCA E STATUS Z dechi Delaylms POCNE E KOOP Hieni E http www mikroe com en books picmcubook appb 31 of 54 5 3 2009 11 36 02 AM
227. ktronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Timer register 4MHz 1MHz Start ys ATEO gt Nm 0 255 Additional register atl 1 1 lapsed time N x 256C B A uS Fig 0 30 Using the interrupt in timer operation This figure illustrates the use of the interrupt in timer operation Delays of arbitrary duration with minimal interference by the main program execution can be easily obtained by assigning a prescaler to the timer Counters If a timer is supplying pulses into the microcontroller input pin then it turns into a counter Clearly It is the same electronic circuit The only difference is that in this case pulses to be counted come through the ports and their duration width is mostly not defined This is why they cannot be used for time measurement but can be used to measure anything else products on an assembly line number of axis rotation passengers etc depending on sensor in use Watchdog Timer The Watchdog Timer is a timer connected to a completely separate RC oscillator within the microcontroller If the watchdog timer is enabled every time it counts up to the program end the microcontroller reset occurs and program execution starts from the first instruction The point is to prevent this from happening by using a specific command The whole idea is based on the fact that every program is executed in several longer or shorter loops
228. lated using the formula CVref Vdd 4 VR3 VRO 32 Vdd In Short In order to properly use built in Comparators it is necessary to do the following Step 1 Configuring module e In order to select the appropriate mode bits of the registers CMICONO and CM2CONO should be configured Interrupt should be disabled on any change of mode Step 2 Configuring internal voltage reference Vref source only when used In the VRCON register it is necessary to Select one of two voltage ranges using the VRR bit Configure necessary Vref using bits VR3 VRO Set the VROE bit if needed and Enable voltage Vref source by setting the VREN bit http www mikroe com en books picmcubook ch7 13 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules Formula used to calculate voltage reference VRR 1 low range CVref VR3 VROI 24 VLADDER VRR 0 high range CVref VLADDER 4 VR3 VRO VLADDER 32 Vladder Vdd or Vref Vref or Vref Step 3 Starting operation e Enable interrupt by setting bits CMIE PIE register PEIE and GIE both in the INTCON register e Read bits CIOUT and C20UT of the CMCON register and e Read flag bit CMIF of the PIR register After being set this bit must be cleared in software Previous Chapter Table of Contents Next Chapter http www mikroe com en books picmcubook ch7 14 of 14 5 3 2009 11 34 24 AM mikroElektronik
229. le Device PICI6FBB Operation None Fig 8 3 PlCflash Program External oscillator in EC mode The external clock EC mode uses the system clock source configured from external oscillator The frequency of this clock source is unlimited 0 20MHz Fig 8 4 External Oscillator This mode has the following advantages e he external clock source is connected to the OSC1 input and the OSC2 is available for general purpose O It is possible to synchronize the operation of the microcontroller with the rest of on board electronics e In this mode the microcontroller starts operating immediately after the power is on There is no delay required for frequency stabilization and e Temporary stopping the external clock input has the effect of halting the device while leaving all data intact Upon restarting the external clock the device resumes operation as if nothing has happened External Oscillator EC mode Pin 05C1 DC 20MHz Pin OSC2 I O Fig 8 5 External Oscillator in EC Mode External oscillator in LP XT or HS mode http www mikroe com en books picmcubook ch8 4 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits Fig 8 6 Two Types of External Oscillators The LP XT and HS modes support the usage of internal oscillator for configuring clock source The frequency of this source is determined by quartz crystal or ceramic resonators co
230. le to operate in sleep mode is built into the PIC16F887 microcontroller Simply what previously has been a separate circuit it is now built into the microcontroller and assigned to the timer TMR1 The oscillator is enabled by setting the T1OSCEN bit of the TICON register After that the TMRICS bit of the same register then is used to determine that the timer TMR1 uses pulse sequences from that oscillator e The signal from this quartz oscillator is synchronized with the microcontroller clock by clearing the T1SYNC bit In that case the timer cannot operate in sleep mode You wonder why Because the circuit for synchronization uses the clock of microcontroller and e The TMRI register overflow interrupt may be enabled Such interrupts will occur in sleep mode as well TMR1 in counter mode Timer TMRI starts to operate as a counter by setting the TMRICS bit It means that the timer TMR1 is incremented on the rising edge of the external clock input T1CKI If control bit T1SYNC of the T1CON register is cleared the external clock inputs will be synchronized on their way to the TMR1 register In other words the timer TMRI is synchronized to the microcontroller system clock and called a synchronous counter When the microcontroller operating in this way is set in sleep mode the TMR1H and TMRIL timer registers are not incremented even though clock pulses appear on the input pins Simply since the microcontroller system clock does not run in this mo
231. llowing bits CREN 1 EUSART receiver is enabled by setting this bit of the RCSTA register SYNC 0 EUSART is configured to operate in asynchronous mode by clearing this bit stored in the TXSTA register and SPEN 1 By setting this bit of the RCSTA register EUSART is enabled and the RX DT pin is automatically configured as input If this bit is simultaneously used for some analog function it must be disabled by clearing the corresponding bit of the ANSEL register http www mikroe com en books picmcubook ch6 3 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules When this first and necessary step is accomplished and START bit is detected data is transferred to the shift register RSR through the RX pin When the STOP bit has been received the following occurs Data is automatically transferred to the RCREG register if empty The flag bit RCIF is set and an interrupt if enabled by the RCIE bit of the PIE1 register occurs Similar to transmitter the flag bit is cleared by software only i e by reading the RCREG register Bear in mind that this is a two character FIFO memory first in first out which allows reception of two characters simultaneously If the RCREG register is occupied contains two bytes and the shift register detects new STOP bit the overflow bit OERR will be set In this case a new coming data is lost and the OEER bit must be cleared
232. lus and ICD In Circuit Debugger that can be used to program software into PIC microcontroller device Since not being the subject of this book they are mentioned as options only In order to start MPLAB your PC should contain PC compatible computer belonging to class 486 or better Any Windows operating system VGA graphic card 8MB memory 32MB recommended 200MB available hard disc and A mouse MPLAB installation comes first Data files from MPLAB CD should be copied to a hard disc The process of installation is similar to almost all other Windows program installations First of all a welcome window appears then options to select and at last installation itself A message notifying that the program is successfully installed and ready for use appears Are you ready Steps to follow prior the installation Start Microsoft Windows Insert the CD into CD ROM Click START and select option RUN Click BROWSE and select CD ROM drive and Find folder MPLAB on CD ROM CNN AN AC Everything is ready now to start installation The following pictures describe the installation steps http www mikroe com en books picmcubook appa 10 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller Install MP760a exe BN Setup Launcher l Microc nip Technology Inc Click on this icon to start up the process InstallShield Wizard MPLAB Tools v7 60 Se
233. ly perform the following steps 2 3 and 4 If the SPI module operates as Slave the microcontroller will not perform these steps until the SCK pin detects clock signal PU Fig 6 15 Step 1 Step 2 This data is now moved to the SSPSR register and the SSPBUF register is not cleared Fig 6 16 Step 2 Step 3 Synchronized with clock signal this data is shifted to the output pin MSB bit first while the register is simultaneously being filled with bits through input pin In Master mode the microcontroller itself generates clock while the Slave mode uses external clock pin SCK Fig 6 17 Step 3 Step 4 The SSPSR register is full once the 8 bits of data have been received It is indicated by setting the BF and SSPIF bits The received data that byte is automatically moved from the SSPSR register to the SSPBUF register Since data transfer via serial communication is performed automatically the rest of the program is normally executed while data transfer is in progress In that case the function of the SSPIF bit is to generate interrupt when one byte transmission is completed Fig 6 18 Step 4 Step 5 CPU At 2 s data stored in the SSPBUF register is ready for use and moved to any register Cr available Fig 6 19 Step 5 Il2C mode I C mode Inter IC Bus is especially suitable when the microcontroller and integrated circuit which the microcontroller should exchange data with are within the same dev
234. m compiles all instructions written before directive ELSE or ENDIF and e If the statement is not correct or the value of a symbol is equal to zero only instructions written after directives ELSE or ENDIF are to be compiled Example 1 IF VERSION gt 3 CALL Table_2 CAE ENDIF If the program is released after the version 3 statement is right then subroutines Table 2 and Extension are executed If the statement in parentheses is wrong VERSION 3 two instructions calling subroutines are ignored and will not be compiled therefore Example 2 If the value of symbol Model is equal to one then first two instructions after directive IF are compiled as well as instructions after directive ENDIF all instructions between ELSE and ENDIF are ignored Otherwise if Model 0 then instructions between IF and ELSE are ignored whereas instructions after directive ELSE are compiled JUE Model MOVEW EUIEBER MOVWE MAXIMUM ELSE MOVEW BUERERI MOVWE MAXIMUM ENDIF BANKSEL directive In order to access an SFR register it is necessary to select the appropriate bank in RAM memory by using bits RPO and RP1 of the STATUS register This directive is used in this case Simply since Inc data file contains the list of all registers along with their addresses the assembler knows which bank corresponds to which register After encountering this directive assembler selects the bits RPO and RP1 for the specified register on its own For example BANK
235. mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers TOC Introduction Ch 1 CE Ch 3 Ch 4 is Ch 6 Ch 7 Ch 8 Ch 9 App A App B App C Introduction World of microcontrollers The situation we find ourselves today in the field of microcontrollers had its beginnings in the development of technology of integrated circuits This development has enabled us to store hundreds of thousands of transistors into one chip That was a precondition for the manufacture of microprocessors The first computers were made by adding external peripherals such as memory input output lines timers and others to it Further increasing of package density resulted in creating an integrated circuit which contained both processor and peripherals That is how the first chip containing a microcomputer later known as a microcontroller has developed This is how it all got started In the year 1969 a team of J apanese engineers from BUSICOM came to the USA with a request that a few integrated circuits for calculators were to be designed according to their projects The request was sent to INTEL and Marcian Hoff was in charge of the project there Having experience working with a computer the PDP8 he came up with an idea to suggest fundamentally different solutions instead of the suggested design This solution presumed that the operation of integrated circuit was to be determined by the program stored in the ci
236. mode In order to generate a pulse of arbitrary form on its output pin it is necessary to determine only two values pulse frequency and duration Period Pulse Fig 5 7 PWM Mode PWM Period The output pulse period T is specified by the PR2 register of the timer TMR2 The PWM period can be calculated using the following equation PWM Period T PR2 1 ATosc TMR2 Prescale Value If the PWM Period T is known then it is easy to determine the signal frequency F because these two values are related http www mikroe com en books picmcubook ch5 5 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules by equation F 1 T PWM Duty Cycle The PWM duty cycle is specified by using in total of 10 bits eight MSbs found in the CCPRIL register and two additional LSbs found in the CCP1CON register DC1B1 and DC1BO The result is 10 bit number contained in the formula Pulse Width CCPR1L DC1B1 DC1B0 Tosc TMR2 Prescale Value The following table shows how to generate PWM signals of varying frequency if the microcontroller uses 20 MHz quartz crystal Tosc 50nS Frequency KHz 1 22 4 88 19 53 78 12 156 3 208 3 TMR2 Prescaler 16 4 1 1 1 AL PR2 Register FFh FFh FFh 3Fh 1Fh 17h Table 5 1 PWM Duty Cycle At last two notes e Output pin will be constantly set in case the pulse width is by negligence determined to be larger than PWM period and e In this applic
237. module has been enabled it waits for a Start condition to occur First the master device sends the START bit logic zero through the SDA pin then the 7 bit address of the selected slave device and finally the bit which requires data write 0 or read 1 to that device Accordingly following the start condition the eight bits are shifted into the SSPSR register All slave devices share the same transmission line and all will simultaneously receive the first byte but only one of them has the address to match TE ILI UUL Address 2 Master 7 SDA SCL Address 1 Address 2 Address 3 MCU Y Fig 6 20 Master and Slave Configuration Once the first byte has been sent only 8 bit data are transmitted master goes into receive mode and waits for acknowledgment from the receive device that address match has occurred If the slave device sends acknowledge data bit 1 data transfer will be continued until the master device microcontroller sends the Stop bit This is the simplest explanation of how two components communicate If needed this microcontroller is able to control more complicated situations when 1024 different components shared by several different master devices are connected Such devices are rarely used in practice and there is no need to discuss them at greater length http www mikroe com en books picmcubook ch6 17 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcont
238. mperature changes tolerance to values of built in components etc Imagine a computer which would operate upon decimal numbers by recognizing 10 digits in the following way 020V 15V 2 10V 3 15V 4 20V 9245V Did anybody say batteries A far simpler solution is the use of binary logic where 0 indicates that there is no voltage and 1 indicates that there is voltage It is easier to write 0 or 1 instead of there is no voltage or there is voltage It is called logic zero 0 and logic one 1 which electronics perfectly conforms with and easily performs all those endlessly complex mathematical operations It is electronics which in reality applies mathematics in which all numbers are represented by two digits only and in which it is only important to know whether there is voltage or not Of course we are talking about digital electronics Hexadecimal Number System At the very beginning of computer development it was realized that people had many difficulties in handling binary numbers Because of this a new numbering system had to be established This time a number system using 16 different digits The first ten digits are the same as digits we are used to 0 1 2 3 9 but there are six digits more In order to keep from making up new symbols the six letters of alphabet A B C D E and F are used A hexadecimal number system consisting of digits 0 1 2 3 4 5 6 7 8 9 A B C D E F has been established What is the purpose o
239. n IC mode e 1 Enables MSSP module and configures pins SDA and SCL as the source of the serial port pins and e 0 Disables MSSP module and configures these pins as I O port pins CKP Clock Polarity Select bit is not used in 1 C master mode In SPI mode e l Idle state for clock is a high level and e 0 Idle state for clock is a low level In 12C slave mode e 1 Enables clock and e 0 Holds clock low Used to provide more time for data stabilization SSPM3 SSPMO Synchronous Serial Port Mode Select bits SSP mode is determined by combining these bits SSPM3 SSPM2 SSPMI SSPMO Mode 0 SP master mode clock Fosc 4 1 SP master mode clock Fosc 16 0 SPI master mode clock Fosc 64 1 SPI master mode clock output TMR 2 0 SPI slave mode SS pin control enabled il SPI slave mode SS pin control disabled SS can be used as I O pin 0 IC slave mode 7 bit address used 1 IC slave mode 10 bit address used 0 12C master mode clock Fosc 4 SSPAD 1 1 0 1 0 1 0 1 Mask used in 12C slave mode Not used IC controlled master mode Not used Not used IC slave mode 7 bit address used START and STOP bits enable interrupt IC slave mode 10 bit address used START and STOP bits enable interrupt FHC2LnBHmnBrmPDrmniHBnboozcoccooocoso FHC 1LBLHRmnBoccocococmnOmDnD mmnmrmnmoocso PrPFoorraoaeorroor ero Table 6 3 Synchronous Serial Port Mode Select Bits http www mikroe com en books picmcubook ch6 21 of 27
240. nfigure voltage reference in the ADCON1 register Select ADC conversion clock in the ADCONO register Select one of input channels CHO CH13 of the ADCONO register Select data format using the ADFM bit of the ADCON1 register and Enable A D converter by setting the ADON bit of the ADCONO register Step 3 Configuring ADC interrupt optionally e Clear the ADIF bit and e Set the ADIE PEIE and GIE bits Step 4 Wait for the required acquisition time approximately 20uS to pass Step 5 Start conversion by setting the GO DONE bit of the ADCONO register Step 6 Wait for ADC conversion to complete e It is necessary to check in program loop whether the GO DONE pin is cleared or wait for an A D interrupt must be previously enabled Step 7 Read ADC results e Read the ADRESH and ADRESL registers Analog Comparator In addition to A D converter there is one more module which until quite recently has been embedded only in integrated circuits belonging to so called analog electronics Owing to the fact that it is hardly possible to find any more complex automatic device which in some way does not use these circuits two high quality comparators along with additional electronics are integrated into the microcontroller and connected to its pins How does a comparator operate Basically the analog comparator is an amplifier which compares the magnitude of voltages at two inputs Looking at its physical features it has two input
241. ng process and cannot be changed Since their bits are physically connected to particular circuits on the chip A D converter serial communication module etc any change of their contents directly affects the operation of the microcontroller or some of its circuits For example by changing the TRISA register the http www mikroe com en books picmcubook chl 9 of 14 5 3 2009 11 31 25 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 1 PIC16F887 Microcontroller Device Overview function of each port A pin can be changed in a way it acts as input or output Another feature of these memory locations is that they have their names registers and their bits which considerably facilitates program writing Since high level programming language can use the list of all registers with their exact addresses it is enough to specify the register s name in order to read or change its contents RAM Memory Banks The data memory is partitioned into four banks Prior to accessing some register during program writing in order to read or change its contents it is necessary to select the bank which contains that register Two bits of the STATUS register are used for bank selecting which will be discussed later In order to facilitate operation the most commonly used SFRs have the same address in all banks which enables them to be easily accessed Addr 00h 01h 02h 03h 04h 05h 06h orh oah 09h DAR OBh och ODh DER UF
242. nication between several microcontrollers The principle of operation is simple The master device sends 9 bit data which represents the address of one microcontroller All slave microcontrollers sharing the same transmission line receive this data Of course each of them must have the ADDEN bit set because it enables address detection ADDEN 1 ADDEN 1 ADDEN 1 9 bit address Upon receiving this data each slave checks if that address matches its own Software in which address match occurs must disable address detection by clearing its ADDEN bit The master device keeps on sending 8 bit data All data passing through the transmission line will be received by recognized EUSART module only Upon receiving the last byte the slave http www mikroe com en books picmcubook ch6 5 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules device should set the ADDEN bit in order to enable new address detection ADDEN 1 ADDEN 0 ADDEN 1 AAA 8 bit data Fig 6 7 Sending Data TXSTA Register CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D Readable Writable bit Readable bit After reset bit is cleared After reset bit is set Fig 6 8 TXSTA Register CSRC Clock Source Select bit determines clock source It is used only in synchronous mode e 1l Master mode Clock is generated internally from Baud Rate Generator and
243. nnected to the OSC1 and OSC2 pins Depending on features of the component in use select one of the following modes LP mode Low Power is used for low frequency quartz crystal only This mode is designed to drive only 32 768 kHz crystals usually embedded in quartz watches It is easy to recognize them by small size and specific cylindrical shape The current consumption is the least of the three modes XT mode is used for intermediate frequency quartz crystals up to 8 MHz The current consumption is the medium of the three modes and HS mode High Speed is used for high frequency quartz crystals over 8 MHz The current consumption is the highest of the three modes LP XT HS mode OSC1 Pin CPU gt 20 30pF OSC2 Pin E OSC 20 30pF Quartz crystal Fig 8 7 Schematic of External Oscillator and Additional External Components Ceramic resonators in XT or HS mode http www mikroe com en books picmcubook ch8 5 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits Fig 8 8 Ceramic Resonator Ceramic resonators are by their features similar to quartz crystals This is why they are connected in the same way Unlike quartz crystals they are cheaper and oscillators containing them have a bit worse characteristics They are used for clock frequencies ranging between 100 kHz and 20 MHz External oscillator in RC and RCIO mode There are
244. ntents of this register should be written to the register from which it was read SUM register address The same data bus is used for all these intermediate operations Harvard Architecture x8 x12 14 16 Microcontrollers using this architecture have two different data buses One is 8 bits wide and connects CPU to RAM Another consists of several lines 12 14 or 16 and connects CPU to ROM Accordingly the CPU can read an instruction and perform a data memory access at the same time Since all RAM memory registers are 8 bits wide all data within the microcontroller are exchanged in the same such format Additionally during program writing only 8 bits data are considered In other words all you can ever change from within the program and all you can affect will be 8 bits wide A program written for some of these microcontrollers will be stored in the microcontroller internal ROM upon having being compiled into machine language However these memory locations do not have 8 but 12 14 or 16 bits The rest of bits 4 6 or 8 represents the instruction itself specifying to the CPU what to do with the 8 bit data ii PIS PARRARAA AAA LLL LLL LT The advantages of such design are the following e All data in a program is one byte 8 bit wide As the data bus used for program reading has several lines 12 14 or 16 both instructions and data can be read simultaneously by using these spare bits Therefore
245. nterrupt TMR2IE TMR2 to PR2 Match Interrupt Enable bit o 1 Enables the TMR2 to PR2 match interrupt o 0 Disables the TMR2 to PR2 match interrupt TMRIIE TMR1 Overflow Interrupt Enable bit enables an interrupt request to be generated after each timer TMR1 register overflow i e when the counting starts from zero o 1 Enables the TMR1 overflow interrupt o 0 Disables the TMR1 overflow interrupt PIE2 Register The PIE2 Register also contains the various interrupt enable bits OSFIE C2IE CUE EEIE BCLIE ULPWUIE CCP2IE Legend Unimplemented bit RW XReadableWritable bit 0 After reset bit is cleared Fig 2 12 PIE2 Register OSFIE Oscillator Fail Interrupt Enable bit o 1 Enables oscillator fail interrupt o 0 Disables oscillator fail interrupt C2IE Comparator C2 Interrupt Enable bit o 1 Enables Comparator C2 interrupt o 0 Disables Comparator C2 interrupt C1IE Comparator C1 Interrupt Enable bit o 1 Enables Comparator Cl interrupt o 0 Disables Comparator C1 interrupt EEIE EEPROM Write Operation Interrupt Enable bit o 1 Enables EEPROM write operation interrupt o 0 Disables EEPROM write operation interrupt BCLIE Bus Collision Interrupt Enable bit o 1 Enables bus collision interrupt o 0 Disables bus collision interrupt ULPWUIE Ultra Low Power Wake up Interrupt Enable bit o 1 Enables Ultra Low Power Wake up interrupt o 0 Disables Ultra Low Power Wak
246. o data EEPROM is complete RD Read Control bit e 1 Initiates read from data EEPROM and e 0 Read from data EEPROM disabled Read from EEPROM Memory http www mikroe com en books picmcubook ch8 12 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits In order to read data EEPROM memory follow the procedure below Step 1 Write an address 00h FFh to the EEADR register Step 2 Select EEPROM memory block by clearing the EEPGD bit of the EECONI register Step 3 To read location set the RD bit of the same register and Step 4 Data is stored in the EEDAT register and ready to use The following example illustrates data EEPROM read BSF AOS EEI BCE STATUS REO MOVF ADDRESS W MOVWF EEADR Bou STATUS REO BCE EECONT EEPGD Bok EECONT RD BCE STATUS REO MOVE EEDATA W Access bank 2 Move address to the W register Write address Access bank 3 Select EEPROM Read data Access bank 2 Data is stored in the W register Ne Ne Ne Ne Wo 0899 wo o No Write to Data EEPROM Memory In order to write data to EEPROM memory first it is necessary to write the address to the EEADR register first and data to the EEDAT register afterwards Then you have to follow a special sequence to initiate write for each byte Interrupts must be disabled during this procedure Data EEPROM write is illustrated in the example below Boe SILA OS REI Bou STATUS REO
247. oElektronika Free Online Book PIC Microcontrollers Appendix B Examples 0 01 100mS Switch off moment 5V OV It is about contact bounce a common problem with mechanical switches When the contacts strike together their momentum and elasticity act together to cause bounce The result is a rapidly pulsed electrical current instead of a clean transition from zero to full current Generally it mostly occurs due to vibrations slight rough spots and dirt between contacts This effect is usually unnoticeable when using these components in everyday life because the bounce happens too quickly to affect most equipment but causes problems in some analogue and logic circuits that respond fast enough to misinterpret the on off pulses as a data stream Anyway the whole process does not last long a few micro or milliseconds but long enough to be registered by the microcontroller When using only a push button as a pulse counter errors occurs in almost 100 of cases This problem may be easily solved by connecting a simple RC circuit to surpress quick voltage changes Since the bounce period is not defined the values of components are not precisely determined In most cases it is recommended to use the values as shown in figure below D 5V If complete stability is needed then radical measures should be taken The output of the circuit shown in figure below RS flip flop will change its logic state only after detecting
248. oElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Tirners EE TEL Camrrunizstien CCP PWM Vo Parts Fig 0 1 Microcontroller versus Microprocessor On the other hand the microcontroller is designed to be all of that in one No other specialized external components are needed for its application because all necessary circuits which otherwise belong to peripherals are already built into it It saves the time and space needed to design a device BASIC CONCEPT http www mikroe com en books picmcubook ch0 3 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Did you know that all people can be classified into one of 10 groups those who are familiar with binary number system and those who are not familiar with it You don t understand That means that you still belong to the later group If you want to change your status read the following text describing briefly some of the basic concepts used further in this book just to be sure we are on the same page World of Numbers Mathematics is such a good science Everything is so logical and simple as that The whole universe can be described with ten digits only But does it really have to be like that Do we need exactly ten digits Of course not it is only a matter of habit Remember the lessons from the school For example what does the number 764 me
249. ocontrollers Appendix A Programming a Microcontroller In the event that a macro has labels they must be defined as local ones by using directive local The given example contains macro which calls a subroutine call label in this case if the Carry bit of the STATUS register is set Otherwise the first following instruction is executed SUBROUTINES Asubroutine contains a sequence of instructions begins with a label subroutine name and ends with command return or retlw The main difference comparing to macro is that subroutine is not replaced by its code in the program but program jumps to subroutine to execute it It happens every time the assembler encounters command call Subroutine name in the program On the command return it leaves a subroutine and continues execution from where it left off the main program Subroutine may be defined both prior to or upon the call Label subroutine name is Label poU mt sequence of instructions sequence of instructions sequence of instructions E return or retlw As seen concerning macros the input and output arguments are of great importance Concerning subroutines it is not possible to define arguments within the subroutine itself However variables predefined in the main program may be used as subroutine arguments A logical sequence of events is as follows defining variables calling subroutine which uses them and at the end reading variables changed upon the execution
250. oe com en books picmcubook ch8 11 of 15 5 3 2009 11 34 45 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 8 Other MCU s Circuits EECON1 control register EECON2 control register EEDAT saves data ready for write and read and EEADR saves address of EEPROM location to be accessed In addition EECON2 is not true register it does not physically exist It is used in write program sequence only The EEDATH and EEADRH registers belong to the same group as the registers used during EEPROM write and read Both of them are therefore used for program FLASH memory write and read Since this is considered a risk zone you surely do not want your microcontroller to accidentally erase your program we will not discuss it further but advise you to be careful EECON1 Register EEPGD WRERR WREN WR RD Bit is unimplemented Readable Writable bit Readable bit Bit can only be set After reset bit is cleared After reset bit is unknown Fig 8 18 EECON1 Register EEPGD Program Data EEPROM Select bit e 1 Access program memory and e 0 Access EEPROM memory WRERR EEPROM Error Flag bit e 1l Write operation is prematurely terminated and error has occurred and e 0 Access EEPROM memory WREN EEPROM Write Enable bit e 1 Write to data EEPROM enabled and e 0 Write to data EEPROM disabled WR Write Control bit e 1 Initiates write to data EEPROM and e 0 Write t
251. of Contents Next Chapter http www mikroe com en books piemcubook appb 54 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix C Development Systems TOC Introduction Ch 1 She Ch 3 Ch 4 Ch 5 Ch 6 Ch 7 Ch 8 Ch 9 App A App B App C Appendix C Development Systems How to start working A microcontroller is a good natured genie in the bottle and no extra knowledge is required to use it In order to create a device controlled by the microcontroller it is necessary to provide the simplest PC program for compiling and simple device to transfer that code from PC to chip itself Even though this process is quite logical there are often some queries not because it is complicated but for numerous variations Let s take a look WRITING PROGRAM IN ASSEMBLY LANGUAGE In order to write a program for the microcontroller a specialized program in the Windows environment may be used Any program for text processing can be used for this purpose The point is to write all instructions in such an order they should be executed by the microcontroller observe the rules of assembly language and write instructions exactly as they are defined In other words you just have to follow the program idea That s all When using custom software there are numerous tools which are also installed to aid in the development process One such tool is the Simulator This enables the user to te
252. of the SSPCON2 register should be set in order to enable sending acknowledge bit and e In order to inform Slave device that transmit is complete the STOP condition should be initiated by setting the PEN bit of the SSPCON register Previous Chapter Table of Contents Next Chapter http www mikroe com en books picmcubook ch6 27 of 27 5 3 2009 11 34 00 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules e TOC e Introduction e Ch e Ch e Ch e Ch e Ch e Ch e Ch e Ch e Ch e App A e App B e App C 1 OU O N wn Ui A W N Chapter 7 Analog Modules Apart from a large number of digital I O lines the PIC16F887 contains 14 analog inputs They enable the microcontroller to recognize not only whether a pin is driven to logic zero or one 0 or 45V but to precisely measure its voltage and convert it into a numerical value i e digital format The whole procedure takes place in the A D converter module which has the following features The converter generates a 10 bit binary result using the method of successive approximation and stores the conversion results into the ADC registers ADRESL and ADRESH There are 14 separate analog inputs The A D converter allows conversion of an analog input signal to a 10 bit binary representation of that signal and By AG NS references Vref and Vref the minimal resolution or quality of conversion may be adjusted to various needs
253. of the port B general purpose I O pins has changed state Upon reading portB RBIF flag bit must be cleared in software o 0 None of the port B general purpose I O pins has changed state PIE1 Register The PIE1 register contains the peripheral interrupt enable bits gt ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMRIIE Legend Unimplemented bit RW Readable Writable bit 0 After reset bit is cleared Fig 2 11 PIE1 register e ADIE A D Converter Interrupt Enable bit o 1 Enables the ADC interrupt o 0 Disables the ADC interrupt e RCIE EUSART Receive Interrupt Enable bit o 1 Enables the EUSART receive interrupt o 0 Disables the EUSART receive interrupt e TXIE EUSART Transmit Interrupt Enable bit o 1 Enables the EUSART transmit interrupt o 0 Disables the EUSART transmit interrupt http www mikroe com en books picmcubook ch2 6 of 12 5 3 2009 11 32 08 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 2 Core SFRs SSPIE Master Synchronous Serial Port MSSP Interrupt Enable bit enables an interrupt request to be generated after each data transfer via synchronous serial communication module SPI or I2C mode o 1 Enables the MSSP interrupt o 0 Disables the MSSP interrupt CCPIIE CCP1 Interrupt Enable bit enables an interrupt request to be generated in CCP1 module used for PWM signal processing o 1 Enables the CCP1 interrupt o 0 Disables the CCP1 i
254. ok KKK KK KK KK KKK KKK KK KK KK KK KK KR KR KKK OK KR KKK OK KK KK KK i DEFINING VARIABLES eode 0x20 Block oir variables otarre ae address Oh w_temp Variable at address 20h pclath_temp Variable at address 21h Status temp Variable at address 22h Ne Ne Ne N endc define DARK PORTB 0 esum ns Du OI DARK as conmecred DESECHOS define ERICHT PFORTE Push _burcon BRIGHI i3 connected 0 RORTE I jes KK KK KK KK KK KK KK KK KK KK KKK KK KKK KK KKK KK KKK KKK KKK KK KKK KKK KKK KKK PROGRAM START ona 0x0000 SO OE sligsic e acoja SNO LOL e SIS goro main mp to ancla KK KK KK KR KKK RK KK KK KK KK KKK KK RK KK KKK KK KKK KKK KK KK KKK KKK KKK INTERRUPT ROUTINE oue 0x0004 Interrupt vector movw f w temp Save register W mov f STATUS Save register STATUS movwf Status temp http www mikroe com en books picmcubook appb 36 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples mov f movw f banksel lone IESUS decf lods TETTE movft movwt MOVE movwt swapf swapf banksel DCE DSE bsf DSE retfie PCLATH pelar Mil SERIE DARK CCIE IIb BEIGE AE pclath_temp w PCLATH Status TCenp w SIATUS w_temp f WE SI PIRI PTR EMR LIE Ti EF TMR1H 6 IINE CIO NE Ne Ne Ne Ne Ne Ne Ne Ne Save register PCLATH Rests PUO OUTOON IDE Push button is pressed decrement CCPIL by 1 Testing PU n oq ae e ETSI HR Push Durton ls pr
255. oks picmcubook ch9 23 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set the value 0x00 ARTE instruction Webs FSR 0xC2 register at address OxC2 contains the value 0x17 N OP No Operation Syntax label NOP Description No operation Operation Operand Status affected Number of cycles 1 EXAMPLE label NOP lus delay oscillator 4MHz Eetore unmnsteuettonsexecqdbqrone Pe c ep ele fas ISI OE OE PC x 1 RETFIE Return from Interrupt Syntax labels RETFIE Description Return from subroutine The value is popped from the stack and loaded to the program counter Interrupts are enabled by setting the bit GIE of the INTCON register Operation TOS PC 1 gt GIE Operand Status affected Number of cycles 2 http www mikroe com en books picmcubook ch9 24 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set EXAMPLE label RETFIE Bello mein aci e de Mo BO X GIE interrupt enable bit of the SATUS register O After Ino Pate uen E I Suo se GIE 1 RE TI LW Return with literal in W Syntax label RETLW k Description 8 bit literal k is loaded into register W The value from the top of stack is loaded to the program counter Operation k gt W top of stack TOP gt PC Operand Status affected Number of cycles 2
256. ollers Chapter 5 CCP Modules bit enabling CCPIIE interrupt and flag bit CCP1IF should be cleared prior to any change occuring in the control register Undesirable interrupt may be also generated by switching from one capture prescaler to another To avoid this the CCP1 module should be temporarily switched off before changing the prescaler The following program sequence is recommended BANKESEL CCPICON CERE ERCON CONI TOLT ECI TERTI COE I POESIE T C CPI MODULE To OFF MOVLW XX NEWTERESCALCER MODETIS SELECTED MOVWE COPISON NEW VALUE To LOADED AO Tit CONTROL REGISTER RIO MODULE fs O IMUC TANEOUS iS CAD SONS CCP1 in Compare mode In this mode the value in the CCP1 register is constantly compared to the value in the timer register TMR1 When a match occurs the output pin RC2 CCP1 logic state may be changed which depends on the state of bits in the control register CCP1M3 CCP1MO The flag bit CCPIIF will be simultaneously set 4 Flag bit CCPT1IF Timer T1 CCPR1 Reset __ DL ni Logic z a _ CCP1M3 TRISC 2 CCP1M2 CCP1M1 CCP1MO Fig 5 3 CCP1 in Compare mode To setup CCP1 module to operate in this mode two conditions must be met e Pin RC2 CCP1 must be configured as output and e Timer TMR1 must be synchronized with internal clock CCP1 in PWM mode Signals of varying frequency and duty cycle have a wide application in automation A typical example is a power control circuit whose simple
257. ollers Chapter 8 Other MCU s Circuits When power supply voltage reaches 1 2 1 7V a circuit Umax called Power up timer resets the microcontroller within approximately 72mS Immediately upon this time has run Unam out the reset signal generates another timer called Oscillator start up timer within 1024 quartz oscillator periods When this delay is over marked as T reset in figure and the MCLR pin is set high the microcontroller starts to execute the first instruction in the program Fig 8 19 Oscillator Start Up Time Delay O Power Supply Voltage Time Apart from such controlled reset which occurs at the moment power goes on there are another two resets called Black out and Brown out which may occur during operation as well as at the moment power goes off Black out reset Black out reset takes place when the power supply normally goes Umax gt a off In that case the microcontroller has no time to do anything Unam unpredictable simply because the voltage drops very fast beneath its minimal value In other words the light goes off curtain falls Jmin down and the show is over Fig 8 20 Black Out Reset at Loss Of Power A Power Supply Voltage Time Brown out reset Umax When power supply voltage drops slowly typical example of that is battery discharge although the microcontroller experiences far ii faster voltage drop as a slow process the internal electronics Unin gradually stops operating
258. onditional branch instructions if condition is met or instructions being executed upon the program counter In both cases two cycles are required for instruction execution where the second cycle is executed as a NOP No Operation A single cycle instruction consists of four clock cycles If 4MHz oscillator is used a nominal time for instruction execution is 1u S In case of jump the instruction execution time is 2u S Legend http www mikroe com en books picmcubook ch9 4 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set f Any memory location register W Working register accumulator b Bit address within an 8 bit register d Destination bit label Set of 8 characters indicating start of particular address in the program TOS Top of stack Option lt bit field in register several bit addresses C Carry Borrow bit of the STATUS register DC Digit Carry bit of the STATUS register and Z Zero bit of the STATUS register ADDLW Add literal and W Syntax label ADDLW k Description The content of the register W is added to the 8 bit literal k The result is stored in the W register Operation W k gt W Operand 0 lt k lt 255 Status affected C DC Z Number of cycles 1 EXAMPLE label ADDLW 0x15 Before instruction execution W 0x10 Arter instruction W 0x203 C 0 the result is not greater than OxFF whic
259. ons RETURN RETLW Or RETFIE to return to the main program the microcontroller will simply continue program execution from where it left off because the return address is pushed and saved onto the stack which as mentioned consists of 13 bit registers Indirect addressing In addition to direct addressing which is logical and clear by itself it is sufficient to specify address of some register to read its contents this microcontroller is able to perform indirect addressing by means of the INDF and FSR registers It sometimes considerably simplifies program writing The whole procedure is enabled because the INDF register is not true one physically does not exist but only specifies the register whose address is located in the FSR register Because of this write or read from the INDF register actually means write or read from the register whose address is located in the FSR register In other words registers addresses are specified in the FSR register and their contents are stored in the INDF register The difference between direct and indirect addressing is illustrated in the figure 2 18 below As seen the problem with the missing addressing bits is solved by borrowing from another register This time it is the seventh bit called IRP from the STATUS register http www mikroe com en books picmcubook ch2 11 of 12 5 3 2009 11 32 08 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 2 Core SFRs Direct address
260. ook PIC Microcontrollers Appendix A Programming a Microcontroller gt FILE REGISTERS option If the program contains variables it is good to monitor their values as well Each variable is assigned a window Watch Windows by clicking VIEW gt WATCH option m Feoweril APA DI rs he ddr mee vase Deep Poe ook G rato Leip Du Ll he iut Faaa f a d Gh G amp ope hee cesa ME ae ee E DL a5 DL Fai CONFIG _COMFIGL LVM DFF amp TOMIN OM amp TESO OFF amp DOR CEF amp CPD OFF i gt um O CONFIG COMFIGZ WKT OFF 4 BORZIV ilicis 4 amp DIIN Be 00041100 sgigl Per Daklara ija promamnjlwih Eeklargect a promenjl lih CEL E 0x20 Bocetek RA amp H a HI lt A BER uris Los Pont one ae Struk tu r amp POoqregeks Besos pe SNAR HAG 0400 i A BELGE goats Hain la Er Osta i In amp ar amp pt vector SE BESESESEREBEHSESEBERZ Hain ASE LDnLterwpr TUELES TRISH i Pocetak programa TRIGA 0 TRIGA 2 THIEB 0 besRwel PRE ent a SERPERERERRRERERE EE a Leet fi jx PORTA 0 2 Po vena PORTA 1 0 Emariji Loop Boece ent f ent y PORTE Leap 9282823 HEHEHEHEHSEHEBESRBERBSE HEHEHEHEIJHEBERERBSE HEHEHEHEHEHEBERERBSE 2HEHEHEHEHJHERERERE i ESEBEBSEBERERERE R MESESERERERERERSS ESESESEEEBSEHERE S ent f ant e PORTE Loop Wn 1157 a J 14 15 amp 17 LH La E 21 a a e ct a7 E 2g 30 zn az 3 4 E Ej 7 g ma 1 a 3 14 5
261. or FLASH memory programming Vpp 12 14V During programming Vpp voltage is applied to the MCLR pin All details concerning this process as well as which one of these http www mikroe com en books picmcubook ch3 6 of 10 5 3 2009 11 32 31 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 3 I O Ports voltages is applied first are beside the point the programmers electronics are in charge of that The point is that the program can be loaded to the microcontroller even when it is soldered onto the target device Normally the loaded program can also be changed in the same way This function is called ICSP In Circuit Serial Programming It is necessary to plan ahead when using it It is not complicated at all It is only necessary to install a 4 pin connector onto the target device so that the necessary programmer voltages may be applied to the microcontroller In order that these voltages don t interfere with other device electronics design some sort of circuit breaking into this connection using resistors or jumpers PIC16F887 Fig 3 10 ICSP Connection PICTBSF887 hese voltages are applied to socket pins in which the microcontroller is to be placed Fig 3 11 Programmer On Board Connections Port C and TRISC Register Port C is an 8 bit wide bidirectional port Bits of the TRISC Register determine the function of its pins Similar to other ports a logic one 1 in the TRISC Register configu
262. or loading into the microcontroller 1 Make a project 2 Write a program and 3 Compile it In order to make a project it is necessary to click the option PROJ ECT and then PROJ ECT WIZARD A welcome window appears Edit View Debugger Project Wizard Project Wizard Welcome This wizard helps you create or configure a new MPLAB IDE project To continue click Next http www mikroe com en books picmcubook appa 14 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller Project Wizard Keep on project making by clicking NEXT Then select the AAA microcontroller you will be using In our case it is PIC16F887 microcontroller Device PIC BREE At the end the project is assigned a name which usually indicates the purpose and the content of the program being written The project should be moved to the desired folder It is best that the folder associates with PIC microcontrollers See figure Step Two Select a language tonlsudbe Achve Toolsute Microchip MPASM Toolsu e Wosbee inne Project Wizard MPASM Assemble mpasmwmn exe MPLIHK Object Linker mplink eos MPLIB Librarian mplib ene Step Three Create a new project of reconfigure the active project Location C Program FilesWiicrochipMPA5hM Su Create New Project File Proba Heb My Su
263. ot always If for any reason power supply voltage does not reach full value within 10mS display will start performing completely unpredictably If voltage supply unit is not able to meet that condition or if it is needed to provide completely safe operation the process of initialization is applied Initialization among other things causes a new reset enabling display to operate normally Refer to the figure below for the procedure on 8 bit initialization Wait for more than 15mS RS RW D7 D6 DS D4 D3 D2 D1 DO Bit BF cannot be checked before this instruction Display is set to 8 bit mode Wait for more than 4 1mS RS RW D7 D6 D5 D4 D3 D2 D1 DO Bit BF cannot be checked before this instruction 0 0 0 O 1 x x x x Display is set to 8 bit mode Wait for more than 100uS RS R W D7 D6 D5 D4 DS Di DO Bit BF cannot be checked before this instruction Display is set to 8 bit mode Bit BF can be checked after the following instructions R W D7 D6 D5 D4 D3 D2 D1 DO The number of display lines and character font have to be defined and these values cannot 001 1 N F X X be changed after this point Display off Display off Display off Initialization ends http www mikroe com en books picmcubook appb 17 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples INManzadon enus It is not a mistake In this algorithm the same value is transferred three times in a
264. ould be cleared and the SPEN bit should be set RCSTA register in order to enable serial port If it is necessary the data receive causes an interrupt both the RCIE bit of the PIE1 register and bits GIE and PEIE of the INTCON register should be set On 9 bit data receive the RX9 bit of the RCSTA register should be set Data receive should be enabled by setting the CREN bit of the RCSTA register The RCSTA register should be read to get information on possible errors which have occurred during transmission On 9 bit data receive the ninth bit will be stored in this register and Received 8 bit data stored in the RCREG register should be read M ND I IAN Setting Address Detection Mode ee Rate should be set by using bits BRGH TXSTA register and BRG16 BAUDCTL register and registers SPBRGH and SPBRG The 2 bit TXSTA register should be cleared and the SPEN bit should be set RCSTA register in order to enable serial port If it is necessary the data receive causes an interrupt the RCIE bit of the PIE1 bit as well as bits GIE and PEIE of the INTCON register should be set The RX9 bit of the RCSTA register should be set The ADDEN of the RCSTA register should be set which enables a data to be interpreted as address Data receive is enabled by setting the CREN bit of the RCSTA register Immediately upon 9 bit data Is received the RCIF bit of the PIRI register will be automatically set If enabled an interrupt occurs The RCSTA reg
265. ovu lokaciju ORG Gai Interapt vector gato Hain nena int r apt rutina Hain Pocset k progress bankzel TRISB Ggleltuj baku u kojoj Je TRISB clr TRISH Port E ja izlazni bankzel FORTE Selektuj baca u mojoj je FORTE serlo Ds PE WeFF sora PORTA Portavi sve jedinice na port B Loop goto Loop Skoci n labelu Loop End SIMULATOR Asimulator is a part of MPLAB environment which provides better insight into the operation of the microcontroller Generally speaking a simulation is an attempt to model a real life or hypothetical situation so that it can be studied to see how the system works By means of the simulator it is also possible to monitor current values of variables registers and port pins states as well To be honest a simulator is not of the same importance for all programs If a program is simpler as in our example the simulation is not of great importance because setting port B pins to logic one 1 is not complicated at all However in more complex programs containing timers different conditions and requests especially mathematical operations the simulator may be of great use As the name itself indicates a simulation means to simulate the operation of microcontroller Like the microcontroller a simulator executes instructions one after another line by line and constantly updates the state of all registers In this way the user simply monitors program execution At the end of program writing the
266. p www mikroe com en books picmcubook ch6 24 of 27 5 3 2009 11 34 00 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules Slave Address o Oo SDA pin SSPBUF 1 x x x x x x x A hi n seco OO Gee SDA pin SSPSR x XXX Xx X xxx A nu wv SSPBUF x x x x x x x x A Dae Data Fig 6 30 Data Reception in I C Master Mode Start Address Acknowledge Data Acknowledge Data Acknowledge Stop In this pulse condition the acknowledge bit is sent to slave device Baud Rate Generator In order to synchronize data transmission all events taking place on the SDA pin must be synchronized with the clock generated in master device This clock is generated by a simple oscillator whose frequency depends on the microcontroller s main oscillator frequency value written to the SSPADD register and the current SPI mode The clock frequency of the mode described in this book depends on selected quartz crystal and the SPADD register The formula used to calculate it is shown in figure below http www mikroe com en books picmcubook ch6 25 of 27 5 3 2009 11 34 00 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules Frequency X X XIX X X x SSPADD Baud Rate frequency ES EIE 1 0 00 SSPCON Fosc 4 SSPADD 1 Mode F Fig 6 31 Baud Rate Generator Useful notes When the microcontroller
267. performed between the corresponding registers bits the same as in logic AND operation NOT Gate This logic gate has only one input and only one output It operates in an extremely simple way When logic zero 0 appears on its input a logic one 1 appears on its output and vice versa This means that this gate inverts the signal by itself It is sometimes called inverter http www mikroe com en books picmcubook ch0 10 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers If a program logic NOT operation is performed on one byte The result is a byte with inverted bits If byte is considered to be a number the inverted value is actually a complement of that number i e the complement of a number is what is needed to add to it to make it reach the maximal 8 bit value 255 Result EXCLUSIVE OR Gate The EXCLUSIVE OR XOR gate is a bit complicated comparing to other gates It represents a combination of all A the previously described gates A logic one 1 appears on its output only when the inputs have different logic states Output In a program this operation is commonly used to compare two bytes Subtraction may be used for the same purpose if the result is O bytes are equal The advantage of this logic operation is that there is no danger to subtract larger number from smaller one Register A register or a memory cell is an el
268. pins http www mikroe com en books picmcubook ch5 13 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules PRSEN PDC6 PDC5 PDC4 PDC3 PDC2 PDC1 PDCO_ Legend RW Readable Writable bit 0 After reset bit is cleared Fig 5 18 PWMICON Register PSTRCON Register STRSYNC Steering Sync bit determines the moment of PWM pulse steering e 1 Steering occurs upon the PSTRCON has been changed but only if a PWM waveform is completed and e 0 Steering occurs upon the PSTRCON register has been changed The PWM signal on output pin is immediately changed with no regard to whether the previous cycle is completed or not This operation is useful when it is needed to immediately remove a PWM signal from the pin STRD Steering Enable bit D determines the P1D pin function e 1 PID pin has the PWM waveform with polarity controlled by the CCP1MO and CCP1M1 bits and e 0 Pin is configured as general Port D input output STRC Steering Enable bit C determines the P1C pin function e 1 P1C pin has the PWM waveform with polarity controlled by the CCP1MO and CCP1M1 bits and e 0 Pin is configured as general port D input output STRB Steering Enable bit B determines the P1B pin function e 1 P1B pin has the PWM waveform with polarity controlled by the CCP1MO and CCP1M1 bits and e 0 Pin is configured as general port D input output STRA Steering Enable b
269. pl PS2 PS1 PSO Prescaler Rate Select bits Prescaler rate is selected by combining these three bits Described as shown in the table below prescaler rate depends on whether prescaler is assigned TMRO or watch dog timer WDT PS2 PS1 PSO TMRO WDT 0 0 0 de dla 0 0 1 1 4 1 2 0 1 0 1 8 1 4 0 1 1 1 16 1 8 1 0 l 1 64 ie os http www mikroe com en books picmcubook ch2 3 of 12 5 3 2009 11 32 08 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 2 Core SFRs 1 1 0 1 128 1 64 1 1 1 1 256 PAZO Table 2 2 In order to achieve 1 1 prescaler rate when the timer TMRO counts up pulses the prescaler should be assigned to the WDT As a result of this the timer TMRO does not use the prescaler but directly counts pulses generated by the oscillator which was the objective Interrupt System Registers When an interrupt request arrives it does not mean that interrupt will automatically occur because it must also be enabled by the user from within the program Because of that there are special bits used to enable or disable interrupts It is easy to recognize these bits by IE contained in their names stands for Interrupt Enable Besides each interrupt is associated with another bit called the flag which indicates that interrupt request has arrived regardless of whether it is enabled or not They are also easily recognizable by the last two letters contained in their names IF Interrupt Flao As seen everything is
270. ple of their operation will be discussed here AND Gate A logic gate AND has two or more inputs and one output Let us presume that the gate used in this case has only two inputs A logic one 1 will appear on its output only in case both inputs A AND B are driven to logic one 1 The table shows mutual dependence between inputs and output When the gate has more than two inputs the principle of operation is the A B Output same a logic one 1 will appear on its output only if case all inputs are driven olo O to logic one 1 Any other combination of input voltages will result in a logic zero 0 at its output 1 0 0 http www mikroe com en books picmcubook ch0 9 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers A 11 1 When used in a program a logic AND operation is performed by the program instruction which will be discussed later For the time being it is enough to remember that logic AND in a program refers to the corresponding bits of two registers Result OR Gate Similarly to the previous case OR gates also have two or more inputs and one output A logic one 1 will appear on its output if either input A OR B is A B O0 t t driven to logic one 1 If all inputs are at logic zero 0 the output will be utpu driven to logic zero 0 oo o ajil 1 In a program logic OR operation is
271. program on a personal computer used to translate assembly language statements into the language of zeros and ones A compiled program is also called Machine Code A Program is a data file stored on a computer hard disc or in memory of the microcontroller if loaded and written according to the rules of assembly or some other programming language Assembly language is understandable for humans because it consists of meaningful words and symbols of the alphabet Let us take for example the command RETURN which is as its name indicates used to return the microcontroller from a subroutine In machine code the same command is represented by a 14 bit array of zeros and ones understandable by the microcontroller All assembly language commands are similarly compiled into the corresponding array of zeros and ones A data file used for storing compiled program is called an executive file i e HEX data file The name comes from the hexadecimal presentation of a data file and has a suffix of hex as well for example probe hex After has been generated the data file is loaded into the microcontroller using a programmer Assembly language programs may be written in any program for text processing editor able to create ASCII data files on a hard disc or in a specialized work environment such as MPLAB described later al Operat ELEMENTS OF ASSEMBLY LANGUAGE http www mikroe com en books piemcubook appa 1 of 21 5 3 2009 11 35 35 AM m
272. r example http www mikroe com en books picmcubook appb 20 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples sie c EIS O GIL It means that the GIE bit of the INTCON register should be set Instruction as such makes no sense to the compiler It has to access the inc document in order to know that the seventh bit of the SFR at the address 000B hex should be set m EQU H D OD F H 0DO1 ETE Register Files aman EQU H O UDQ TMEO EQU H OODI dea Eve Pda i BANK 0 REGISTER DEFINITIONS STATUS EQU H DQ Ae ee M e o LM o ek Ee iens n Rabat STATUS Bits PORTA EQU H O005 EQU aA 0007 PORTB EQU H O006 RP1l EQU H O00nDs s PORTC EQU H ODO7 app At uann PORTD EQU H ODOS PORTE EQU H ODos PCLATH EQU H ODOA INTCON EQU H 000B PIRI EQU H 000c PIR2 EGU H ODOD TMR1L EQU H ODOE TMRlH EQU H ODOF CONFIGI EQU H 2007 TICON EQU H 0010 TE j CONFIG2 EQU H 2008 THMRZ EQU H OQUO11 T2CON EQU H DIZ Configuration Wordl DEBUG ON EQU H lFFF DEBUG OFF EQU H 3FFF LVP ON EQU H 3FFF LVP OFF EQU H 2FFF FCMEN ON EQU H 3FFF FCMEN OFF EQU H 37FF IESO ON EQU H 3FFF errorlevel 302 This is a cosmetic directive which disables the irritating message Register in operand not in to appear at the end of every compiling process It is not necessary
273. r from sleep mode if it is setup in that mode CM1CONO Register http www mikroe com en books picmcubook ch7 8 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules C1ON C1OUT CIOE CIPOL CIR C1CH CICHO Bit is unimplemented RW Readable Writable bit Readable bit After reset bit is cleared R 0 Fig 7 8 CMICONO Regsiter Comparator C1 Bits of this register are in control of the comparator C1 It mainly affects configuration of its inputs To understand it better look at figure 7 9 below which shows only a part of electronics directly affected by the bits of this register Fins HA F hi 4 0 nma m a I C12IN0 x C121N1 C121N2 C121N3 peo C11N E gt C10UT A E ND Vref 0 6V CVref C1RSEL g Fig 7 9 Comparator C1 Enable Bit C10N Comparator C1 Enable bit enables comparator C1 e l Comparator C1 is enabled and e 0 Comparator C1 is disabled C10UT Comparator C1 Output bit is comparator C1 output bit If CIPOL 21 comparator output is inverted Analog voltage at C1Vin is lower than analog voltage at C1Vin and e 0 Analog voltage at ClVin is higher than analog voltage at C1Vin e 1 If CIPOL 0 comparator output is non inverted e 1 Analog voltage at ClVin is higher than analog voltage at C1Vin and e 0 Analog voltage at C1Vin is lower than analog voltage at C1Vin C1
274. r second bps It should be noted that it refers to bits not bytes It is usually required by the protocol that each byte is transferred along with several control bits It means that one byte in serial data stream may consist of 11 bits For example if the baud rate is 300 bps then maximum 37 and minimum 27 bytes may be transferred per second which depends on type of connection and protocol in use The most commonly used serial communication systems are http www mikroe com en books picmcubook ch0 18 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers I2C Inter Integrated Circuit is a system used when the distance between the microcontrollers is short and specialized integrated circuits of of a new generation receiver and transmitter are usually on the same printed circuit board Connection is established via two conductors one is used for data transfer whereas another is used for synchronization clock signal As seen in figure one device is always the master It performs addressing of one slave chip subordinated before communication starts In this way one microcontroller can communicate with 112 different devices Baud rate is usually 100 Kb sec standard mode or 10 Kb sec slow baud rate mode Systems with the baud rate of 3 4 Mb sec have recently appeared The distance between devices which communicate via an inter integrated circuit bus is limit
275. rand 0 lt f lt 127 Ox bx 7 Status affected Number of cycles 1 EXAMPLE 1 Mabel BCE REG 7 Ecdbemcdh Sidi esee som E51 OO E TESTE IO NS ede UIS AE O OOO SO EXAMPLE 2 label BCF INDF 3 Before instruction execution W 0x1 ESR 0C Register at address Ox2F Auc uWnstrucidonmnme N OI BSR TORO Z Register at address 0x2 BSF Bit set f Syntax label BSF f b Description Bit b of register f is set Operation 1 gt f b Operand 0 lt f lt 127 0 lt b lt 7 http www mikroe com en books picmcubook ch9 9 of 35 5 3 2009 11 35 12 AM FSR contains the value FSR contains the value mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set Status affected Number of cycles 1 EXAMPLE 1 label BSF REG 7 Before instruction execution REG 905907 gt 0000 Cll 0x07 After Y ure ct ons REG USO y du DIET TOR EXAMPLE 2 I aped BSE TNDE Fs Before instruction execution W 0x17 ESR 59 Register at address FSR contains the value USAN After instruction W Ox17 FSR OxC2 Register at address FSR contains the value 0x28 BTFSC Bit test f Skip if Clear Syntax label BTFSC f b Description If bit b of register f is 0 the next instruction is discarded and a NOP is executed instead making this a two cycle instruction Operation Discard the next instruction if f b 20 Operand 0 lt f lt 127 0x bx 7 Status affected http ww
276. rcuit itself It meant that configuration would be simpler but it would require far more memory than the project proposed by J apanese engineers After a while even though the J apanese engineers were trying to find an easier solution Marcian s idea won and the first microprocessor was born A major help with turning an idea into a ready to use product was Federico Faggin Nine months after hiring him Intel succeeded in developing such a product from its original concept In 1971 Intel obtained the right to sell this integrated circuit Before that Intel bought the license from BUSICOM which had no idea what a treasure it had During that year a microprocessor called the 4004 appeared on the market That was the first 4 bit microprocessor with the speed of 6000 operations per second Not long after that an American company CTC requested from Intel and Texas Instruments to manufacture an 8 bit microprocessor to be applied in terminals Even though CTC gave up this project Intel and Texas Instruments kept working on the microprocessor and in April 1972 the first 8 bit microprocessor called the 8008 appeared on the market It was able to address 16Kb of memory had 45 instructions and the speed of 300 000 operations per second That microprocessor was the predecessor http www mikroe com en books picmcubook ch0 1 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers of all today
277. rectly it is necessary to add a decimal number 48 to each of them prior to sending them to LCD http www mikroe com en books picmcubook appb 14 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples What is ASCII From their inception till today computers can recognize only numbers but not letters It means that all data a computer swaps with a peripheral device has a binary format even though the same is recognized by the man as letters The keyboard is an excellent example It s as simple as that every character matches the unique combination of zeroes and ones ASCII is character encoding based on the English alphabet ASCII code specifies a correspondence between standard character symbols and their numerical equivalents LCD Basic Commands All data transferred to LCD through the outputs DO D7 will be interpreted as a command or a data which depends on the pin RS logic state RS 1 Bits DO D7 are addresses of the characters to be displayed LCD processor addresses one character from the character map and displays it The DDRAM address specifies the location on which the character is to be displayed This address is defined prior character transfer or the address of the previously transferred character is automatically incremented RS 0 Bits DO D7 are commands which determine display mode The commands recognized by the LCD are listed in table below Command RS RW D
278. ree Online Book PIC Microcontrollers Appendix B Examples 1 1 1 ENDW pios dede ENDM e Ac e AC ARA ARA SO ATEOS TRAS TRAGOS PAG AT Soe ORAS CRUS OUO Ae A CPUS den e ATAS TAS AZ ASA KREK NK ROS RAKAR RAR TAS RAT WAG K AA This macro writes value in size of 1 byte on LCD excluding leading zeros VA ROBO RA RO ROCA QUA ASIA ECC Wak AS A tan WAS Ea TAL dal ai eat PARAS Lak AE eal All At IO Tae da A RAO AS US Cahora cat Gall ak wale Tah Val AGUA RIA LOK CARO CATAS ah VAN GIC NUAGE E tah AGIS CAE IRA Ne Ne UM Ne lcdbyte MACRO argo digbyte argo A hundred is in Digz Atonas In Digiland one an DS movf DIG W addlw 0x30 ccu IE OIBIereue MOVE Digli wW Eg ncs O move cursor addlw 0x30 cel new care movf BIGO W d Ii oasis ee soe addlw 0x50 col Onda ENDM AKAAKA LS LATAS YAGI AS AG MAT A A US LAS TS LT A LAS EK AS SR AS Pak tal A Tok CA TAS AS Vas RA LAS EAL AT Cae TAL A A LAS Yak AS LA RS AL IN AS ral A AS AS ims Delay Delaylms mov lw 22810 movwf ODE DelaylOus nop IE BIS nop jus nop PIMOS Nop EIS nop cs nop ADS nop e decfsz IE OXOJE eunte AS gorto Delay10us PAKS SAA EXAMPLE 16 RS232 serial communication This example illustrates the use of the microcontroller s EUSART module Connection to the PC is enabled through RS232 standard The program works in the following way Every byte received via the serial communication is displayed using LED diodes connected to port B and is automatically returned to the tr
279. ree signal LEDs and simultaneously monitor the logic state of five sensors or push buttons Some of ports need to be configured so that there are three outputs connected to the LEDs and five inputs connected to sensors It is p simply performed by software which means that the pin s function can be changed during operation http www mikroe com en books picmcubook ch0 13 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Microcontroller Fig 0 19 Input Output ports One of the more important specifications of input output I O pins is the maximum current they can handle For most microcontrollers current obtained from one pin is sufficient to activate an LED or other similar low current device 10 20 mA If the microcontroller has many 1 0 pins then the maximum current of one pin is lower Simply put you cannot expect all pins to give maximum current if there are more than 80 of them on one microcontroller Another way of putting it is that the maximum current stated in the data specifications sheet for the microprocessor is shared across all I O ports Another important pin function is that it can have pull up resistors These resistors connect pins to the positive power supply voltage and their effect is visible when the pin is configured as an input connected to mechanical switch or push button Newer versions of microcontrollers have pull
280. res the appropriate port pin as an input Legend RAW Readable Writable bit x After reset bit is unknown 1 After reset bit is set Fig 3 12 Port C and TRISC Register All additional functions of this port s bits will be explained later Port D and TRISD Register Port D is an 8 bit wide bidirectional port Bits of the TRISD register determine the function of its pins A logic one 1 in the TRISD register configures the appropriate port pin as input http www mikroe com en books picmcubook ch3 7 of 10 5 3 2009 11 32 31 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 3 I O Ports RIW x RW x RAW x RW RW x RW x RW x X RU x Features PORTO RD7 RD6 RDS RD4 RD3 RD2 RD RDO Bitname Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 RIW 1 RIW 1 RIW 1 X RIW 1 X RW 1 RAW 4 RW 1 RW T Features TRISD Bit name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit Legend RW Readable Writable bit x After reset bit is unknown 1 After reset bit is set Fig 3 13 Port D and TRISD Register Port E and TRISE Register Port E is a 4 bit wide bidirectional port The TRISE register s bits determine the function of its pins Similar to other ports a logic one 1 in the TRISE T configures the appropriate port pin as input The exception is RE3 which is input only and its TRIS bit is always read as RW x Rd RW x RW x Features Bit 7 Bit
281. result is copied to W Byte is copied to PORTB Starts new conversion Juni rotacion Toc Of Program This example demonstrates write to and read from built in EEPROM memory The program works as follows The main loop constantly reads EEPROM memory location at address 5 decimal This number is displayed on port D The same loop tests the state of three push buttons connected to port A The push buttons INCREMENT and DECREMENT have the same purpose like in example 7 increment and decreme button MEMO enables that variable to be written t button and switch off the device On the next switc nt the variable cnt which is thereafter displayed on port B The push o EEPROM memory In order to check it it Is enough to press this push h on the program displays the value of the variable on port D at the moment of writing this value was displayed on port B INCREMENT DECR EMENT MEMO GND GND http www mikroe com en books picmcubook appb 39 of 54 5 3 2009 11 36 02 AM ua 88491Dld oh GND mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples Example 12 GND BI a a a a OUS ee Rarer ne ane eat Header DUC UA Lk LAS TAS US RAS VAS TAPIA Cah Wat AS TAN UAT TAS iat tal Wal DAT Uh TAP Ah Mak Cat tah Gal Cat A UP RC Wah E ACA GRO EAE RA TAP erat zat Cah Mat AS Ral Phor c ur Ur eS Defining vVarqabi es LM proc WA AK KK AT SK LAS AC AGE CASA LA ROTAR LK
282. rollers Chapter 4 Timers d E d a a Fig 4 4 The function of the PSA bit 1 As seen the logic state of the PSA bit determines whether the prescaler is to be assigned to the timer counter or watch dog timer Additionally it is also worth mentioning When the prescaler is assigned to the timer counter any write to the TMRO register will clear the prescaler When the prescaler is assigned to watch dog timer a CLRWDT instruction will clear both the prescaler and WDT Writing to the TMRO register used as a timer will not cause the pulse counting to start immediately but with two instruction cycles delay Accordingly it is necessary to adjust the value written to the TMRO register When the microcontroller is setup in sleep mode the oscillator is turned off Overflow cannot occur since there are no pulses to count This is why the TMRO overflow interrupt cannot wake up the processor from Sleep mode When used as an external clock counter without prescaler a minimal pulse length or a pause between two pulses must be 2 Tosc 20 nS Tosc is the oscillator signal period When used as an external clock counter with prescaler a minimal pulse length or a pause between two pulses is 10nS The 8 bit prescaler register is not available to the user which means that it cannot be directly read or written to When changing the pres
283. rollers Chapter 6 Serial Communication Modules s 43 21 o ev ADDRESS Acknowledge Data Bit 1 1 z READ P Acknowledge 1 STOP bit 1 il Data Bit START bit 0 RW 0 WRITE Fig 6 21 Data Transfer Figure below shows the block diagram of the MSSP module in I C mode http www mikroe com en books picmcubook ch6 18 of 27 5 3 2009 11 33 59 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 6 Serial Communication Modules Fig 6 22 MSSP Block Diagram in IC Mode The MSSP module uses six registers for C operation Some of them are shown in figure above SSPCON SSPCON2 SSPSTAT SSPBUF SSPSR and SSPADD SSPSTAT Register SMP CKE D A P S RW UA BF Legend RAW Readable Writable bit R Readable bit 0 After reset bit is cleared Fig 6 23 SSPSTAT Register SMP Sample bit SPI master mode This bit determines input data phase e 1 Logic state is read at end of data output time and e 0 Logic state is read in the middle of data output time SPI slave mode This bit must be cleared when SPI is used in Slave mode 12 mode master or slave e 1 Slew rate control disabled for standard speed mode 100kHz and e 0 Slew rate control enabled for high speed mode 400kHz CKE Clock Edge Select bit selects synchronization mode CKP 0 e 1 Data Is transmitted on rising edge of clock pulse 0 1 and e 0 Data is transmitte
284. rs Introduction World of Microcontrollers e Instruction Decoder is a part of the electronics which recognizes program instructions and runs other circuits on the basis of that The instruction set which is different for each microcontroller family expresses the abilities of this circuit e Arithmetical Logical Unit ALU performs all mathematical and logical operations upon data e Accumulator is a SFR closely related to the operation of the ALU It is a kind of working desk used for storing all data upon which some operation should be performed addition shift move etc It also stores the results ready for use in further processing One of the SFRs called a Status Register PSW is closely related to the accumulator It shows at any given moment the status of a number stored in the accumulator number is greater or less than zero etc PSW register Instruction Accumulator Decoder Fig 0 22 Central Processor Unit CPU Bus Physically the bus consists of 8 16 or more wires There are two types of buses the address bus and the data bus The address bus consists of as many lines as necessary for memory addressing It is used to transmit the address from the CPU to the memory The data bus is as wide as the data in our case it is 8 bits or wires wide It is used to connect all circuits inside the microcontroller Serial Communication Parallel connections between the microcontroller and peripherals via input output po
285. rthermore it can also operate without elements for frequency stabilization like RC oscillator It is important to say that instructions are not executed at the rate imposed by the oscillator itself but several times slower It happens because each instruction is executed in several steps In some microcontrollers the same number of cycles is needed to execute any instruction while in others the execution time is not the same for all instructions Accordingly if the system uses quartz crystal with a frequency of 20 Mhz execution time of an instruction is not 50nS but 200 400 or 800 nS depending on the type of Microcontroller Unit MCU Power supply circuit There are two things worth attention concerning the microcontroller power supply circuit Brown out is a potentially dangerous state which occurs at the moment the microcontroller is being turned off or in situations when power supply voltage drops to the limit due to electric noise As the microcontroller consists of several circuits which have different operating voltage levels this state can cause its out of control performance In order to prevent it the microcontroller usually has built in circuit for brown out reset This circuit immediately resets the whole electronics when the voltage level drops below the limit Reset pin is usually marked as MCLR Master Clear Reset and serves for external reset of the microcontroller by applying logic zero 0 or one 1 depending on type
286. rts is the ideal solution for shorter distances up to several meters However in other cases when it is necessary to establish communication between two devices on longer distances it is not possible to use a parallel connection such a simple solution is out of question In these situations serial communication is the best solution Today most microcontrollers have built in several different systems for serial communication as a standard equipment Which of these systems will be used depends on many factors of which the most important are How many devices the microcontroller has to exchange data with How fast the data exchange has to be What is the distance between devices Is it necessary to send and receive data simultaneously One of the most important things concerning serial communication is the Protocol which http www mikroe com en books picmcubook ch0 17 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Fig 0 23 Serial communication should be strictly observed It is a set of rules which must be applied in order that the devices can correctly interpret data they mutually exchange Fortunately the microcontrollers automatically take care of this so the work of the programmer user is reduced to simple write data to be sent and read received data Baud Rate The term Baud rate is commonly used to denote the number of bits transferred pe
287. s and one output Depending on which input has a higher voltage analog value a logic zero 0 or logic one 1 digital values will appear on its output http www mikroe com en books picmcubook ch7 6 of 14 5 3 2009 11 34 24 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 7 Analog Modules OUT Fig 7 6 Analog Comparator e When the analog voltage at Vin is higher than the analog voltage at Vin the output of the comparator is a digital low level and e When the analog voltage at Vin is higher than the analog voltage at Vin the output of the comparator is a digital high level The PIC16F887 microcontroller has two such voltage comparators whose inputs are connected to I O pins RAO RA3 whereas the outputs are connected to the pins RA4 and RA5 In addition there is also a referent voltage internal source on chip itself but it will be discussed later These two circuits are under control of the bits stored in the following registers CM1CONO is in control of comparator Cl CM2CONO is in control of comparator C2 and CM2CONI is in control of comparator C2 Voltage Reference Internal Source One of two analog voltages provided on the comparator inputs is usually stable and unchangeable Because of those features it is called voltage reference Vref To generate it both external and special internal voltage source can be used After selecting voltage source Vref is derived from it by means of ladder n
288. s data Dack to PC R522 exit return Return from interrupt routine Hg NC ME D M M M M ME MM M M E M A A CM M E M C M E Ld D Me P Marn Tee SIT main banksel ANSEL Selects bank containing ANSEL Cpu ANSEL JOUET IE inputa are digiral EE ANSELH banksel movlw TRISA I http www mikroe com en books piemcubook appb 53 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples movwt TRISA movlw ley 9901010 0394610 4 movwt MESS banksel PORTA MOV W Io ctt TE OO movwt PORTA movwt ONE movilw P OVO OOO OOF movwt EOI movwt POCU B banksel IU IESIC Do TRIOC c ROOT CIA oa DS HEUS RIC ES SIDES SISTI e banksel BAUDCTL psf BAUDCILE BRGI6 banksel SEBRG movlw ul baud rate 38400 MES AZ SEI Error 0 6 movwf SPBRG cl Ede EH banksel TXSTA DEL TS TAS M Data IS 2 Dit wide bsf TXSTA TXEN Data transmission enabled DCE TXSTA ONC Asyuecwroneus mode lca TXSTA BRGH High speed Baud rate banksel RESTA En ER SIE EUROS DIOC eua 1x Ck othepuies e on poa Der Resta Rx Select mode for 8 bit data receive los RCSTA CREN Receive data enabled DCE RCSTA ADDEN No address detection ninth bit may be 7 Used usu oie mov E RESTA W MOVE RCREG W banksel ETEL DSE PIEL INC We USART Rx interrupt enabled ONS IC MECON T RETE All peripheral interrupts enabled OSE INICON CIE Global interrupt enabled end EN OMOT POr Aam Previous Chapter Table
289. s icon the program counter is positioned at the beginning of the program and simulation can start Similar to real environment the first thing that should be done is to reset the microcontroller using the option DEBUGGER gt RESET or by clicking reset icon As the consequence of this a green line is positioned at the beginning of the program and program counter PCL is cleared to zero Refer to the window Special Function Registers shown below L Special Function Registers w Project aaaress w Output INDF AAA AAA A THEO DOCDODDDU Toolbars PLL LILDIDDDDLEDL STATUS 00000000 FSR oo000000 PORTA no0000000 Disassembly Listing PORTE oooo00000 PORTC 00000000 EEPROM PORTD 00000000 See ee PORTE 00000000 File Registers PCLATH 00000000 INTCUON no0000000 Hardware Stack eum sfain PIEZ 00000000 TARL DOOOOOO D ODDDDDOD THR1L 00000000 Locals THRERiH nanobooo u Program Memory TiCON noooooo 0 Special Function Registers Watch Memory Usage Gauge Simulator Trace Simulator Logic Analyzer Apart from SFRs it is good to have an insight in File Registers A window containing them appears by clicking the VIEW http www mikroe com en books picmcubook appa 20 of 21 5 3 2009 11 35 35 AM THRZ T COM SoOPBUF SSPCON CCPRi1 CCPRLIL CCPRiH CCPICON RCSTA TERES RCREG 00000000 anonDODOD ancoDODOD aooODDOD 00000000 0000001040 00000000 DODODDDDD 00000000 00000000 mikroElektronika Free Online B
290. s is the number of available instructions The manufacturers stick to movwf TEMPI one of the two following strategies btfsc MAX3 7 goto check btfsc MAX3 6 goto opening btfsc MAX3 5 goto closing RISC Reduced Instruction Set Computer In this case the microcontroller recognizes and executes only basic operations addition subtraction copying etc All other more complicated operations are performed by combining these for example multiplication is performed by performing successive addition The constrains are obvious try by using only a few words to explain to someone how to reach the airport in some other city However there are also some great advantages First of all this language is easy to learn Besides the microcontroller is very fast so that it is not possible to see all the arithmetic acrobatics it performs The user can only see the final result of all those operations At last it is not so difficult to explain where the airport is if you use the right words For example left right kilometers etc CISC Complex Instruction Set Computer CISC is the opposite of RISC Microcontrollers designed to recognize more than 200 different instructions can do much and are very fast However one needs to understand how to take all that such a rich language offers which is not at all easy How to make the right choice Ok you are the beginner and you have made a decision to go on an adventure of working with the microcontroll
291. s or subroutines for generating pulses of arbitrary duration time measurement or counting external pulses events with almost no limitations The timer TMRO module is an 8 bit timer counter with the following features e 8 bit timer counter e 8 bit prescaler shared with Watchdog timer e Programmable internal or external clock source e Interrupt on overflow and e Programmable external clock edge selection Figure 4 1 below represents the timer TMRO schematic with all bits which determine its operation These bits are stored in the OPTION REG Register http www mikroe com en books picmcubook ch4 1 of 12 5 3 2009 11 32 57 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 4 Timers Mc i Prescaler assignment election i sat 1 assigned to WDT 0 timer PSA 4 p assigned to timer or counter Edge selection 1 raising edge 0 falling edge Ld Tocs Prescaler PS2 PS1 PSO Bits sel prescaler rate selection Counter timer Interrupt flag B bit Misit Pin RA4 TOCK signal external source Fig 4 1 Timer TMRO OPTION REG Register RIW 1 EIN RW 1 O RW RW 1 RW 1 RW t Features OPTION REG Bit name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Legend RAW Readable Writable bit 1 After reset bit is set Fig 4 2 OPTION REG Register e RBPU PORTB Pull up enable bit o Q PORTB pull up resistors are disabled and o 1 PORTB p
292. s placed in a short subroutine DELAY t is not necessary for PORTA pins since they are automatically configured as inputs after every reset Example 5 SKK ACRAS AS AAA A OR AUGE CQ SUS AISLADA OCA RAT TASTE LASER ATA A AT TAS IR SINE TAS AC RAE eR GUAE CAS KR IK AQUA ACRAS ACA ARGIS I ONE AC RA AS ARA TOS Header ESS SS ISS SS c sls US US ES si Ss usa guts us s Ls Lg sU Sg SiS UAE us TL Ls C s scs n ug LU DAS lus Ls ut nM us c US DS Dal rs usi s usus ttg sug C tes us us ttt LUDUM UNUS INR DEFINING VARIABLES KAKARAKA CG PA EATR TAS Uy aS AS Sly SU is KAAKAA ah TAS eS TAS A Ad AS TA CAE Ub is SIE Uy So sip Sy S colo el DEAD Block of variables starts at address 20h counterl Variable counterl at address 20h counter2 Variable counter2 at address 21h endc Block of variables ends ek kockckckckckckokckckockckockckockckckckckok KKK ck ck ck ck ck ck ck ck ck ck KK KARA KAR KA KK KK ck ck ck ck KKK MAIN PROGRAM aa 0x0000 ROCESS OF tho Ss oo eme state ton banksel ANSEL Selects bank containing register ANSEL exisse ANSEL Clears registers ANSEL and ANSELH to ean ANSELH Da elata sl aligromiee eis ODE IE UTE banksel JD EIS c5elects bank containing register TRISB esa MESSIS 7 All port B pins are configured as outputs movlw EDI DNE http www mikroe com en books picmcubook appb 27 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples Pin RATS SIS Selects
293. s to its input One such circuit is built in the microcontroller and its division rate can be changed from within the program It is used when it is necessary to measure longer periods of time One prescaler is usually shared by timer and watch dog timer which means that it cannot be used by both of them simultaneously http www mikroe com en books picmcubook ch0 22 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers Timer register 1MHz AMHz 1 1 1 Elapsed time aa ney tus Fig 0 29 Using prescaler in timer operating Using the interrupt in timer operation If the timer register consists of 8 bits the largest number that can be written to it is 255 for 16 bit registers it is the number 65 535 If this number is exceeded the timer will be automatically reset and counting will start from zero again This condition is called overflow If enabled from within the program such overflow can cause an interrupt which gives completely new possibilities For example the state of registers used for counting seconds minutes or days can be changed in an interrupt routine The whole process except interrupt routine is automatically performed in the background which enables the main circuits of the microcontroller to perform other operations http www mikroe com en books picmcubook ch0 23 of 30 5 3 2009 11 28 39 AM mikroEle
294. splay which is indeed the most commonly used J I E VW MEE MUA n B LETILILLDLLLD LI Display contrast depends on the power supply voltage and whether messages are displayed in one or two lines For this reason varying voltage 0 Vdd is applied on the pin marked as Vee Trimmer potentiometer is usually used for that purpose Some LCD displays have built in backlight blue or green diodes When used during operation a current limiting resistor should be serially connected to one of the pins for backlight similar to LED diodes http www mikroe com en books picmcubook appb 12 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples i 5V Contrast LED backlights FREERERRERERRER If there are no characters displayed or if all of them are dimmed when the display is switched on the first thing that should be done is to check the potentiometer for contrast adjustment Is it properly adjusted The same applies if the mode of operation has been changed writing in one or two lines LCD Memory LCD display contains three memory blocks e DDRAM Display Data RAM e CGRAM Character Generator RAM and e CGROM Character Generator ROM DDRAM Memory DDRAM memory is used for storing characters that should be displayed The size of this memory is sufficient for storing 80 characters
295. st significant bit of the result has occurred OPTION REG Register RBPU INTEDG Tocs Tose PSA PS2 Ps1 PSO Fig 2 2 The OPTION REG register contains various control bits to configure TimerO WDT prescaler timer TMRO external interrupt and pull ups on PORTB http www mikroe com en books picmcubook ch2 2 of 12 5 3 2009 11 32 08 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 2 Core SFRs E e RBPU Port B Pull up Enable bit a ISC o l PortB pull ups are disabled REPU o 0 PortB pull ups are enabled 10 Fig 2 3 e INTEDG Interrupt Edge Select bit E o 1 Interrupt on rising edge of RBO INT pin B o 0 Interrupt on falling edge of RBO INT pin m Fin RAM anar e TOCS TMRO Clock Source Select bit o l Transition on TOCKI pin o 0 Internal instruction cycle clock Fosc 4 Fig 2 5 Pin RAATOCKLCTOUT e TOSE TMRO Source Edge Select bit selects pulse edge rising or falling counted by E the timer TMRO through the RA4 TOCKI pin o 1 Increment on high to low transition on TOCKI pin o 0 Increment on low to high transition on TOCKI pin LT Pin RAAT OCR IOUT OPTION REG e PSA Prescaler Assignment bit assigns prescaler only one exists to the timer or EE watchdog timer Psa ME o 1 Prescaler is assigned to the WDT m T o 0 Prescaler is assigned to the TMRO 0 i Prescaler E Fig 2 7 Tn BS tro osc
296. st the code prior to burning it to the MCU Loop Button PORTA 0 0 ncrement button PORTA 1 0 Decrement http www mikroe com en books picmcubook appc 1 of 7 5 3 2009 11 36 25 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix C Development Systems Gono I eSI Increment Inci emit MOV E ea Ww movwft PORTB gotro Loja Decrement decf cnt f Ove ene NU Inovwi PORTE To enable the compiler to perform its task successfully it is necessary that a document containing this program has the extension asm in its name for example Program asm When a specialized program MPLAB is used this extension will be automatically added If any other program for text processing Notepad is used then the document should be saved and renamed For example Program txt gt Program asm Note for lazy ones skip this procedure open a new asm document in MPLAB and simply copy paste the text of the program written in assembly language COMPILING PROGRAM The microcontroller does not understand assembly language as such This is why it is necessary to compile the program into machine language It is more than simple when using a specialized program MPLAB because a compiler is part of the software ust one click on the appropriate icon solves the problem and a new document with hex extension pops out It is actually the same program but compiled into computer language which the microcontroller perfectly understands Such doc
297. ster This circuit also allows the user to trigger an external event when a predetermined amount of time has expired PWM Pulse Width Modulation can generate signals of varying frequency and duty cycle The PIC16F887 microcontroller has two such modules CCP1 and CCP2 Both of them are identical in normal mode with the exception of the Enhanced PWM features available on CCP1 only This Fitter this Ly describes the CCP1 module in detail Concerning CCP2 only the features distinguishing it from CCP1 will be covered Complicated All this is only a simplified explanation on their operation Everything is much more complicated in practice because these modules can operate in many different modes Try to analyze their operation on the basis of the tables describing bit functions If you use any CCP module first select the mode you need analyze the appropriate figure and then start changing bits of the registers or else CCP1 Module A central part of this circuit is a 16 bit register CCPR1 which consists of the CCPRIL and CCPRIH registers It is used for capturing or comparing with binary number stored in the timer register TMR1 TMR1H and TMRI1L http www mikroe com en books picmcubook ch5 1 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 5 CCP Modules Module CCPR1 Registers 2s l Register CCPR1H Register CCPR1L ug M bit 15 bit 8 bit 7 bit 0 Fig
298. struction execution FSR 0xC2 Register at address FSR contains the value OxAA After In e le toa PoR O Register at address FSR contains the value Ose SS DECF Decrement f http www mikroe com en books picmcubook ch9 15 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set Syntax label DECF f d Description Decrement register f by one If d w or d 0 the result is stored in the W register If d f ord 1 the result is stored in register f Operation f 1 gt d Operand 0 x f lt 127 d 0 1 Status affected Z Number of cycles 1 EXAMPLE 1 Rabel i DECE BG Suus cec eO PREC NOl DL Abeer gneuuciasoDp REG 0x00 Z 1 EXAMPLE 2 label DECF REG w Before instruction execution REG 0x13 W x Z 0 Ameer task wien tom REE US W 0x12 2 0 DECFSZ Decrement f Skip if 0 Syntax label DECFSZ f d Description Decrement register f by one If d w or d 0 the result is stored in the W http www mikroe com en books picmcubook ch9 16 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set register If d f ord 1 the result is stored in register f If the result is 0 then a NOP is executed instead making this a two cycle instruction Operation f 1 gt d Operand 0 x f lt 127 d 0 1 Status affected Number of cycles 1 or 2 depending on th
299. t C2OUT gate is low 0 TMRIGE Timerl Gate Enable bit determines whether the pin T1G or comparator C2 output C2OUT gate will be active or not This bit is functional only in the event that the timer TMRI is on bit TMR1ON 1 Otherwise this bit is ignored e l Timer TMRI is on only if timer 1 gate is not active and e 0 Gate does not affect the timer TMRI http www mikroe com en books piemcubook ch4 9 of 12 5 3 2009 11 32 57 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 4 Timers T1CKPS1 TICKPSO Timer1 Input Clock Prescale Select bits determine the rate of the prescaler assigned to the timer TMRI T1CKPS1 T1CKPSO Prescaler Rate 0 0 etl 0 1 pu 1 0 1 4 1 1 1 8 Table 4 2 Prescaler Rate T1OSCEN LP Oscillator Enable Control bit e 1 LP oscillator is enabled for timer TMR1 clock oscillator with low power consumption and frequency 32 768 kHz and e O LP oscillator is off T1SYNC Timer1 External Clock Input Synchronization Control bit enables synchronization of the LP oscillator input or T1CKI pin input with the microcontroller internal clock When counting pulses from the local clock source bit TMR1CS 0 this bit is ignored e 1 Do not synchronize external clock input and e 0 Synchronize external clock input TMRI1CS Timer TMR1 Clock Source Select bit e 1 Counts pulses on the T1CKI pin on the rising edge 0 1 and e 0 Counts pulses of the internal clock of microcontroll
300. t refers to transmission of PWM signal to the output pins Why is it so important Because the microcontrollers are more frequently used in control systems for electric motors These devices are not described here but if you ever have had a chance to work on development of similar devices you will recognize elements which until quite recently have been used as external ones Normally all these elements are now integrated into the microcontroller and can operate in several different modes Single Output PWM Mode This mode is enabled only in the event that the P1M1 and P1MO bits of the CCP1CON register are cleared In this case there is only one PWM signal which can be simultaneously available on a maximum of four different output pins Besides the PWM signal may appear in basic or inverted waveform Signal distribution is determined by the bits of the PSTRCON register while it s polarity is determined by the CCP1M1 and CCP1MO bits of the CCP1CON register When an inverted output is in use the pins are low active and pulses having the same waveform are always generated in pairs on the P1A and P1C pins and P1B and P1D pins respectively Pin ELM RC2 P1A EB ix Pin RD5 P1B P Pin i RD6 P1C Uy Pin Ei RD7 P1D INPUT OUTPUT Fig 5 11 Single Output PWM Mode Half Bridge Mode http www mikroe com en books picmcubook ch5 10 of 15 5 3 2009 11 33 21 AM mikroElektronika Free Online Book PIC Microcontrollers
301. t s it The microcontroller is programmed and everything is ready for operation If you are not satisfied make some changes in the program and repeat the procedure Until when Until you feel satisfied Development systems A device which in testing program phase can simulate any environment is called a development system Apart from the programmer the power supply unit and the microcontroller s socket the development system contains elements for input pin activation and output pin monitoring The simplest version has every pin connected to one push button and one LED as well A high quality version has LED displays LCD displays temperature sensors and all other elements which the target device can be supplied with These peripherals could be connected to the MCU via miniature jumpers In this way the whole program may be tested in practice during its development stage because the microcontroller does not know or care whether its input is activated by a push button or a sensor built in a real machine http www mikroe com en books piemcubook appe 6 of 7 5 3 2009 11 36 25 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix C Development Systems Development system EasyPIC5 Previous Chapter Table of Contents http www mikroe com en books piemcubook appe 7 of 7 5 3 2009 11 36 25 AM
302. ted The size of a program that can be written depends on the size of this memory Today s microcontrollers commonly use 16 bit addressing which means that they are able to address up to 64 Kb of memory i e 65535 locations As a novice your program will rarely exceed the limit of several hundred instructions There are several types of ROM Masked ROM Microcontrollers containing this ROM are reserved for the great manufacturers Program is loaded into the chip by the manufacturer In case of large scale manufacture the price is very low Forget it One Time Programmable ROM OTP ROM If the microcontroller contains this memory you can download a program into this memory but the process of program downloading is a one way ticket meaning that it can be done only once If an error is detected after downloading the only thing you can do is to download the corrected program to another chip http www mikroe com en books picmcubook ch0 15 of 30 5 3 2009 11 28 39 AM mikroElektronika Free Online Book PIC Microcontrollers Introduction World of Microcontrollers UV Erasable Programmable ROM UV EPROM Both the manufacturing process and characteristics of this memory are completely identical to OTP ROM However the package of this microcontroller has a recognizable window on the upper side It enables the surface of the silicon chip inside to be lit by an UV lamp which effectively erases and program from the ROM Installation of this
303. tes its purpose During compiling it enables the assembler to use data contained in another file on a computer hard disc For example include sS foo dme CBLOCK and ENDC directives All variables their names and addresses that will be used in a program must be defined at the beginning of the program Because of this it is not necessary to specify the address of each specified variable later in the program Instead it is enough to specify the address of the first one by using directive CBLOCK and list all others afterwards The compiler automatically assigns these variables the corresponding addresses as per the order they are listed Lastly the directive ENDC indicates the end of the list of variables PRECIO 0x20 SL JUANES IP address 0x20 RE LE address 0x21 STOP address 0x22 LEET address Ux253 http www mikroe com en books piemcubook appa 4 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller RIGHT gt address 0x24 ENDC IF ENDIF and ELSE directives These directives are used to create so called conditional blocks in a program Each of these blocks starts with the directive IF and ends with the directive ENDIF or ELSE A statement or a symbol in parentheses following the directive IF represents a condition which determines which part of the program is to be compiled e f the statement is correct or the value of a symbol is equal to one progra
304. truction followed by a constant address increment Bit 12 Biti1 Bit 10 Bits Bra Bit Bit A Bit5 Bits Bit3 Bit2 Bit Bit O Bit 4 Bit 3 Bit 2 Bit 1 Bit O M Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit O PCLATH PCL Fig 2 16 PCL and PCLATH Registers If the program counter is changed in software then there are several things that should be kept in mind in order to avoid problems e Eight lower bits the low byte come from the PCL register which is readable and writable whereas five upper bits coming from the PCLATH register are writable only e he PCLATH register is cleared on any reset e In assembly language the value of the program counter is marked with PCL but it obviously refers to 8 lower bits only One should take care when using the ADDWF PCL instruction This is a jump instruction which specifies the target location by adding some number to the current address It is often used when jumping into a look up table or program branch table to read them A problem arises if the current address is such that addition causes change on some bit belonging to the higher byte of the PCLATH register Do you see what is going on Executing any instruction upon the PCL register simultaneously causes the Prog ram Counter bits to be replaced by the contents of the PCLATH register However the PCL register has access to only 8 lower bits of the instruction result and the following jump will be completely incorrect The
305. tup is preparing the InstallS Field Wizard which val quide you through the program setup process Please Checking Operating System Version CLLILILLILLIILIILLIL Something is going on The picture coming up indicates that the process of installation has just started MPLAB Toots v7 60 El O contains the word Welcome Need MPLAB Tools 7 60 Installation Actually the program reminds you to close all active programs in order to not interfere with the installation process Next of course Welcome to the MPLAB Tool Inetallanion Program IE is slrangle recommended that pou follow these drechons 1 Quit all applications before instaling this product 2 Urinstal all peeious MPLAB Took 6 4 versions 3 Disable arg ar rvrus soflwere running on the machine 4 When using Ihe WEB Install use the Browser inbemet Ophons lo Delete Fides from the ritesnelt Temp Director MPLAB Tools v7 60 tj Prior to continue you have to accept the MPLAB software License Agreement br A v A CHIP eee conditions Select the option accept and click IMPORTANT YOU MUST ACCEPT THE TERMS AND CONDITIONS OF THIS LICENSE AGREEMENT TO RECEIVE A LICENSE FOR THE ACCOMPANYING TERMS CLICK I DO HOT ACCEPT OR DO HOT OFEN THIS PACKAGE DOWNLOAD OR INSTALL THES SOFTWARE MPLAB IDE LICENSE P accept the teem of the licenze agreement Pint C I dono accept th
306. uU E M D E E http www mikroe com en books picmcubook appb 52 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples TOTS part or the program 1s executed vn interrupt routine banksel PIET PECSS PIER TE goto TSR NOC E452 1 dETQUE banksel PIE1 ici SIG EUR ERE call ROO D QE SNC SENOR C28 2 ac MOVE pclath temp w movwft IPSE AI CECI Sis Given its OT eu Se MONE status_ temp w movwf STATUS STATUS As given Tte Original valus swapf w_temp f swapf w temp w W is given its original value retfie Ret cn rom Interrupt 6outrne Mg M UM MEM x LU E C DK UV ES AI TRO 7 Check it error has occurred banksel RCSTA MONE RCSTA w movwf RS232temp lon gat cre NS temo EERR goto EA o IDEEN perce RS232temp OERR SOTO EXA ao OI goro DELS ZT ge PE CIO me AS LE SS FERR Cir ROSTA CREN lO clear FERR Dil receiver as first switched off and on afterwards nop Delay nop bsf RSS IAN movf RCREG w Reads receive register and clears FERR bit DSi Dod A 0 owt eres TED on UART error Indicator mov f POr A wW movwf PORTA goro SiS O ROA O eene bliss PEE RESIT CREN Clears OERR bit nop Delay Io psf ROSAS REN mov E RCREG w Reads receive register and clears FERR bit BSE Doni M 1l Scc SES BC UARI error ciem mov E POTE Ww movwf PORTA JORG RS232_ex1t R2 57 ne Pro o OnE I ORE RCREG W Reads received data movwf RIE E movwf PORTE movwt TXREG send
307. ubroutine First the address of the next instruction to execute is pushed onto the stack It is the PC 1 address Afterwards the subroutine address is written to the program counter Operation PC 1 Top Of Stack TOS k PC 10 0 PCLATH 4 3 gt PC 12 11 Operand 0 x k x 2047 Flag Status affected 2 EXAMPLE LAB OI CALL LAB 02 Call subroutine 555992 LAB_02 Before instruction execution PC address LAB 01 TOO ECOD or Uo EN x After instruction PC address LAB 02 IOS EOP Or Steck uet TAR OI CLRF Clear f Syntax label CLRF f Description The content of register f is cleared and the Z flag of the STATUS register is set http www mikroe com en books picmcubook ch9 12 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set Operation 0 gt f Operand 0 x f lt 127 Status affected Z Number of cycles 1 EXAMPLE 1 ase EEE E SUL E Bertone Lnc UCE IOL Cxe Uc ey s ARTES Ig gs CER tek ee ID MEE Ob WERT SES 00 Z3 E EXAMPLE 2 Before instruction execution FSR 0xC2 Register at address OxC2 contains the value QR PUES US Sere GI EAS Register at address OxC2 contains the value 0x00 Z 1 CLRW Clear W Syntax label CLRW Description Register W is cleared and the Z flag of the STATUS register is set Operation 0 gt W Operand Status affected Z Number of cycles 1 http www mikroe com en
308. umentation is commonly named hex code and seemingly represents a meaningless sequence of numbers in hexadecimal numerical system 050100109010 201 02d 0 0130 919 810 Sei 1 Sie IOQUPPBZIOIZOLODG ORI ATA 7 2D40 SMO MOO GS 2 Sto EAR C IGE cy 2 0 A585FEA2569ADO9OEODSPEDOPFAD APFODDOOOOO0O00IFFZ255AFED5S89EA PSI Sr cupio 2 9 99 LAZO SADO DASS SIDO TE SIDE pega DAFO6DDOOO00001FFZ55AFEDSFED 2 MDA SUID CONE a Sl 2 SCL A Th Hoven aap DD DDAFED589EAF3698ESEBZ25BA585 FEA2569AD96DAC5D9D9FADAFOD DOOQ000001FF255AFEDSFEDOFADA EC DPOOOPT S TORERE 2 0 IL 3 2 a ECD MOOD EDO PASS SEAS o EB DBA585FEAZ2569AD96DAFODDOOO JOLIE DVN DUO ETE EU SSA ADAFO6DDOOO000001FFZ255AFEDSFE D9FA http www mikroe com en books picmcubook appc 2 of 7 5 3 2009 11 36 25 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix C Development Systems In case other software for program writing in assembly language is used special software for compiling the program must be installed and used as follows set up the compiler open the document with asm extension and compile The result is the same a new document with hex extension The only problem you have now is that it is stored in your PC PROGRAMMING A MICROCONTROLLER To enable hex code transmission to the microcontroller it is necessary to provide a cable for serial communication and a special device called programmer with appropriate software There are several ways to do it A lot
309. us temp w movwf STATUS swapf w_temp f Swapft w temp w oso INGTON GTE retfie 5 Selects bank containing PORTB Increments register PORTB by 1 Selects bank containing INTCON tiles Interrupt ilog TMROTE jo ys TS irene original Content STATUS as Given its original Content Wais giyen Ite Origina content Global interrupt enabled Return from interrupt routine KK KK KK KK KKK KK KK KK KK KK KKK KK RK KK KK KK KKK KKK KKK KKK KKK KKK KKK KKK MAIN PROGRAM Malta banksel ANSEL eco ANSEL CHEESE ANSELH banksel TRICE cl SIS banksel OBTLTONARES Dei OPTION FEC TOCS DET ORPTTONTREG Te ey E psf OPTTON TREG PSO Dor OPTION SIS G c Pol BoT IPSIS NS IS Eo banksel UNTCON sr ih GE Oh PMROTE DSi INTCON GIE banksel PORTE elr r PORTE E JEGYXOJS Joro Koop end Example 5 Using subroutine using push buttons In the previous examples the microcontroller executes the program without being influenced in any way its surrounding In Suscipe d Ete MAN pogram Bank containing register ANSEL Clears registers ANSEL and ANSELH All pins are digital Selects bank containing register TRISB PSOne B PINS are Conrigured aS BET AS Bank containing register OPTION REG IMEO Scones pulses tronos claro Prescaler is assign to timer TMRO Prescaler rate is 1 256 Bank containing register INTCON TMRO interrupt overflow enabled Global interrupt enabled Bank Compe LONG registrer LOR is Clears port B Remain
310. user should first test it in the simulator prior to executing it in a real environment Unfortunately this is one of many good things being overlooked by the programmer because of its character as such and the lack of high quality simulators as well 1 9 None Clear Memory 1 MPLAB ICD 2 2 MPLAB ICE ULL 3 MPLAB SIM 4 MPLAB ICE 2000 5 REAL ICE 6 PICKit 2 http www mikroe com en books picmcubook appa 19 of 21 5 3 2009 11 35 35 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix A Programming a Microcontroller Simulator is activated by clicking on DEBUGGER SELECT TOOL MPLAB SIM as shown in figure As a result several icons related to the simulator only appear Their meanings are as follows Starts program execution at full speed In this example the simulator executes the program at full normal speed D until it is halted by clicking the icon below DD Starts program execution at optional speed The speed of execution is set in dialog Debugger Settings Animation Realtime Updates Pauses program execution Program can continue executing step by step or at full speed again Starts step by step program execution Instructions are executed one after another Furthermore clicking on this icon enables you to step into subroutines and macros gp This icon has the same function as the previous one except it has the ability to step into subroutines Ely Resets microcontroller By clicking thi
311. w mikroe com en books picmcubook ch9 10 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set Number of cycles 1 or 2 depending on bit b EXAMPLE NE 0d eee usce d 2 wies bie 1 om EG ZA vta Sos wee ta Dire ER TABS eu J umo here if bit 0 Before instruction execution The program counter was at address LAB OI e T e hole Saf EL Lof REG Ie Cleaned Pror am Counter Points TO address LAB OS SS REG ook TOUS o a o el os oaa ee LAB 02 BTFSS Bit test f Skip if Set Syntax label BTFSSf b Description If bit b of register f is 1 the next instruction is discarded and a NOP is executed instead making this a two cycle instruction Operation Discard the next instruction if f b 21 Operand 0 lt f lt 127 0x bx 7 Status affected Number of cycles 1 or 2 depending on bit b EXAMPLE IPSOM PRESS IDEO OR CIL SER oe e ome AZ ute aes okip thio I o e TABS e Jump here if bit 1 Before instruction execution The program counter was at address http www mikroe com en books picmcubook ch9 11 of 35 5 3 2009 11 35 12 AM mikroElektronika Free Online Book PIC Microcontrollers Chapter 9 Instruction Set LAB 01 Are o Eon A o jme als eMe ie amo aa eoa E Cice SE celo ss LAB 0 Sai Die oe core REG Te e Me re pio Sie O ie Pone to addres LAB 02 CALL Calls Subroutine Syntax label CALL k Description Calls s
312. wf ARG2L W w w ARG2L movwf RESL RESL w DELEC STATUS C Io che result greater than 2995 eE RESH f If greater increment RESH by one mov E ARG1H w w ARG1H addwf ARG2H w w wtARG2 addwft RECH E RESH w return Return from subroutine end 7 Sno OTI OON In Short The main difference between macros and subroutines is that macro is after compiling replaced by its code enables the programmer to type less It may also have arguments while subroutine uses less memory but does not have arguments MPLAB MPLAB is a Windows program package which enables easy program writing as well as easy program development It is best to describe it as development environment for a standard program language designed for PC programming MPLAB technically simplifies some operations consisting of a lot of parameters which until the IDE environment appeared were executed from the command line However tastes are different and there are some programmers who prefer standard editors and command line compilers Every program written in MPLAB is clear but there are also help documentation j ust in case INSTALLING MPLAB MPLAB consists of several parts e he program which sorts data files of the same project into one group Project Manager e program for text generating and processing Text Editor and e Simulator used to simulate the operation of a program loaded into the microcontroller Besides there are also built in programmers such as PlCStart P
313. y as well This frequency is normally labelled on the microcontroller package Apart from the crystal capacitors C1 and C2 must be also connected as per the schematic below Their capacitance is not of great importance therefore the values provided in the table should be considered as a recommendation rather than a strict rule Mode Frequency C1 C2 Lp 32KHz 33pF 200KHz 15pF 200 KHz 47 68 pF XT 1 MHz 15pF 4 MHz 15pF 4MHz _ 15pF HS 8 MHz 15 33 pF 20MHz 15 33 pF Ceramic resonator is cheaper but very similar to quartz by its function and the way of operating This is why the schematics illustrating their connection to the microcontroller are identical However the capacitor value is a bit different in this case due to different electric features Refer to the table Ceramic resonator Mode Frequency C1 C2 AT 2 MHz 15 68 pF 16 MHz 10 22 pF http www mikroe com en books picmcubook appb 3 of 54 5 3 2009 11 36 02 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix B Examples These oscillators are used when it is not necessary to have extremely precise frequency RC oscillator If the operating frequency is not of importance then there is no need for additional expensive components for stabilization Instead a simple RC network as shown in the figure below will be enough Since only the input of the local oscillator input is in use here the clock
314. ys operate as expected Namely by pressing the push button the number on port B is not always incremented by 1 Mechanical push buttons make several short successive contacts when they have been activated You guess the microcontroller registers and counts all that vec 204 200 0 1 2 3 INCREMENT je 8839L Old 8MHz 2x20 30pF e GND GND There are several ways to solve this problem This program uses program delay known as debounce Basically it is a simple procedure Upon input change detection button press a short program delay is provided and the program waits for another change button release Only after this the program comes to a conclusion that the button is activated In this very case the push button is tested by means of macro called button Besides this macro contains a program delay which is provided by means of another macro pausems The main program is relatively simple and enables the variable cnt to be incremented and decremented by using two push buttons This variable is thereafter copied to port B and affects the LED logic one 1 turns LED diode on while logic zero 0 turns LED diode off Example 7 Ck kck ck kk sk sk kk ke ke RRA Header X XX dkkookokck kk kk KKK KK eK KKK KK KK KK KKK KKK KKK KK KKK KKK KKK KK KKK ck ck DEFINING VARIABLES culto els 0x20 Block of variables starts at address 20hex http www mikroe com en boo
315. ztarapt actor SS ua gu UT ET m krtien PORTA U 0 Forera Dira PORTA 1 0 Tman i ets Laep a E ee E vaca inzt cur f mont cor mrt POETDB 7 oe bg ES mari det cat f aot cab imr d PORTH geto Laep AA aceso ss 00 ee la ea ar e cm en foe en os ve im FF OFF FF FF FF FF OTF FF FF FF FF Lo T I EEE aa 13 a4 rr pi rr rr ii rr rr a rr rr Fr rr rr ii rr rr pi rr rr pi rr rr i nr rr DE Fr rr FF 3 zm E mu uu LE 5 E 13 aac af 333 143333 aa m E TS uH T a EE 33 fs T Hu 4 3 EE 3 3 Ti T bs ERA ERA 3 1432323 3 y E EH a LE EE bar ER Dd M Boa OK You have written a program and tested it with the simulator The program did not reports any error during the compiling process It seems that everything is under control http www mikroe com en books picmcubook appc 4 of 7 5 3 2009 11 36 25 AM mikroElektronika Free Online Book PIC Microcontrollers Appendix C Development Systems MPASM v5 11 Assembling PRIMER1 A5M 100 Errors Warnings Reported suppressed Messages Reported 3 Suppressed Lines Assembled 253 The program is written and successfully compiled All that s left isto dump the program to the microcontroller For this purpose it is necessary to have software that takes the written and compile

Download Pdf Manuals

image

Related Search

Related Contents

Control Line Motor Timer Manual - E  FIREMON Database User Manual  - File Delivery Service  Samsung GW71E Instrukcja obsługi  Liners qualité Celsius & Premium  Page 1 Page 2 賊” “ 「 清量を ー0% 含みます。添付の培地添加剤を  Targus Drifter 17"  ifd air cleaner service manual  FT Pierrenet - Piscines & Bains  Procedimentos para utilização e manutenção do destilador de água  

Copyright © All rights reserved.
Failed to retrieve file