Learn To Use state machines to create Solutions to comple' problems. %ow to use state machines to solve problems inclu(ing full) (ebugge( e'amples one is co(ing a scrolling menu on a stan(ar( c+ (ispla). & earn 8o 2se state 0achines 8o 0a'imum 9ffect. & egal.
Learn To Use state machines to create Solutions to comple' problems. %ow to use state machines to solve problems inclu(ing full) (ebugge( e'amples one is co(ing a scrolling menu on a stan(ar( c+ (ispla). & earn 8o 2se state 0achines 8o 0a'imum 9ffect. & egal.
Learn To Use state machines to create Solutions to comple' problems. %ow to use state machines to solve problems inclu(ing full) (ebugge( e'amples one is co(ing a scrolling menu on a stan(ar( c+ (ispla). & earn 8o 2se state 0achines 8o 0a'imum 9ffect. & egal.
Using Interrupts http://www.best-microcontroller-projects.com Page 1 of 83. Effective PIC Interrupts 1 Other Resources 1.1 PIC C Course A Complete C course for PIC micros in 11 parts. CIC! the image abo"e. #r Clic$ %ere http://www.best-microcontroller-projects.com Page & of 83. Effective PIC Interrupts 1.2 Learn To Use state Machines To Maximum Effect. %ow to use state machines to create Solutions to comple' problems inclu(ing full) (ebugge( e'amples * one is co(ing a scrolling menu on a stan(ar( C+ (ispla). CIC! the Image Abo"e #r Clic$ %ere. http://www.best-microcontroller-projects.com Page 3 of 83. Effective PIC Interrupts How to Make Projects Fly Using Interrupts ,1.-1 .) /ohn 0ain Cop)right 1 /ohn 0ain &--8 Understanding How and Why Interrupts work lets You Optii!e the for any processor"
2sing the techni#ues in this (ocument )ou can learn how to manage an( optimi3e interrupts as well as use pro"i(e( C templates that ma$es using interrupts eas). History : V1.01 Nov 08 : Updated for 18F interrupts. Copyright 2008 John Main http://www.best-microcontroller-projects.com All rights reser"e(. 4o part of this e.oo$ ma) be repro(uce(5 store( in a retrie"al s)stem or transmitte( in an) form or b) an) means electronic5 mechanical5 photocop)ing5 recor(ing or otherwise without e'press written5 (ate( an( signe( permission from the author /ohn 0ain. http://www.best-microcontroller-projects.com Page 6 of 83. Effective PIC Interrupts Table of Contents 1 #ther 7esources........................................................................ ..............& 1.1 PIC C Course........................................... .........................................& 1.& earn 8o 2se state 0achines 8o 0a'imum 9ffect....................................3 & egal........................................................................ .............................8 3 Intro(uction......................................................................................... ...: 3.1 ;rom Polling 8o Interrupts....................................................... ............: 3.& 7eal 8ime 9"ents................................................... ..........................1- 3.3 Achie"ing 0ore 2sing Interrupts........................................................ .11 3.6 <h) Interrupts are 9ssential for Critical Inputs.................................. ...11 3.= Power >a"ing................................................. .................................1& 6 Interrupts.............................................................................. ...............13 6.1 8he Interrupt 0o(ule.................................................................. ......13 6.& Polling (isa("antages .................................. ....................................13 6.3 8he Power of Interrupts........................................ ............................16 6.6 %ow +oes An Interrupt Affect 8he 0ain Co(e?................................... ...1= 6.= %ow to 9nsure Interrupts an( 0ain co(e <or$.....................................1@ 6.@ A"oi(ing Acci(ental Co(e Increase In the I>7......................................1@ 6.@.1 +ata 8)pes............................................................................ ....1A 6.@.& %i((en ibrar) Co(e................................................ ...................1A = %ow Interrupts <or$........................................................ ......................1A =.1 Instruction c)cle.................................................... ..........................1A @ Interrupt >er"ice 7outine BI>7C............................................................. ...18 @.1 I>7 : Interrupt >er"ice 7outine........................................ ..................1: @.& Interrupt ,ector...................................................................... .........1: @.3 Interrupt Co(e..................................... ...........................................&- @.6 Conte't >witching........................................................... .................&1 @.6.1 >a"ing 8he Current >tate........................................ ....................&1 @.6.& >a"ing the Program Counter............................................ ............&1 @.6.3 .an$ Conte't >a"ing........................................ ..........................&1 A Co(ing PIC Interrupts................................................................ .............&1 A.1 PIC Interrupt 7egisters.......................................... ...........................&& A.& PI7 Peripheral Interrupt 7egister >tate B;lagC................................... ....&3 A.3 Peripheral Interrupt 9nable PI9 B9nableC.............................................. &3 A.3.1 Interrupt 0as$s.................................................. .......................&3 A.6 I48C#4 * #riginal Interrupt Control 7egister.......................................&6 A.= Dlobal An( Peripheral Interrupt 9nable.................................... ............&6 A.=.1 DI9............................................................................. .............&6 A.=.& P9I9....................................................................................... ..&= A.@ 2sing the Interrupt ;lag 7egisters......................................................&= A.A Interrupt ;low +iagram................................................................ .....&A http://www.best-microcontroller-projects.com Page = of 83. Effective PIC Interrupts A.8 Interrupt +esign +ecisions................................ ................................&8 A.8.1 Processing / Interrupt 8ime Anal)sis.............................................&: A.8.& 8hree Interrupt +esign >olutions .................................... .............3- A.8.3 9ffect of using a &-0%3 cloc$..................................................... ..3- 8 +esign techniEues.............................................................................. ....31 8.1 2sing ;AD> to communicate from I>7 to main Program ......................31 8.& FInterrupt Casca(eFG.......................................................... ..............3& 8.3 0easuring the I>7 time.............................. ......................................36 8.3.1 +irect Pin 0onitoring....................................... ...........................36 8.3.& >imulating Interrupts.................................................................36 8.3.&.1 2sing H(efine 0acros............................... ............................3= 8.3.3 2sing A 8imer.......................................................................... ..3= 8.3.3.1 ,iewing the 8imer ,alue..................................................... ...3@ : An 9rror Iou 0ust A"oi(.............................. ...........................................3A 1- 18; >eries Interrupts................................................................... .........3: 1-.1 %igh or ow Priorit) Interrupts: 7eason for 2sage...............................3: 1-.& %ar(ware for Prioriti3e( Interrupts.............................................. ......3: 1-.3 Prioriti3e( Interrupt 0echanism.............................................. ..........6- 1-.6 Priorit) 9nable Control .it Bbac$war(s compatibilit)C...........................61 1-.= 18; >eries 7egisters.................................................. .....................6& 1-.@ 18; Conte't >a"ing............................................. ...........................6& 1-.@.1 ;ast 7egister >tac$....................................................... ............63 1-.@.1.1 2sing the ;ast 7egister >tac$ for normal function calls.............63 11 9'amples.............................................................................. ..............63 11.1 %ar(ware J >oftware ......................................................... ............63 11.1.1 %ar(ware................................................................ ................63 11.1.& >erial port configuration............................................ ................66 11.1.3 1@;88 %ar(ware +iagram.......................................... ................6= 11.1.6 18;&==- %ar(ware +iagram......................................................6@ 11.1.= >oftware +ownloa(s.......................................... .......................6@ 11.1.=.1 C Compiler (ownloa(.................................. ........................6@ 11.1.=.& ICP7#D........................................... .................................6@ 11.1.=.3 <inPic Bfor the 18;&==- an( man) othersC............................6A 11.& Interrupt 8emplate........................................... ..............................6A 11.&.1 Interrupt 8emplate Co(e Action.............................. ....................68 11.&.& Interrupt 8emplate C Co(e....................................................... ..68 11.3 1@; %eartbeat 8imer................................................................... ....=1 11.3.1 1@; %eartbeat 8imer Co(e Action...............................................=1 11.3.& 1@; %eart .eat 8imer C Co(e....................................... ..............=1 11.6 8ransmit Interrupts Bno co(e but some important informationC.............=@ 11.= 7>&3& Interrupt 7eception..............................................................=A 11.=.1 1@; 7>&3& Interrupt 7eception Co(e Action.................................=A http://www.best-microcontroller-projects.com Page @ of 83. Effective PIC Interrupts 11.=.& 1@; 7>&3& Interrupt 7eception C Co(e................................ ........=A 11.@ >imple ;lag 9'ample............................... .......................................@& 11.@.1 1@; >imple ;lag Interrupt Co(e Action........................................@& 11.@.& 1@; >imple ;lag Interrupt C Co(e...............................................@& 11.A Interrupt >imulation using 0acros....................................................@@ 11.A.1 1@; Interrupt >imulation Co(e Action..........................................@@ 11.A.& 1@; Interrupt >imulation C Co(e................................................@8 11.8 18; Interrupt +ri"en .lin$ing 9+ 9'ample........................................A1 11.8.1 18; Interrupt +ri"en .lin$ing 9+ Co(e Action.............................A1 11.8.& 18; Interrupt +ri"en .lin$ing 9+ C Co(e....................................A& 11.: 18; Prioriti3e( Interrupt 9'ample.....................................................A= 11.:.1 18; Prioriti3e( Interrupt Co(e Action................................. ..........A@ 11.:.& Priorit) 9ffect on 9+ at P#78...................................................AA 11.:.3 18; Changing the interrupt priorit).............................................AA 11.:.6 18;Prioriti3e( Interrupt C Co(e..................................................AA 1& %ighlights........................................................ ...................................8& http://www.best-microcontroller-projects.com Page A of 83. Effective PIC Interrupts 2 Legal Copyright 2008 John Main http://www.best-microcontroller-projects.com All rights resere!. "o part o# this e$oo% may be repro!&ce!' store! in a retrieal system or transmitte! in any #orm or by any means electronic' mechanical' photocopying' recor!ing or otherwise witho&t e(press written' !ate! an! signe! permission #rom the a&thor John Main. DISCLAIMER AND/OR LEGAL NOTICES: )he in#ormation presente! herein represents the iew o# the a&thor as o# the !ate o# p&blication. $eca&se o# the rate with which con!itions change' the a&thor reseres the right to alter an! &p!ate his opinion base! on the new con!itions. )he report is #or in#ormational p&rposes only. *hile eery attempt has been ma!e to eri#y the in#ormation proi!e! in this report' neither the a&thor nor his a##iliates/partners ass&me any responsibility #or errors' inacc&racies or omissions. Any slights o# people or organi+ations are &nintentional. ,# a!ice concerning legal or relate! matters is nee!e!' the serices o# a #&lly -&ali#ie! pro#essional sho&l! be so&ght. )his report is not inten!e! #or &se as a so&rce o# legal or acco&nting a!ice. .o& sho&l! be aware o# any laws which goern b&siness transactions or other b&siness practices in yo&r co&ntry an! state. Any re#erence to any person or b&siness whether liing or !ea! is p&rely coinci!ental. http://www.best-microcontroller-projects.com Page 8 of 83. Effective PIC Interrupts 3 Introduction Interrupts are use( in all s)stems from simple microcontroller projects up to PC base( (es$top processors but each processor is only capa$le of perforing one instruction at a tie. ItFs important to note this since computers seem capable of an) number of actions simultaneousl) BIn fact the) can onl) achie"e this tric$ using interruptsC. 8he magic of interrupts is their abilit) to ma$e it appear that: %& Single'Instruction'&t'&'(ie Processor Can Perfor )ultiple Processes &** at the Sae (ie+ An interrupt allows the main processor co(e to be halte( while a sub process ta$es o"er the (e"ice an( performs a small tas$. It then returns control to the main program without the main program being aware that it was interrupte(. .ecause the interrupt co(e is small B4ote: )ou must ensure that it is $ept smallKC the time use( b) the interrupt is small an( it loo$s li$e both the main program an( the interrupt co(e are wor$ing at the same time. Note: Factors such as the size of the interrupt code, device processing power and affect the speed of the ain code and you have to !a"ance out these factors to find a wor#a!"e so"ution for your design pro!"e $ %ee &hapter '.8. Interrupt magic reall) (oes wor$ if the processing spee( of the (e"ice is fast because when main co(e an( interrupt co(e are e'ecute( Euic$l)5 it loo$s li$e simultaneous e'ecution. In fact )ou coul( sa) that if the processor is wor$ing fast enough then these processes reall) are happening at the same time Bwithin a finite time frameC i.e. if all these processes are happening within a millisecon( then the) are happening at the same time Bwithin the (iscrete time unit of a millisecon(KC. 3.1 From Polling To Interrupts Polling means loo$ing at a signal at regular inter"als i.e. itFs what )ou (o before )ou use interrupts an( itFs the most natural wa) to start programming a microcontroller. It is a useful metho( but interrupts pro"i(e a superior techniEue in sol"ing )our programming problem because the) allow large an( comple' programs to wor$ while man) smaller tas$s are han(le( (irectl) b) the interrupt co(e. http://www.best-microcontroller-projects.com Page : of 83. Effective PIC Interrupts <ithout interrupts the onl) wa) that an e'ternal e"ent Bsignal change on a pin or internal peripheral up(ateC can be (etecte( is for the program to perio(icall) loo$ at the input pin B$nown as pollingC but this must be (one while fitting in all the other program actions e.g. calculations/up(ate screens etc. Polling is a suitable metho( onl) if the processing loa( is low i.e. #nl) if )ou can go roun( the loop fast enough to ensure that )ou will ne"er miss an input e"ent. 8his is a (esign (ecision * either the e"ent must be slow enough compare( to the processor e'ecution time or the e"ent must be non critical i.e. Iou can affor( to wait a while before processing it or possibl) miss it altogether. ;or critical s)stems if an e"ent happens while the processor is bus) processing other instructions it is ignore( an( this can ha"e implications for )our program because missing (ata can cause the program to hang or )our s)stem to fail. Note: (f you do not want to use interrupts for soe reason it is sti"" possi!"e to interrogate the state of interna" periphera"s !ecause each periphera" that generates an interrupt sets a f"ag to indicate that the interrupt action occurred )even when the the rea" interrupt is not ena!"ed*. (f you po"" this f"ag then you wi"" !e a!"e to detect the event and do not need any interrupt code e.g. for receiving +, seria" data po"" the +, odu"e continuous"y reading the +, f"ag. -his ethod is on"y recoended for testing using sa"" sections of code and is not the !est way $ you rea""y shou"d use interrupts for !est perforance and ease of coding )as a progra gets !igger po""ing gives pro!"es whereas interrupt code is not affected !y the ain progra size*. 3.2 Real Time Events A 7eal 8ime 9"ent is an e"ent that is not s)nchroni3e( to the processor cloc$ so it can happen at an) ran(om time e.g. a $e) press is a 7eal 8ime 9"ent. 8o (etect it reliabl) )ou either ha"e to poll an input pin continuousl) Bwasting processing power an( batter) powerC or )ou use an interrupt Busing one of the input pins that has an interrupt associate( with it e.g. P#78.5 or I48 on a PIC microcontrollerC. Interrupts mean that a processor can run a main program an( at the same time process multiple critical signals inclu(ing 7eal 8ime 9"ent signals. ;or instance it coul( recei"e a b)te from the 7>&3& port as well as from an signal change on an e'ternal pin Ban(/or other internal mo(ulesC. 8)picall) the interrupting mo(ule will store the (ata/e"ent until the processor can ser"ice the interrupt. Note: (nterrupts can occur at the sae tie since each periphera" odu"e has it.s own hardware register)s* that store the data and you can service u"tip"e interrupts in the sae interrupt code. >o real time e"ents can easil) be capture( using interrupts e"en while the http://www.best-microcontroller-projects.com Page 1- of 83. Effective PIC Interrupts processor is e'ecuting other co(e in a "er) efficient wa) without a huge processing o"erhea( i.e. without wasting time. Interrupts are the onl) feasible wa) that a processor can react to real time e"ents i.e. e'ternal signal changes on pins or internal e"entsL when )ou co(e up large an( comple' programs. 3.3 c!ieving "ore #sing Interrupts >ome har(ware mo(ules Bwith interrupts outputs i.e. 0ost internal peripheral mo(ules in the PIC microcontrollersC allow )ou to measure real worl( parameters that )ou coul( not possibl) measure using onl) a FpollingF processing metho(. ;or instance the Capture Compare mo(ule can measure "er) small time (ifferences between input e(ges of a signal an( then gi"e an interrupt to tell the processor to store the "alues capture(. 8hese timing inter"als are much finer than using the eEui"alent Fsoftware co(eF to rea( the input port state because the software can onl) run at the processor spee( an( not at the (iscrete spee( of the har(ware i.e. the spee( of stan(ar( logic gates. Note: -here are a!out 1/ interrupt sources in a 0(& and ost of these are triggered fro within an interna" periphera" hardware odu"e at the cop"etion of each hardware tas#. 1"" of these can !e used together and even at the sae tie using interrupts to anage the. 3.$ %!& Interrupts are Essential for Critical Inputs Capturing a real time e"ent can be crucial for a s)stem to operate safel) since it is the onl) fast an( reliable wa) for an e"ent to be (etecte( especiall) if the main co(e is large an( comple' BslowC. 8o illustrate wh) interrupts can be essential for critical s)stem operations consi(er ma$ing a program using onl) the polling metho( without using interrupts. Consi(er a normal linear program that must (o multiple tas$s such as processing a screen5 then the $e)boar(5 then the rs&3& interface an( then computing a comple' calculation. At an) gi"en moment the processor will be engage( in an) one of these tas$s an( it is a matter of luc$ whether or not a $e) press is (etecte( at the $e)boar(. If the tas$s are small an( the computation is eas) then the processor coul( whi33 aroun( the co(e an( the $e) woul( be (etecte( but if not5 i.e. if the computation is comple' then the main program coul( be stuc$ for some time an( not get aroun( to chec$ing the $e)boar(. In some cases this ma) not matter but if )ou are ma$ing a critical real time s)stem where )ou must ensure that some piece of machiner) must be turne( off http://www.best-microcontroller-projects.com Page 11 of 83. Effective PIC Interrupts for safet) then an interrupt woul( be the best metho( Bfor a life threatening s)stem )ou woul( emplo) e'tra fail safe har(wareC. Iou woul( create a s)stem with an interrupt from a $e)boar( so that this real-time-e"ent coul( be ser"ice( imme(iatel) sa"ing the s)stem from (isaster. Interrupts are useful in (etecting 7eal 8ime 9"ents .ecause: 8he) are actione( imme(iatel) Bwithin a few instruction c)clesC. 8he) (o not reEuire large o"erhea( of co(e. 8he) a"oi( potential problems such as co(e loc$ up BcrashC in the main co(e Bthe interrupt co(e can not easil) loc$ up unless )ou reall) mess up the interrupt softwareKC. Note: &ode "oc# up can a"so !e itigated !y using the watch dog tier )23-*. -he purpose of the 23- is to reset the processor if the 23- is not c"eared within a certain aount of tie. N.4. Never c"ear the 23- fro within the (%+ )interrupt code* as it.s cheating and a#es the 23- use"ess !ut a"ways c"ear the 23- periodica""y fro within the ain code. -his way when or if the ain "oc#s up the 23- triggers and the processor resets restarting the code fro the !eginning. (t is a crude way of ensuring that the processor does not "oc# up forever and is rea""y on"y a fa""!ac# ethod since it does not save the current state of the progra. -he advantage is that the syste wi"" recover fro unforeseen software errors 8he interrupt co(e will still operate e"en if the main co(e loc$s up because main co(e e"en when loc$e( up is still e'ecuting in(i"i(ual machine co(e instructions that can still be interrupte( e.g. if main co(e is stuc$ in a loop waiting for an input or a computation to complete. 8his is wh) the interrupt co(e will continue e"en if it loo$s li$e the s)stem has (ie( an( it is wh) critical input monitoring can be safel) performe( using interrupts as long as the critical action Bthat must be performe( as a result of the interruptC is performe( in the I>7 itself * not in the main co(e. Note: (t does assue that you thorough"y test and siu"ate the interrupt code to ensure that it is correct !ut since it shou"d !e a sa"" piece of code this shou"d not !e a pro!"e. 3.' Po(er )aving Another use for interrupts is creating low power s)stems5 since some interrupts can wa$e the processor from low power sleep mo(e so sa"ing power until )ou nee( the processor to (o some wor$. Compare this to polling where the processor is continuousl) acti"e5 (oing no real wor$ * wasting batter) power. Note: %oe of the 0(& processors ep"oy Nanowatt techno"ogy eaning they can http://www.best-microcontroller-projects.com Page 1& of 83. Effective PIC Interrupts run for the standard she"f "ife of a !attery if they are put into this "ow power ode e.g. 15F88. $ Interrupts $.1 T!e Interrupt "odule 8he Interrupt mo(ule is a mo(ule attache( to the processor that stops the processor after it finishes the current machine co(e instruction an( forces a jump B"ia the interrupt "ectorC to another program Bthe I>7 * Interrupt >er"ice 7outineC. Note: 6ou won.t find the (nterrupt odu"e shown on the 0(& data sheet diagras !ecause interrupts affect )and are attached to* any of the interna" periphera"s and pins and it wou"d a#e the diagras too cop"e7. Note: (nstructions in 0(& icrocontro""ers are pipe"ined so the interrupt "atency )the tie !efore the (%+ is ca""ed* is not one instruction tie it is in fact fro 8 instructions )interna" interrupt* and fro 8 to 8.'/ instructions )e7terna"*. (n addition for e7terna" interrupts the "atency depends on when the signa" occurs in the current instruction cyc"e i.e. 4ecause the input signa" is unsynchronized with the processor c"oc#. 9atency occurs !ecause the pipe"ine ust !e c"eared !efore e7ecuting the new instructions in the (%+. Compare( to simple pin polling to (etect a signal change5 interrupts appear comple' an( (ifficult to use. ItFs true that )ou (o nee( more co(e an( )ou (o nee( to un(erstan( more (etails but this (ocument e'plains interrupts in a general sense Bapplicable to an) processorC an( shows )ou template co(e that )ou can use in )our PIC projects to easil) manage an) interrupt an( its associate( har(ware mo(ule. 8his means )ou will be able to easil) use interrupts an( interrupts ma$e comple' operation easier because the) separate processes into instantl) e'ecute( co(e locate( in the I>7 i.e. the) separate out small bloc$s of easil) manage( co(e which is more robust than ha"ing co(e bloc$s e'ecute( one after another in the main co(e. $.2 Polling disadvantages ;or a simple s)stem )ou ma) (eci(e ,ot to use interrupts instea( polling the resource .e.g the $e)pa(5 then the 7>&3& interface an( then the sensor input. Iou woul( (o this continuousl) in a loop of co(e repeate(l) chec$ing each resource until something happens i.e. A $e) is presse(5 (ata recei"e( or an( input from the sensor is recei"e(. 8his Euite often happens when )ou (e"elop a http://www.best-microcontroller-projects.com Page 13 of 83. Effective PIC Interrupts simple s)stem since itFs eas) to (o an( it (oes wor$. 8he problem comes when )ou ha"e to (o something else or react to more inputs or when )ou ma$e the program larger. All of these increase the e'ecution time of the loop so it ta$es longer to get aroun( to processing each input. Polling (oes wor$ if the processing time is co(e( carefull) to $eep it to a minimum compare( to the e'pecte( rate of input (ata from the input resources but )ou ha"e to "er) carefull) (esign the s)stem an( if )ou change or a(( resources )ou will nee( to thin$ again an( possibl) re-(esign. It is in fact easier to use interrupts since the main program can be altere( without affecting the operation of the whole s)stem. .ut this is onl) true if the I>7 time is small compare( to the main co(e e'ecution time i.e. )ou must $eep the I>7 co(e as short as possible - in general $eep the interrupt co(e a short as possible an( ma$e e"er) attempt to mo"e an) comple' processing operation out of the interrupt an( into the main co(e i.e. 2se flags to mo"e co(e out of the I>7 Bpage 31C. If the I>7 is too long an( so long that the main co(e (oes not ha"e enough time to (o itFs job then continuous interrupts can o"erloa( the main co(e before it has finishe( processing (ata from the pre"ious interrupt an( this will loc$ up the s)stem i.e. it will crash. Note: 1s with a"" syste design it is a !a"ancing act where you have to decide on the correct size of (%+ and ain code size and it a"" depends on the pro!"e to !e so"ved and other syste features : see &hapter '.8 for syste design trade off decisions that you can use to iprove syste perforance. $.3 T!e Po(er of Interrupts Interrupts allow )ou to create small poc$ets of co(e that (o a specific small tas$ while the main program continues operating. ;or e'ample if )ou use an 7>&3& interrupt mo(uleL when a b)te of (ata is recei"e( b) the mo(ule an interrupt is generate( to interrupt the processor from itFs current tas$. 8he mo(ule triggers an 7>&3& 7M Brecei"eC (ata interrupt. 8his tells )ou that some (ata is rea() to be processe( in the 7>&3& 7M mo(ule an( that )ou shoul( (o something about it within the I>7 co(e. In the I>7 )ou write some co(e that ta$es the (ata from the mo(ule an( stores it for later processing b) the main program Bwhen it is rea() to (o soC or )ou can set a flag telling main co(e to rea( the mo(uleFs (ata Bas long as )ou $now that the main co(e is capable of processing the (ata before the ne't b)te is recei"e( at the serial portC. Note: For cop"e7 systes a circu"ar !uffer wi"" often !e used to gather the http://www.best-microcontroller-projects.com Page 16 of 83. Effective PIC Interrupts received +%;8; data and this saves the ain code fro having to decode and store each !yte of data $ typica""y the (%+ circu"ar !uffer code wi"" set a f"ag when a specific !yte is received e.g. ."ine return. $ this way the ain code <ust has to recognize a cop"ete te7t string. &ircu"ar !uffers are ore cop"e7 re=uiring use of pointers and code to ensure no data overruns within the !uffer itse"f. Interrupts mean that the main program (oes not ha"e to stop itFs current operation to imme(iatel) process the incoming (ata * it effecti"el) happens in the bac$groun( an( the main program can processes the (ata when its rea(). $.$ *o( +oes n Interrupt ffect T!e "ain Code, It appears to the main program that interrupts are ser"ice( in the bac$groun( with no effect on the main program but it is important to un(erstan( there is an effect on the operation of the main co(e. 8o un(erstan( wh) itFs a goo( i(ea to see how interrupts wor$. 8he interrupt wor$s li$e this: After completing the current instruction Bplus pipeline (ela)C5 8he the current location an( state is store(5 8he interrupt co(e is e'ecute(5 8he original location an( state is restore(5 8he main program continues as before. <hen thin$ing about an interrupt )ou coul( sa) that the currentl) e'ecuting program is unaware of the interrupt co(eFs action but it means the current co(e looses a few instruction c)cles. In fact5 the effect of the interrupt is to insert a (ela) into the main program an( this (ela) is (epen(ent on which parts of the interrupt co(e are e'ecute( an( this will "ar) (epen(ing on the actual interrupts that are triggere( i.e. 8he (ela) time (ue to the interrupt is un$nown an( ran(om Bunless )ou anal)3e the interrupt co(e "er) carefull) or it has onl) one eas) to anal)3e co(e section i.e. without multiple interruptsC. 8his is wh) co(e that e'ecutes normall) i.e. co(e outsi(e of the interrupt function must be co(e that is timing insensiti"e i.e. Iou must not ma$e co(e Boutsi(e the interrupt co(eC that (epen(s on e'ecuting co(e in a specific fi'e( timeL for instance if )ou create( a (ela) routine carefull) co(e( in assembler Bin the main co(e areaC to operate at a fi'e( (ela) time of 1--us if interrupts were enable( then the 1--us (ela) woul( be interrupte( ma$ing it longer b) a ran(om amount (epen(ing on the an( length of the interrupt routine itself. Note: -his is why the seven segent fre=uency counter on site does not use http://www.best-microcontroller-projects.com Page 1= of 83. Effective PIC Interrupts interrupts. -he ain code is carefu""y tied to a""ow a specific "ength e7ecution tie regard"ess of the path of e7ecution of the code. Using interrupts wou"d change this causing errors in fre=uency easureent. $.' *o( to Ensure Interrupts and "ain code %or- 8he $e) problem with processors ha"ing low processing 0IP> i.e. PICs is that )ou can not affor( to throw awa) processing time. Interrupts (o ma'imi3e )our use of this time but )ou must be careful to (esign the co(e to share out processing time between the main co(e an( interrupt co(e. If )ou thin$ of the processing power of a (e"ice as a single bar below in blue. 8his bo' represents a "isuali3ation of the (e"ice co(e/0IP>. 8he re( bo' represents the i(eal interrupt co(e/0IP>. 8he abo"e situation woul( be i(eal where most of the processing time is spent performing main co(e actions an( a highl) optimi3e( interrupt routine is small an( efficient. 8he last (iagram shows processing power share( out in the wrong wa) since more time/0IP> is spent in the interrupt routine than (oing main co(e processing. If interrupts occurre( at a high rate then the processor woul( be o"erloa(e( an( woul( crash (ue to constant interrupts ne"er allowing the main co(e to operate. #n the flip si(e this (esign can wor$ if )ou $now that interrupts are infreEuent an( thatFs )our (esign (ecision. >ee also Chapter A.8 for other (esign (ecision tra(e off information. $.. voiding ccidental Code Increase In t!e I)R It is eas) to acci(entall) ma$e I>7 fail b) co(ing it wrongl) but there are more subtle wa)s of ma$ing it fail an( these are tric$ier to (etect arise as a result of the con"enience of the use of a high le"el language. 8he two main culprits are: Choosing the wrong (ata t)pes. %i((en co(e libraries. http://www.best-microcontroller-projects.com Page 1@ of 83. Effective PIC Interrupts $...1 +ata T&pes >ometimes )ou can acci(entall) ma$e the interrupt routine large b) something as simple as using the wrong (ata t)pe or function in C which pulls in some librar) co(e that is far too long Bbut it is not "isible in the co(e because it is (one in the bac$groun( for )ouC. 9'amples of this are the floating point t)pe which 8 bit processors are not goo( at an( conseEuentl) reEuire large amounts of co(e to support. $...2 *idden Librar& Code #n a project that I wor$e( on a software (esigner use( sprintf to (ebug output all within an interrupt an( this cause( intermittent operation because the actual sprintf co(e too$ (ifferent amounts of time (epen(ing on "ariables being output. It soun(s li$e the most ob"ious wa) to (ebug co(e after all it is one wa) to (ebug embe((e( co(e i.e. b) sen(ing serial information out to a PC 7>&3& port. In the main co(e this techniEue (oes wor$ well because it is simple5 eas) an( con"enient. 8he problem is that sprintf (oes a huge amount of wor$ behin( the scenes Bi.e. it has a huge un(erl)ing co(e baseC an( when )ou use it parts of that librar) will be inclu(e( in the co(e (epen(ing on the e'act tas$ )ou want it to (o i.e. (ispla) a long as a formatte( te't string etc. >o (epen(ing on which "ariable t)pe )ou are currentl) (ebugging the time ta$en will "ar). If )ou use it within the I>7 then the "ariable time ta$en can cause the interrupt to ta$e too long an( fail. 8he solution was to remo"e the sprintf co(e then the interrupts wor$e( perfectl)K Note: %oe copi"ers a""ow you to ca"" functions fro within the (%+ )a""owing easier partitioning of the (%+ code* so watch out that you don.t use hidden code or too !ig data types when coding these functions !ecause those functions wi"" "oo# e7act"y "i#e other .nora". functions ' *o( Interrupts %or- 8o un(erstan( interrupts itFs a goo( i(ea to re"iew the instruction c)cle of the PIC processor as the interrupt mechanism must fit perfectl) within it for interrupts to operate at all. '.1 Instruction c&cle All processors can onl) (o one thing at a time i.e. 8he) fetch an instruction5 process it an( then increase the program counter rea() for the ne't repetition of this c)cle. 0o"ing to (ifferent co(e areas e.g. .) jump or call is achie"e( b) http://www.best-microcontroller-projects.com Page 1A of 83. Effective PIC Interrupts manipulating the program counter Bmemor) a((ressC (uring the processing c)cle. <hate"er happens the processor must follow this simple scheme: +9C#+9 : Instruction (eco(e c)cle 79A+ : 7ea( (ata c)cle P7#C9>> : +ata process c)cle <7I89 : +ata write c)cle Note: -he 3ata 0rocessing )0+>&?%%* part of the cyc"e wi"" update the 0rogra &ounter increasing it !y 1 for a nora" instruction )to ove to the ne7t instruction* and increasing it !y the data va"ue)s* for a <up instruction* updated after the write cyc"e. 8his is wh) the PIC instruction freEuenc) is N times the main cloc$ freEuenc) since there are four actions complete( in one instruction c)cle e.g. A cloc$ running at 60%3 lets instructions run at 103 B60%3/6C or 1us. 9ach of the abo"e actions ta$es 1 main cloc$ perio( to perform. 8his c)cle repeats en(lessl) with the program counter up(ate( at the en( of e"er) instruction so all the processor can (o is linearl) e'ecute seEuential instructions or jump to a (ifferent a((ress to e'ecute another instruction. +esigners reali3e( that this s)stem b) itself (oes not allow a processor to react imme(iatel) to an e'ternal e"ent ma$ing the processor fairl) uselessK >o the) a((e( the abilit) to stop the processor mi(-wa) through a program an( jump to a (ifferent program i.e the Interrupt * this jump a((ress is $nown as the interrupt "ector. 8he basic wa) that the interrupt wor$s is b) storing the current "alue of the program counter on the stac$ an( then changing the program counter to the "alue hel( in the interrupt "ector. #n return from the I>7 the Program counter is set bac$ to the "alue on the stac$ so the program continues from e'actl) where it was pre"iousl). . Interrupt )ervice Routine /I)R0 8here are two parts to an I>7 Balthough strictl) the I>7 is just the interrupt co(e but the "ector is tie( (irectl) to the I>7 so the) are treate( as one hereC. 8he Interrupt ,ector. 8he Interrupt Co(e. http://www.best-microcontroller-projects.com Page 18 of 83. Effective PIC Interrupts ..1 I)R 1 Interrupt )ervice Routine 8he Interrupt >er"ice 7outine BI>7C is the onl) entr) point Bor functionC calle( when an interrupt jump is triggere(. 8his happens when an enable register bit is unmas$e( an( when the correspon(ing interrupt flag is set b) the har(ware mo(ule that generates the interrupt when the mo(ule completes its action. 8he most important point about an interrupt routine is that it must be $ept short unless )ou ha"e a "er) goo( reason for (oing otherwise. In general )ou nee( to $eep it short so that: 1. Iou can ser"ice man) interrupts Bas man) as nee(e(C. &. Iou allow the main program to continue processing. !eeping the I>7 short is another wa) of ensuring that there is enough time for the main program to ha"e enough processing c)cles to (o itFs job. ..2 Interrupt 2ector An interrupt "ector is a (e(icate( har(ware a((ress that contains a jump location which is calle( when an interrupt occurs. 8he problem in un(erstan(ing interrupts is that there is onl) one interrupt "ector but multiple interrupts. 8he Euestion is how (o )ou ser"ice man) interrupts using onl) one jump location Ban( conseEuentl) onl) one piece of interrupt co(eC? 8he short answer is to use a har(ware solution using internal har(ware registers. Iou ha"e to (etect e'actl) which interrupts were triggere( b) rea(ing registers that store the interrupt state when the interrupt triggere( an( )ou (o this as part of the Interrupt >er"ice 7outine co(e for all interrupts that will be acti"e in )our s)stem. 8he interrupt "ector is simpl) a location that contains an a((ress an( this a((ress is programme( to contain the starting point of the I>7 or the Interrupt Ser"ice -outine B)our interrupt co(e functionC. In a PIC when an) interrupt is triggere( the contents of this "ector location replaces the program counter i.e. the interrupt co(e is Fcalle(F as an Interrupt >er"ice 7outine BI>7C * the return a((ress is also store( on the stac$. Note: (n the 0(& 15 series the interrupt vector is at physica" address 07000@. 6ou "oad this address with the address of your (%+ so whenever the interrupt triggers then your (%+ code is ca""ed. >ften a high "eve" "anguage wi"" do a"" the hard wor# for you and you don.t even have to #now this address since =ua"ifying the function with the word .interrupt. wi"" te"" the copi"er that this function is to !e an (%+. +ee!er soe copi"ers re=uire different notation as interrupts are not a part of the 1N%( standard & specification. For instance Ai#ro& "oo#s for a http://www.best-microcontroller-projects.com Page 1: of 83. Effective PIC Interrupts function naed .interrupt.. Note: >ther processors ay have ore interrupt vectors !ut they a"" wor# in a sii"ar way to a sing"e interrupt vector. For instance others wi"" have an NA( interrupt which eans Non:Aas#a!"e:(nterrupt $ this is sip"y an interrupt that can not !e ignored and is reserved for a!so"ute"y critica" syste actions e.g. the device is a!out to !e powered down )the 0(&s do not have this type of interrupt since the !rown out device acts autoatica""y if ena!"ed*. 1"so ore interrupt vectors add ore and ore cop"e7ity to a device and re=uire ore code to service those interrupts. ..3 Interrupt Code 8he interrupt co(e Bor I>7C is the single program function that )ou write to manage Bor ser"iceC an) interrupt that is triggere(. It is the action point for an) har(ware mo(ules that generate these interrupts an( although it is a single piece of co(e Bone functionC5 it must contain co(e for each interrupt in use. ;or each interrupt that )ou enable Bunmas$e(C there are three actions to be ma(e in the I>7: +etect if the interrupt has triggere( Btest the flag bit in a PI7 registerC. If the interrupt triggere( clear the same flag bit to re-enable this interrupt. Perform actions that )ou want to e'ecute (ue to this interrupt. 4ote: It is not necessar) to re-enable the mas$ register BPI9C as this is not change( b) the interrupt action so once enable( the interrupt is in use until the specific bit in the enable register BPI9C is cleare(. 8he I>7 is just another piece of co(e but )ou ha"e to ha"e some e'tra co(e surroun(ing the core I>7 co(e to perform essential house$eeping tas$s Bor Conte't >witchingC. 8his inclu(es a special machine co(e instruction 798;I9 B-E(urn .rom Interrupt EnableC as the "er) last instruction. 8his is wh) an interrupt function can ne"er simpl) be a normal piece of co(e * the routine )ou use must be flagge( as an interrupt routine so that Conte't >witching can ta$e place automaticall) for )ou. Note: 0ersona" &oputers use Software Interrupts which are triggered using a achine code instruction to generate an interrupt which causes e7ecution of an (%+. -here are no software interrupts in a 0(& since it is a hardware centric device so a"" interrupts are generated !y actions of hardware events e.g. a tier tieout )hardware tier !ecoes zero* or a signa" change on an input pin e.g. 0ort4. http://www.best-microcontroller-projects.com Page &- of 83. Effective PIC Interrupts ..$ Conte3t )(itc!ing ..$.1 )aving T!e Current )tate 8o ma$e an interrupt useful it has to wor$ seamlessl) with the co(e that has been interrupte( an( to (o this the state of the processor must be sa"e( an( restore( before an( after e'ecuting the interrupt. ;ortunatel) the PIC micro onl) has a few registers that nee( sa"ing Bthese are the A2 registers an( not the file registers i.e. 8he internal registers <5 PCA8% register an( the >8A82> registerC. In (ifferent processors there will be man) more registers to preser"e. 8his action is also $nown as conte't sa"ing. ..$.2 )aving t!e Program Counter As well as sa"ing the register state the program counter must be store( so that the interrupt can return to the original co(e e'ecution point. 8his is the onl) action the the 1@; series processor will (o for )ou all other actions must be (one b) writing more co(e aroun( the interrupt routine itself. 8he PIC (e"ice will automaticall) push the Program Counter BPCC "alue to the stac$ when an interrupt is triggere(. An( at the en( of an I>7 )ou must e'ecute the 798;I9 B-E(urn .rom Interrupt EnableC instruction which pops the 7eturn a((ress from the stac$ an( enables the Dlobal Interrupt flag. ..$.3 4an- Conte3t )aving 8he onl) other critical thing to loo$ out for in the 1@; series is that the segmente( memor) using ban$ switching must also be sa"e( an( restore(. 8his is because an interrupt routine coul( ma$e use of a (ifferent ban$ compare( to the main program. Note: Aost high "eve" copi"ers wi"" ta#e care of &onte7t %witching )inc"uding !an# conte7t switching* for you and this a#es using interrupts even easier. 5 Coding PIC Interrupts >ee Chapter 11.& for the Interrupt co(e template. 8he (iagram below shows a generic har(ware (iagram of interrupt registers the mas$ or flag register BPI7C an( the enable register BPI9C. http://www.best-microcontroller-projects.com Page &1 of 83. Effective PIC Interrupts 5.1 PIC Interrupt Registers .ecause PIC (e"ices ha"e been aroun( for Euite some time an( the new ones must be bac$war(s compatible with the original Bto allow as much co(e re-use as possibleC the interrupt registers ha"e been (esigne( incrementall). In fact the new interrupt register la)out is far easier to use because it is logicall) arrange( whereas the original interrupt flags are sEuashe( into a single register. >o initiall) weFll tal$ about interrupts using the new register set an( then bac$trac$ to the original register. Note: Fro here on the ter odu"e refers to interrupts generated fro interna" hardware odu"es as we"" as e7terna" interrupts generated at a pin. ;or each peripheral mo(ule within the PIC microcontroller that generates an interrupt there are two register flags associate( with it: 8he state flag - PI7 register 8he enable flag * PI9 register http://www.best-microcontroller-projects.com Page && of 83. Effective PIC Interrupts 5.2 PIR Perip!eral Interrupt Register )tate /Flag0 9ach of these is a single bit within a specific register - newer registers are labele( PI7 Peripheral Interrupt 7egister B;lagC with a number on the en( to allow multiple sets of these registers. 9ach bit in a PI7 register is a flag telling )ou if the mo(ule generate( an interrupt signal i.e. if the mo(ule was acti"ate( since the last time that the register bit was cleare(. Note: (portant : 0(+ f"ag !its are set even if the ena!"e f"ags are not set i.e. interrupt f"ags show the )interrupt* state of the odu"e even when a"" ena!"es are not active )inc"uding B(?, 0(? and 0?(?*. -his a""ows software po""ing of the odu"e even when no interrupt is actioned for the odu"e. 5.3 Perip!eral Interrupt Enable PIE /Enable0 9ach of the PI9 bits is a single bit within a specific register labele( in the same wa) as the PI7 register e'cept this is labele( PI9 B9 for enableC. 9ach bit in a PI9 register enables the correspon(ing har(ware mo(ule to cause an interrupt action i.e. it ma$es the interrupt from the associate( har(ware mo(ule acti"e so that it will cause a jump to the interrupt "ector. Note: 0(+ and 0(? registers are a"igned so that the sae !it position in each register services the hardware odu"e a""owing convenient !itwise operations. -his is different to the origina" 0(& devices that put a"" interrupt ena!"es and f"ags into the (N-&>N register. 5.3.1 Interrupt "as-s 8he PI9 register can also be thought of as a mas$ register where each bit can be set or reset using bitwise operators an( this allows )ou to enable or (isable in(i"i(ual interrupt sources. Note: -he process of setting )ena!"ing* an individua" interrupt ena!"e !it is #nown as unmasking an interrupt. http://www.best-microcontroller-projects.com Page &3 of 83. Effective PIC Interrupts ;or instance )ou ma) want to turn off a capture interrupt because at that particular time )ou are not rea() to capture a trigger time "alue. #nl) when other co(e has e'ecute( e.g. )ou turn on a trans(ucer5 will )ou want to enable that interrupt. 8hese flags allow that to happen but the) also allow other interrupts to continue e.g. a timer interrupt can still count time as a bac$groun( tas$. 5.$ I6TC76 8 7riginal Interrupt Control Register 8his is a single 8 bit register that e'ists on all the ol( an( new PIC (e"ices. #riginall) it was probabl) thought that there woul( not be man) interrupts so all the enables an( flags were place( in this register. As the range of (e"ices has increase( an( the number of internal peripherals Bwith interrupt capabilit)C has also increase( so more interrupt space was nee(e( hence the creation of PI7 an( PI9 registers for interrupt e'pansion. A spare position in I48C#4 has been use( to allow enabling of all other internal peripheral interrupts an( is labele( P9I9 * just set this bit high if )ou are using an) of the other internal peripheral interrupts Bother than the three original ones (etaile( belowC. 8he e'isting interrupt flags an( enables in this register are: Ena$les 8I097-I9 Bbit=C I48-I9 Bbit6C 7.I9 Bbit3C .lags 8I097-I; Bbit&C I48-I; Bbit1C 7.I; Bbit-C 8hese are for timer -5 e'ternal pin interrupt an( P#78. interrupt respecti"el). 5.' 9lobal nd Perip!eral Interrupt Enable 8hereFs two registers for global control of interrupts an( these both allow interrupts to cause a jump to the I>7 routine. 5.'.1 9IE 8he first global interrupt flag is the DI9 control flag or /lobal Interrupt Enable controlC. It is from the original PIC series an( it is containe( in the I48C#4 register. <hen set it allows all interrupts to operate an( when cleare( it pre"ents http://www.best-microcontroller-projects.com Page &6 of 83. Effective PIC Interrupts all interrupts from operating BNote: -his !it overrides the 0eriphera" (nterrupt contro" 0?(?C. DI9 is automaticall) cleare( when the I>7 is e'ecute( so that no more interrupts trigger the I>7. It is not automaticall) enable( at the en( of )our interrupt co(e an( )ou must ensure that there is a 798;I9 instruction B-E(urn .rom Interrupt an( Enable an( DI9 bitC at the "er) en( of )our co(e Bnormall) high le"el compilers will automaticall) (o this for )ouC. Note: 6ou can contro" B(? yourse"f <ust "i#e any other register f"ag at any point in your codeC for instance if you want to turn off interrupts whi"e you do soe critica" code that ust not !e interrupted )of course you ay iss interrupts and it.s up to you to ensure that the syste sti"" wor#sD*. Note: B(? is autoatica""y turned off when an (%+ is ca""ed so that the interrupt code itse"f is not interruptedD 5.'.2 PEIE 8he secon( global interrupt flag is the P9I9 control flag or Peripheral Interrupt Enable. 8his fits into a spare register position that was left free for future e'pansion in the I48C#4 register an( is a enable control for all peripheral har(ware interrupts. <hen )ou clear this it means that the har(ware operates onl) with interrupts that were create( for the original series of PIC chips. Practicall) P9I9 is not much use so just lea"e it set high an( use DI9 to control all interrupts. Note: B(? overrides 0?(?. 5.. #sing t!e Interrupt Flag Registers #nce the DI9 bit an( P9I9 bits are enable( the PI9 Binterrupt enableC registers come into pla) an( an) bits that are set will allow the associate( interrupt to fire an( trigger the I>7 co(e. It is important to note that the flag registers BPI7C tell )ou the state of the interrupt from the associate( har(ware mo(ule but the) wor$ in(epen(entl) from the enable registers i.e. the flag register will reflect the state of the interrupt signal from the associate( mo(ule regar(less of whether the PI9 #7 DI9 bits are set or not. 8his means )ou can poll the har(ware mo(ule to (etect a change of state of the mo(ule Bnot recommen(e( but useful if )ou are caught outC. 8he flag bit is set b) the har(ware mo(ule to in(icate that the har(ware has generate( an interrupt con(ition i.e. it triggers an interrupt that will cause a jump http://www.best-microcontroller-projects.com Page &= of 83. Effective PIC Interrupts to the I>7 Bif the correspon(ing enable bit in the PI9 register an( associate( enables are acti"eL P9I9 an( DI9C. After the interrupt has triggere(5 the same flag registers will store the state of the har(ware so b) rea(ing the flag register BPI7C )ou can (etect which har(ware mo(ule triggere( the interrupt. After this )ou must write a 3ero to this in(i"i(ual bit to reset it an( allow the mo(ule to generate this interrupt again after the I>7 has complete(. >ee Chapter 11.& for the Interrupt co(e template. http://www.best-microcontroller-projects.com Page &@ of 83. Effective PIC Interrupts 5.5 Interrupt Flo( +iagram 8he following flow (iagram shows how to initiali3e an( use interrupts correctl). >ee Chapter 11.& for the Interrupt co(e template. http://www.best-microcontroller-projects.com Page &A of 83. Initiali3eOInterrupts 9nableOInterrupts ;or each har(ware peripheral that )ou want to use set itFs F9nableF flag i.e. the PI9 bit. an( clear its state flag i.e. the PI7 bit A(( co(e here that sets up each har(ware mo(ule rea() for use. 8urn on the DI9 bit an( the P9I9 bit B)ou coul( turn on the P9I9 bit in the initiali3e co(e as DI9 o"erri(es P9I9 so P9I9 is not reall) useful but has to be set high somewhereC. Perform 0ain Co(e Actions Ban( repeat in loopC F9nableOInterruptsF is place( before the main co(e loop Bnot within itC. Co(e then operates as normal while interrupts are acti"e i.e. interrupts are acti"e within the main co(e loop. +isableOInterrupts F+isableOInterruptsF is use( Bwith (iscretionC an)where within the main co(e. Effective PIC Interrupts 5.: Interrupt +esign +ecisions An interrupt constitutes a brea$ in the normal operation of e'ecuting co(e but )ou can alter the effect of the interrupt on that co(e b) un(erstan(ing three factors. 1. 8he interrupt rate Beither from e'ternal or internal sourcesC. &. 8he length of the interrupt co(e Bthe I>7C. 3. 8he processing power of the processor. 8hese factors control how effecti"e )our project will be so )ou must ha"e some i(ea of them when creating )our project. ;or instance if )ou were measuring the rate of a signal changing on a pin Ban( using an e'ternal interrupt to (etect itC. If the signal was firing the interrupt at a rate of 1$%3 or 1ms then )ou can wor$ out that )ou woul( ha"e 1--- machine co(e instructions before the ne't interrupt fires Bassuming a 60%3 Cr)stal an( conseEuent internal instruction rate running at 10%3 so 1ms/1e-@ P 1--- instruction c)clesC. #b"iousl) the interrupt routine must ta$e a short enough time so that it completes well before the ne't interrupt because )ou can not ha"e multi threa(e( interrupts i.e. the interrupt must be full) complete( before the ne't interrupt occurs. Also )ou nee( the interrupt to complete in a short time so that there is enough processing time left o"er for the main co(e. Note: (n practice you wou"d pro!a!"y use a different ethod to detect the signa" e.g. !y using a presca"er in front of the signa" or use an interna" tier with !ui"t in presca"er. In general the i(eal situation is to ma$e the I>7 as short as possible so that the main tas$s of the processor Ball other co(eC can be e'ecute( as well. In general the best (esign will ha"e the interrupt routine ta$ing significantl) less time than the main co(e e'ecution loop. 8o wor$ out the processing time just subtract the I>7 time form the fastest interrupt repeat rate so for e'ample perhaps )ou ha"e an I>7 time of 1-- instruction c)cles en( up with an appro'imate "alue of :-- c)cles i.e. :-- instruction c)cles for the main program to operate before the ne't interrupt fires. If the input freEuenc) increases to &$%3 then )ou woul( onl) ha"e 6-- c)cles for main co(e e'ecution. At 6$%3 an( )ou onl) ha"e 1=- c)cles. >o seemingl) small changes in the input freEuenc) will cause the ma'imum Bmain co(eC processing time to rapi(l) (ecrease. 8his ma) or ma) not be important an( it (epen(s on the main co(e processing tas$. ;or instance if a simple C+ (ispla) was to be up(ate( then it ma) be #! to http://www.best-microcontroller-projects.com Page &8 of 83. Effective PIC Interrupts be continuousl) interrupte( as the (ispla) woul( be up(ate( e"entuall). If howe"er there was a time constraint where some actions ha( to be performe( then it woul( not be #! for the interrupts to continuousl) fire. 9"entuall) the repeat rate of the interrupt coul( become too large halting the s)stem completel) i.e. the processor will spen( all itFs time ser"icing the interrupt routine (oing no useful wor$. Note: -his syste is dependent on an e7terna" signa" over which you ay not have contro" so the pro!"e is actua""y a cop"ete design pro!"e where you ust characterize the cop"ete pro<ect i.e. the e7pected a7iu signa" input rates 5.:.1 Processing ; Interrupt Time nal&sis Interrupt -ate Instruction Cycles &vaila$le 0$efore ne1t interrupt PIC using 2)H! 3tal4 Interrupt routine length Cycles &vaila$le (o )ain Code 0$efore ne1t interrupt4 1$%3 1--- 1-- :-- &$%3 =-- 1-- 6-- 6$%3 &=- 1-- 1=- 8$%3 1&= 1-- &= 8he real point about this problem is that the a"ailable processing time is re(uce( as the interrupt rate increases. ets assume that the 1$%3 rate is the FrealF (esign point i.e. the rate that )ou ha"e (esigne( the s)stem to wor$ aroun(. >o )our total e'pecte( c)cles a"ailable to (o main co(e wor$ is :-- c)cles. 8he Interrupt co(e routine is fi'e( Bnote: It will change (epen(ing on which actual interrupts an( their associate( co(e are e'ecute( but just ta$e the 1-- c)cles as )our t)pical interrupt co(e length/timeC so lets assume that 1-- c)cles are use( at e"er) interrupt call. 8he table abo"e shows the a"ailable processing time left for use in the main co(e Btotal machine instruction c)cles between interrupts at the (esign interrupt rate of 1$%3 minus the time use( in the interruptC. As the interrupt rate increases so less main co(e instruction c)cles are left for use. http://www.best-microcontroller-projects.com Page &: of 83. Effective PIC Interrupts Comparison of Instruction Cycles Available as Interrupt Rate Increases Interrupt rate Cycles calculation (otal Cycles &vaila$le (o )ain Code Percentage of )ain code cycles availa$le copared to cycles at 5kH! design rate 1$%3 1----B1Q1--C :-- 1--R &$%3 1----B&Q1--C 8-- 8:R 6$%3 1----B6Q1--C @-- @AR 8$%3 1----B8Q1--C &-- &&R 5.:.2 T!ree Interrupt +esign )olutions %ereFs three wa)s to combat the problem b) (esign choice: 1. Increase the main s)stem cloc$ Bmore processing powerC. &. Place a (i"i(er in front of the signal source i.e. a (iscrete chip. 3. 2se an internal 8imer an( its prescaler Bfee(ing into an internal counterC. 8he important point is that )ou must figure out if the s)stem is capable of wor$ing correctl) before committing to an) particular (esign Ban(/or (o some brea(boar(ing testsC. 5.:.3 Effect of using a 2<"*= cloc- 8he table abo"e shows what happens when )ou )ou increase the processing power of a (e"ice. .ecause the interrupt co(e si3e remains the same there are far more processing cloc$ c)cles a"ailable to the main co(e so the I>7 has less effect Buses less c)cles compare( to the total a"ailableC on main co(e operation. Note: (nstead of <ust changing the c"oc# you cou"d change the device e.g. use a 18F series with !ui"t in 099 i.e. e7tree"y high interna" c"oc# rate and ree!er changing a device over is a !ig <o! !ut it is ade uch easier when you use a high "eve" "anguage such as &. 1"so the interrupt code tep"ates presented here are generic $ <ust change soe register naes if the new device uses different ones. Calculations: ,ta" E ;0AHz, processor c"oc# E ;0e5F@ E /AHz, -E;00ns &yc"es within 1#Hz period E 1F1#Hz E )1F1e8*F;00e:G E /000 http://www.best-microcontroller-projects.com Page 3- of 83. Effective PIC Interrupts Effect of Increasing the Processor Clock to 2!"# Interrupt rate Cycles calculation (otal Cycles &vaila$le (o )ain Code Percentage of )ain code cycles availa$le copared to cycles at 5kH! design rate 1$%3 =----B1Q1--C 6:-- 1--R &$%3 =----B&Q1--C 68-- :8R 6$%3 =----B6Q1--C 6@-- :6R 8$%3 =----B8Q1--C 6&-- 8@R : +esign tec!ni>ues :.1 #sing FL9) to communicate from I)R to main Program ;lags are boolean "ariables use( to in(icate that an action shoul( be ta$en an( )ou can use them to transfer actions from the I>7 to the main co(e. Note: 6ou can save space !y using !it varia!"es in & and use the as !oo"ean f"ags. In C )ou can also (eclare a "ariable as a FstaticF within a file an( it has what is $nown as file scope Bit is onl) "isible to functions that are (eclare( within the file itselfC. 8his means that an) function in the same file5 inclu(ing the I>7 function5 can FseeF the "ariable. Iou can use this "ariable as a flag "ariable which can be set within the I>7 an( actione( within the main co(e. In this wa) a non critical actions can be performe( when instigate( b) an interrupt trigger flag from within the I>7. >o wh) woul( )ou want to (o this? 8he reason is that )ou can re(uce the I>7 time which is one wa) of impro"ing performance of )our s)stem. Iou can ta$e co(e that woul( otherwise ha"e to be performe( within the I>7 itself an( (elegate it to be performe( b) the main co(e when it goes aroun( its processing loop. 8he penalt) is that )ou wonFt $now e'actl) when the (elegate( co(e is e'ecute( so )ou ha"e to ensure that this (oes not matter i.e. it must not ha"e a critical e'ecution time reEuirement. 8he benefit is that the I>7 has to onl) e'ecute a few instructions i.e. setting a http://www.best-microcontroller-projects.com Page 31 of 83. Effective PIC Interrupts "ariable5 instea( of e'ecuting a whole lot of co(e within the I>7. 8his means that the interrupt is shorter an( )ou ma) be able to increase the interrupt rate an( this can mean better performance. >ee Chapter 11.@ for a simple e'ample using this flag techniEue * this is onl) a s$eleton co(e e'ample but illustrates the structure of co(e to use. A more real e'ample woul( be storing recei"e( 7>&3& (ata into a buffer Bin the I>7C an( when full setting a flag to in(icate that the main co(e shoul( go an( interpret the contents. 8his means the I>7 can be $ept small an( lean an( the main co(e is onl) e'ecute( when nee(e( i.e. there is no (ata interpretation within the I>7 itself. :.2 ?Interrupt Cascade? @ An Finterrupt casca(eF G is a simple concept of calling an( starting one interrupt from within another. ItFs a techniEue that is useful for not onl) precise repeate( interrupts but precise repeate( interrupts that ha"e a resulting precise repeatable output of (ifferent (uration to the main interrupt rate i.e. itFs goo( for creating a P<0 t)pe signal when )ou ha"e run out of P<0 mo(ules or )ou (onFt ha"e one in the first place. It is also useful in reacting to an interrupt e"ent of an) $in( but reacting at a precise Bcontrolle(C (ela)e( time perio( after the original e"ent. ;or instance it coul( be useful to chec$ for a return signal in an ultrasonic ranger. If )ou ma(e the secon( interrupt (ela) time e"en longer )ou coul( use it as a courtes) light (ela). http://www.best-microcontroller-projects.com Page 3& of 83. Effective PIC Interrupts #b"iousl) there are hun(re(s of wa)s of sol"ing these $in( of problems an( this is an e'tra techniEue which )ou coul( choose if it fits the problem. 8o create an output using this metho( use one timer interrupt an( get it going at a suitable rate e.g. &-ms. Ba goo( rate for ser"o controlC. <hen the first &-ms interrupt fires re-enable it but also set the enable flag of a secon( B(ifferentC timer mo(ule. At the same time set an output high. <hen the secon( interrupt fires set the output low an( +#48 re-enable the secon( interrupt its (one b) the first interrupt. 8his generates a pulse output high for the (uration of the secon( timer interrupt setting. 8o control the (uration of the pulse5 control the secon( timer "alue from within the first timer interrupt co(e. .) controlling this "alue using a "ariable the (uration of the pulse can be manipulate( from within the main co(e e.g. use a static "ariable in C co(e. 8his means )ou get a repeate( pulse signal at the &-ms rate (ue to the 1 st timer an( )ou also get a controlle( pulse (uration (ue to the time length of the secon( timer. http://www.best-microcontroller-projects.com Page 33 of 83. Effective PIC Interrupts :.3 "easuring t!e I)R time 8here are two easier wa)s to measure the I>7 time * using a scope or a simulator an( one more (ifficult wa) * using a timer. #ne of the easiest wa)s to measure the e'ecution time of an I>7 is to use an oscilloscope an( monitor a pin for signals set from within interrupt. Another metho( is to use a simulator. It is more laborious but it is possible to chec$ (ifferent con(itional paths within the I>7 b) setting "ariables after )ou ha"e stoppe( the simulator just at the entr) to the I>7. 8he thir( wa) is to use internal timer har(ware an( store start an( en( times of the interrupt from the timer. 8he problem then is to sen( the timer "alues out so )ou ha"e to choose from a"ailable har(ware e.g. 7>&3& or C+ etc. :.3.1 +irect Pin "onitoring 8he eas) wa) to chec$ the I>7 time is to set a pin high at the start an( low at the en( of the interrupt co(e )ou want to monitor. 8his wa) )ou can see the interrupt (uration b) measuring it (irectl) on an oscilloscope an( because setting a pin high or low uses one instruction the metho( has minimal impact on the e'ecution time of the interrupt. Note: -his ethod wi"" increase the actua" tie !ut on"y !y two instruction cyc"es. 8he (isa("antage is that )ou ha"e to ha"e a spare pin a"ailable for monitoring. :.3.2 )imulating Interrupts >imulating interrupts is (ifficult because simulators are base( on (iscrete time s)stems an( not real time actions. 8his in itself (oes not present a problem. 8he problem is that a real time e"ent can be sche(ule( some time in the future for instance at 1ms inter"als. 8o simulate this )ou woul( want a real time e"ent at the 1ms simulation time but simple (iscrete time simulators (o not allow )ou to specif) these t)pes of e"ent because the) are base( solel) on the processor5 itFs inputs an( outputs an( internal co(e operation i.e. there is usuall) no pro"ision for time( e'ternal e"ents or operation of internal har(ware peripherals. All )ou can simulate is the registers that are5 in real life5 controlle( b) the (iscrete har(ware mo(ules. 8o illustrate the problem consi(er simulating a 1ms inter"al timer with a 1$%3 signal on an e'ternal pin an( using a 60%3 main cloc$ Binstructions at 10%3 or 1us perio(C. 8his woul( mean that )ou ha"e to simulate 1--- (iscrete time inter"als i.e. 1--- c)cles of simulation time before the interrupt co(e is acti"ate( an( this also http://www.best-microcontroller-projects.com Page 36 of 83. Effective PIC Interrupts assumes that )ou can use the simulator to assign time( e"ents to processor inputs which is not possible with most of these simulators. .ut just for illustration assume that )ou can (o this. Note: -here is one way to fa#e it and that.s !y using a counter )written in ore & code* to count down the nu!er of ties the ain code "oop is e7ecuted and at the appro7iate tie )count* ca""s the interrupt code )which you have to copy as a nora" function*. -he pro!"e with this is that you are introducing "ots of code that you do not rea""y want !ecause this new code cou"d have ore new !ugs within itD Assuming that )ou (o ha"e a metho( to trigger the interrupt. >ince simulation time is "er) slow because the simulation mo(el uses co(e to simulate the actions of internal registers i.e. the whole processor. It will ta$e a long time before )ou reach the 1--- simulation (iscrete time e"ent meaning that it will ta$e so long that )ou wonFt want to bother. 9"en if it ta$es @--ms repeate( testing will mean it ta$es a "er) long time to (ebug. 8he i(eal situation is to test the target co(e BinterruptC imme(iatel). :.3.2.1 #sing Adefine "acros 8he solution is not to use the simulation time of 1---ms but to alter the co(e using C macros to trigger the interrupt co(e imme(iatel) Bafter some initiali3ation co(eC in the main part of the program. 2sing macros is con"enient because )ou can set a FH(efineF control for e'ample FH(efine 89>8OI489772P8 1F an( this woul( enable the rele"ant co(e throughout. It means )ou can place a brea$ instruction Bi.e. halt the simulatorC just before the interrupt co(e is calle( an( then setup an) registers )ou nee( to set e.g. interrupt flag registers etc to test out a specific part of the interrupt routine. >ee Chapter 11.A for an e'ample of this metho(. :.3.3 #sing Timer 8his techniEue is a more comple' wa) of measuring an interrupt time but offers the a("antages of being non intrusi"e Bno e'ternal pins are reEuire(C an( Euic$ Bonce set up itFs instant thereFs no poring o"er simulation co(e/tools to get an answerC. 8he (isa("antage is that )ou use internal memor) resources Bbut not too muchKC an( e'isting (ispla) interfaces to (o the job * It all (epen(s on what har(ware is a"ailable. Note: 6ou can a#e a very sip"e software coded seria" output at a pin and use a standard "eve" trans"ator chip to generate the re=uired +%;8; "eve"s at a 0& e.g. http://www.best-microcontroller-projects.com Page 3= of 83. Effective PIC Interrupts a A1,;8; )use the 1 version to use the sa""er 0.1uF capacitors*. 8he metho( also assumes )ou ha"e a timer running an( in most comple' co(e )ou will be using one an)wa). 9"en if )ou are not )ou can enable the timer an( not the interrupts so it (oes not affect currentl) running co(e. All )ou (o is poll the timer at the beginning an( en( of the interrupt storing these "alues Ban( assuming that the timer has not rolle( o"er i.e. passe( through 3eroC subtract the first from the secon( "alue to get the time perio( of the interrupt. In the main co(e these "alues are con"erte( to A>CII an( the result sent to )our chosen (ispla) interface. 9"en if the timer passes through 3ero5 between the first an( secon( rea(ings5 it will more often be the case that it (oes not roll o"er5 so the "alues measure( will on a"erage be the right ones. 8his is important since )ou onl) reall) want a gui(e to the interrupt time an( when )ou get the "alue out of the (e"ice )ou will see the same "alue most of the time an( this is the one to ta$e note of. Note: (t.s not worth spending tie correcting the operation of the code as it wi"" ta#e ore and ore tie to get it perfect. Bood enough is >H. :.3.3.1 2ie(ing t!e Timer 2alue #nce )ou ha"e obtaine( the timer "alue )ou nee( to (ispla) it an( hereFs two eas) har(ware interfaces to use: 7>&3& C+ In or(er to (ispla) "alues on these (e"ices )ou will nee( to output it in A>CII format an( that means translating the "alue from the t)pe in use Bprobabl) an integerC into A>CII. A commonl) use( C con"ersion routine is ltoaBC Bfoun( in st(lib.hC an( that uses the long t)pe which )ou can cast into an) other integer t)pe Bb)te5 char5 int etc.C. Note: -he "toa)* function is not inc"uded in a"" icrocontro""er copi"ers !ut it.s usefu" to #now a!out anyway !ecause in different environents e.g. on a 0& you can use it to convert any integer type to a string and it a"so a""ows you to specify the radi7 $ so it.s usefu" for conversions to he7 and !inary. 8he problem is that longFs use up more internal resources Bbigger librar) co(e is importe(C. Another factor is that the ma'imum string si3e is (epen(ent on the t)pe Ban( con"ersion ra(i'C use( so ltoaBC uses more string space i.e. when a long is con"erte( to A>CII there are more resulting (igits for the ma'imum output "alue. 8o get roun( this5 compiler manufacturers will ma$e simple small routines to (o a http://www.best-microcontroller-projects.com Page 3@ of 83. Effective PIC Interrupts specific con"ersion job e.g. .)te8o>trBC or <or(8o>trBC which are optimi3e( for each Ft)peF an( occup) less space in memor) because these routines (o not nee( to allow for an arbitrar) output string length. Note:1"" these routines )or sii"ar* can !e found on the we!, so if your copi"er anufacturer does not supp"y the <ust create a source fi"e and header fi"e and copi"e the code so you can use it $ that.s the great power of using &C you can never get rea""y stuc#. B n Error Cou "ust void Interrupts are tric$) an( I (i( ma$e a mista$e while co(ing them for this (ocument. 8he onl) reason I foun( the problem was that I was re-chec$ing the heartbeat timer interrupt co(e b) turning off the enable controls for in(i"i(ual interrupts. Duess what I turne( off enables for both timer - an( & but the 9+s still in(icate( that timer - an( & the) were still running. ,er) pu33ling since when an enable is off the interrupt shoul( not fire at all .28 loo$ing at the co(e I saw that I ha( not chec$e( for the enable being acti"e while chec$ing the interrupt flag. 8he co(e loo$e( li$e this Bwithin the I>7 itselfC : if BI48C#4 J B1SS8-I;C C T // 8- o"erflowe( ? I48C#4 JP UB1SS8-I;CL // clear timer- o"erflow bit. // ;osc/6 ' BPrescale1:1@C ' Bcount to o"erflowC P repeat rate. // &us ' 1&8 ' 131 P 1ms BC // 4ote count to o"erflow uses & when up(ating hence 133 not 131 807- P 133L // ;rom PIC 8imer - calculator. 8-timeVVL W 8he problem is that if an) other interrupt fires A4+ the flag bit of a (ifferent interrupt is high then that co(e gets actione( i.e. it loo$s li$e the other interrupt is still acti"e. 8his is true since the har(ware as mentione( alwa)s shows the interrupt state of the mo(ule using the flag bit Btimers are still acti"e e"en though their interrupt enable is offK - as long as another interrupt is firingC 8he co(e shoul( loo$ li$e this: if B I48C#4 J B1SS8-I9C C T // Int. 9nable(? if BI48C#4 J B1SS8-I;C C T // 8- o"erflowe( ? I48C#4 JP UB1SS8-I;CL // clear timer- o"erflow bit. // ;osc/6 ' BPrescale1:1@C ' Bcount to o"erflowC P repeat rate. // &us ' 1&8 ' 131 P 1ms BC http://www.best-microcontroller-projects.com Page 3A of 83. Effective PIC Interrupts // 4ote count to o"erflow uses & when up(ating hence 133 not 131 807- P 133L // ;rom PIC 8imer - calculator. 8-timeVVL W W 8he problem with this error is that it is subtle since )ou can get awa) with it if )ou (onFt nee( to (isable an interrupt BEuite commonC - the) will alwa)s be correctl) actione(. 8he problem comes if )ou tr) to turn off an interrupt Ban( )ou fin( out that )ou canFtC. 2sing the abo"e co(e sol"es the problem but remember if )ou (onFt nee( to turn off the enable Be.g. ;or a heartbeat timerC then )ou (onFt nee( the e'tra co(e * which will just increase the interrupt action time. http://www.best-microcontroller-projects.com Page 38 of 83. Effective PIC Interrupts 1< 1:F )eries Interrupts As )ou woul( e'pect from the more a("ance( 18; (e"ices the interrupt structure has been consi(erabl) enhance( compare( to the mi( range (e"ices. In fact a complete cop) of the e'isting Bmi(-range-(e"iceC interrupt s)stem gi"es )ou a completel) new feature: Prioriti!ed Interrupts. In essence it allows *ow Priority Interrupts Bjust thin$ of these as XnormalY interrupts since the) are eEui"alent to the mi( range interruptsC to be interrupte(. It a((s a complete la)er of new interrupt capabilit) onto all e'isting interrupts * ow priorit) interrupts themsel"es can now be interrupte( hence these new interrupts are calle( High Priority Interrupts. 1<.1 *ig! or Lo( Priorit& Interrupts1 Reason for #sage 2sing Prioriti3e( Interrupts is a speciali3e( concept an( is reall) for a("ance( usage so )ou probabl) wonFt nee( it for stan(ar( programs. 8he reason )ou might want to use them is when )ou ha"e built up a critical piece of co(e that either )ou are worrie( ma) not alwa)s capture an interrupt Bbecause there are too man) other interrupts all nee(ing ser"icing at the same time * since )our co(e is getting largerC or a specific interrupt is absolutel) critical an( must un(er no circumstances be misse( e.g. >afet) Critical #peration. 1<.2 *ard(are for Prioriti=ed Interrupts Note: -he new interrupt hardware is cop"ete"y !ac#wards copati!"e with id: range )high "eve"* code since there are new register contro"s to turn it off so this eans you can use e7isting code and s"ow"y transition to the new 18F hardware feature )!ut on"y if you want to*. 8o allow the priorit) mechanism to wor$ an e'tra interrupt "ector has been a((e( an( this han(les the high priorit) interrupts an( to control it there is an a((itional enable register DI9% Dlobal Interrupt 9nable for %igh Priorit) Interrupts. Note: &hec# your copi"er docuentation for e7act ip"eentation detai"s. 8his is in a((ition to the original DI9 Bor Dlobal Interrupt 9nableC which has been re-labele( DI9%/DI9 Bor Dlobal Interrupt 9nable for %igh Priorit) InterruptsC. P9I9 has become DI9 - global enable for low priorit) interrupts. DI9 has become DI9% * global enable for high priorit) interrupts. http://www.best-microcontroller-projects.com Page 3: of 83. Effective PIC Interrupts 6iagra of interrupt hardware in a typical 57. series device 0e1cerpt fro 57.899: data sheet docuent ;<=;8$4 1<.3 Prioriti=ed Interrupt "ec!anism In the mi(-range (e"ices such as 1@; or 1&; etc )ou can onl) prioriti3e an interrupt in a limite( wa) an( that is to place the interrupt that )ou want e'ecute( first in the I>7 at the start of the interrupt routine * this wa) if the http://www.best-microcontroller-projects.com Page 6- of 83. Effective PIC Interrupts associate( interrupt fires then )ou $now that the I>7 will e'ecute that interrupt first. Prioriti3e( interrupts in the 18; series wor$ on the ph)sical har(ware le"el an( a low priorit) interrupt can itself be interrupte( b) a high priorit) interrupt. 8he mechanism wor$s since there are two ph)sical har(ware interrupts so )ou will nee( two high le"el interrupt functions to ser"ice each of these "ectors. 8he two interrupt "ectors ha"e the following a((resses: ow priorit) interrupt "ector at : ----18h Bnormal use interruptC %igh priorit) interrupt "ector at : -----8h 8he important point is that a high priorit) interrupt can e'ecute e"en while a low priorit) interrupt is e'ecuting i.e. the lower Be'ecutingC interrupt can be o"erri((en b) the higher priorit) interrupt. In the mi(-range (e"ices the main interrupt can ne"er be interrupte( an( e"er)thing has to stop an( wait until the interrupt co(e BI>7C is finishe( an( until e'it from the I>7. .ut in the same wa) that a normal Bmi(-range (e"iceC interrupt stops the main co(e wor$ing an( branches to the I>7 so the high priorit) interrupt will stop the low priorit) interrupt until the high priorit) interrupt has finishe(. It is a neste( interrupt structure operating in har(ware. 9ach of the interrupt sources Bi.e. an) of the sources of interrupts within the 18; (e"iceC has an enable bit to allow it to become a high priorit) interrupt so )ou can (eci(e whether or not to ma$e each interrupt a high priorit) interrupt or a low priorit) interrupt. Note: -his is a design decision and you shou"d assign high priority to those interrupts that a!so"ute"y ust not !e issed i.e. critica" ones. 1<.$ Priorit& Enable Control 4it /bac-(ards compatibilit&0 #"erall control of the priorit) interrupt mechanism is set b) using the IP94 bit in the 7C#4 register. .it A is the IP94 or Interrupt Priorit) E,able bit an( when set it enables priorit) interrupts which means that an) of the interrupt sources within the 18; (e"ice can be prioriti3e(. <hen IP94 is reset to 3ero the (e"ice interrupt s)stem is compatible with the mi(-range PIC (e"ices i.e. prioriti3e( interrupts are off i.e. the interrupt structure beha"es in the same wa) as for the mi( range (e"ice interrupt s)stem meaning the interrupt har(ware loo$s as though there is onl) a single interrupt "ector. http://www.best-microcontroller-projects.com Page 61 of 83. Effective PIC Interrupts 1<.' 1:F )eries Registers As with the mi( range (e"ices the 18; series still has the PI7 an( PI9 registers an( these wor$ in e'actl) the same wa) as the mi( range (e"ices but in a((ition to these the 18; series also has an Interrupt Priorit) 9nable register B8he IP9 registersC. 8he registers that control interrupts are: PI7 - Peripheral Interrupt 7eEuest B;lagC. PI9 - Peripheral Interrupt 9nable. IP9 - Interrupt Priorit) 9nable. A((itional interrupt control bits are hel( in I48C#4 I48C#4 : #riginal interrupts the same as the mi(-range (e"ices V e'tras. Note: (n the sae way that soe origina" interrupts are "ocated in the (N-&>N register, e7tra (N-&>N registers are avai"a!"e (N-&>N; I (N-&>N8. -hese house the new e7terna" interrupt contro"s )!oth ena!"e and F"ag !its* !ut in addition they a"so house the priority contro" !its )(0?* for these new interrupts and new"y created priority !its for the origina" interrupts )(0?*. %ere is a list of registers associate( with interrupts 7C#4 I48C#45 I48C#4&5 I48C#43 PI715 PI7& PI915 PI9& IP715 IP7& Bfrom 18;&==- (atasheetC 1<.. 1:F Conte3t )aving 7ecall that for mi( range (e"ices onl) the program counter BPCC is sa"e( on the stac$ B>ee Chapter @.6C. In the 18; series )ou can also ha"e the <79D5 >8A82> an( .>7 registers sa"e( but onl) if )ou use a fast return from interrupt. If )ou (onFt use a fast return from interrupt )ou ma) nee( to sa"e <79D5 >8A82> an( .>7 using )our own co(e. Note: 6ou sti"" have to !e carefu" as you ay need to save other registers anyway. http://www.best-microcontroller-projects.com Page 6& of 83. Effective PIC Interrupts 1<...1 Fast Register )tac- 8he ;ast 7eturn stac$ is specificall) for use in interrupts Bbut see laterC an( sa"es <79D5 >8A82> an( .>7. 8he problem is that it is onl) one le"el (eep so )ou ha"e to be careful with it when using the priorit) interrupt mechanism since if two interrupts are triggere( Bone low priorit) an( one highC then the fast stac$ will be o"erwritten * in that case )ou ha"e to a manuall) control sa"ing the register "alues. Warning> ItFs best not to use the fast return stac$ if both high an( low priorit) interrupts are acti"e since the f-r-s is onl) one le"el (eep * the secon( interrupt will o"erwrite the fast return stac$ "aluesK Iou will nee( to chec$ )our compiler (ocumentation Ban( possibl) anal)3e the co(e outputC to chec$ e'actl) what )our compiler (oes with the stac$ i.e. whether or not it ta$es care of conte't sa"ing when using prioriti3e( interrupts. If fast stac$ an( priorit) interrupts are enable( the (uring the low priorit) interrupt )ou must sa"e the <79D5>8A82> an( .>7 since these will be the ones o"erwritten b) a high priorit) interrupt e"ent. 1<...1.1 #sing t!e Fast Register )tac- for normal function calls If interrupts are not use( then )ou can use the fast return stac$ (uring normal function calls * Bprobabl) (ifficult in a high le"el compiler an( woul( be easier in machine co(e/assemblerC. 8o (o this in assembler )ou woul( call the function as follows: CA ;unc15 ;A>8 8o return from the function use: 798274 ;A>8 11 E3amples 11.1 *ard(are D )oft(are 11.1.1 *ard(are 8o run the e'ample co(e the har(ware is $ept to a minimum. All )ou nee( is: An IC>P programmer. A PIC 1@;88 18;&==- or an) similar 18; (e"ice Ba(just setup as necessar)C. http://www.best-microcontroller-projects.com Page 63 of 83. Effective PIC Interrupts 0AM&3&A Bthe A "ersion uses -.1u; pol)ester not 1u; electrol)tic so it is easierC. =, power suppl) P>2 (ecoupling capacitor 1-u; electrol)tic. 1 (ecoupling capacitor -.1u; Battache( close to power J groun( on 1@;88C 6 0AM&3& capacitors -.1u; 3 1$ resistors 3 9+s. >ol(erless brea(boar(. >oli( core sheathe( connection wire. <ire strippers. A PC. >erial cable 4ull mo(em Bstraight through * no crosso"erC for 7>&3&. : wa) female +-t)pe Bconnects to PC serial portC. 11.1.2 )erial port configuration .au(: :@-- +ata: 8 bits Parit): 4one >top bits: 1 ;low control: 4one http://www.best-microcontroller-projects.com Page 66 of 83. Effective PIC Interrupts 11.1.3 1.F:: *ard(are +iagram http://www.best-microcontroller-projects.com Page 6= of 83. Effective PIC Interrupts 11.1.$ 1:F2''< *ard(are +iagram 11.1.' )oft(are +o(nloads 11.1.'.1 C Compiler do(nload Compiler : 0i$roC (ownloa( : http://www.mi$roe.com/en/compilers/mi$roc/pic/(ownloa(.htm 11.1.'.2 ICPR79 +ownloa( ICP7#D here : http://www.ic-prog.com/in(e'1.htm Iou nee( the ICP7#D programming software an( the 0i$roC C compiler Balthough the e'amples come with precompile( he' file so if )ou are not going to change the co(e then )ou wonFt nee( the compilerC * the compiler is free for the small http://www.best-microcontroller-projects.com Page 6@ of 83. Effective PIC Interrupts amounts of co(e use( in these e'amples.. Programmer >oftware : ICP7#D >ee notes on site for setup instructions. #n web page: http://www.best-microcontroller-projects.com/c-programming-tutorial-setup.html 11.1.'.3 %inPic /for t!e 1:F2''< and man& ot!ers0 Although I mainl) use ICP7#D it (oes not ha"e regular up(ates an( (oes not cater for the 18;&==-. 8here is a program that is up(ate( much more regularl) an( is just as goo( as an( itFs calle( <inPic. Note: (&0+>B does have soe supported 18F devices so chec# those out !efore changing to new software e.g. (f you use the popu"ar 18F;/;. (A0>+-1N-: (f you do have (&0+>B running and then start up 2in0ic you ay need to re!oot your coputer since (&0+>B ay not re"ease the ports )90- 0>+-* and it wi"" appear that 2in0ic is not running reading or writing. +e!oot wi"" so"ve thisD <inPic caters for man) (ifferent interfaces an( I thin$ )ou can e"en specif) an unsupporte( programming interface "ia a configuration file so )ou are guarantee( to ma$e )our programmer wor$ using this software. 8hereFs also a lot of information on the website on how to configure an( use it. ;ortunatel) it has an A4=8: programming interface Bparallel portC that I use so it was a matter of selecting that interface an( just using the program (irectl) in place of ICP7#D. -(0: 2hen prograing )<ust !efore hitting the prograing !utton* c"ic# the ta! "a!e"ed JAessagesK as this wi"" then show you how the progra is progressing $ otherwise it "oo#s "i#e the progra is hung. Note: -here are severa" versions with this )or a sii"ar nae* so down"oad your version fro : fro www.=s".netFd"@yhf )Note: %ii"ar"y to (&0+>B, 2in0ic is free*. -(0: 1""ow the configuration to !e prograed when prograing the 18F;//0 $ it does return a prograing fai"ed error !ecause it does not read !ac# the prograed va"ue proper"y so don.t worry a!out that $ if anyone finds out why )p"us the so"ution* drop e an eai" and (."" update the e!oo# $ than#s. 11.2 Interrupt Template Note: -his techni=ue can !e adapted to any systeFdevice. 8his co(e is e'tremel) boring but I guess thatFs whatFs nee(e( as a template. http://www.best-microcontroller-projects.com Page 6A of 83. Effective PIC Interrupts 11.2.1 Interrupt Template Code ction Note: ?ven f"ashing the 9?3 is tota""y unnecessary !ut hey $ it.s got to do soethingD 11.2.2 Interrupt Template C Code FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FF FF Fi"e: 15F88:interrupt:tep"ate.c FF FF 1uthor: L F Aain. FF FF 3escription: FF FF (nterrupt -ep"ate &ode FF FF &opi"er : i#ro&, i#ro?"e#troni#a & copi"er FF for Aicrochip 0(& icrocontro""ers FF Version: 8.;.0.0 FF FF Note -esting: FF FF -ested on 15F88 FF FF +e=uireents: FF FF &"oc# : 8AHz )(nterna"* FF FF -arget : 15F88 FF FF Version: FF 1.00 : (nitia" re"ease. FF FF &opyright : &opyright M Lohn Aain ;008 FF http:FFwww.!est:icrocontro""er:pro<ects.co FF For use on"y if purchased with e!oo# FF N0(& (nterrupt %ecretsN FF avai"a!"e fro we!site a!ove. FF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF Oinc"ude N!it.hN FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FF 3efines FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF http://www.best-microcontroller-projects.com Page 68 of 83. Effective PIC Interrupts FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FF fi"e scope varia!"es FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF static unsigned "ong -1tieE0C FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF void init)void* P >%&&>N E 07'0C FF !5..@ E 110 E @AHz, 111 E 8AHz 1N%?9 E 0C FF a"" 13& pins to digita" (F> FF -ier 1 -1&>N E )1QQ-A+1>N*C R FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF void initSports)void* P 0>+-1 E 0C -+(%1 E 0C FF 0EoFp. 0>+-4 E 0C -+(%4 E 0C FF 0EoFp. R FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF void ena!"eSinterrupts)void* P FF (nterrupt ena!"e. -A+1 0(?1 E 0700C 0(?1 TE )1QQ-A+1(?*C FF B"o!a" I 0eriphera" interrupt ena!"e. (N-&>N TE )1QQB(?* T )1QQ0?(?*C R FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF void disa!"eSinterrupts)void* P (N-&>N IE U)1QQB(?*C FF disa!"e interrupts R FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF void -ier1Saction)void* P static unsigned "ong t E 0C http://www.best-microcontroller-projects.com Page 6: of 83. Effective PIC Interrupts static unsigned char 9?3 E 0C if)tEE0* P FF restart tie count t E -1tieC R e"se P FF togg"e de"ay if ) )-1tie : t*VE/00 * P 9?3 E U9?3C if )9?3* set4it)0>+-1,0*C e"se res4it)0>+-1,0*C t E 0C FF start a new tie count R R R FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FF %tart here FF void ain)* P initSports)*C init)*C ena!"eSinterrupts)*C whi"e)1* -ier1Saction)*C R FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF void interrupt)void* P FF -ier 1 if ) 0(?1 I )1QQ-A+1(?* * P FF (nt. ?na!"edW if )0(+1 I )1QQ-A+1(F* * P FF -1 overf"owed W 0(+1 IE U)1QQ-A+1(F*C FF c"ear tier1 overf"ow !it. -A+19 E @8C -A+1H E ;@8C -1tieXXC R R FF Note B(? set !y +?-F(? instruction )see asse!"er output*. R http://www.best-microcontroller-projects.com Page =- of 83. Effective PIC Interrupts 11.3 1.F *eartbeat Timer Note: -his techni=ue can !e adapted to any systeFdevice. 8his co(e (emonstrates using three timersL 8imer -5 8imer 1 an( 8imer & using each to generate a 1ms interrupt heartbeat cloc$ Bthese are not s)nchroni3e( to each otherC. Note: (n practice you wou"d use on"y one tier for the heart!eat tier and they are presented here so that you can choose one fro any of the three avai"a!"e tiers. A heartbeat timer is useful in most co(e because it allows )ou to time an)thing without loosing time in a wasteful (ela) loop since while the timer is counting in the bac$groun( for )ou the processor can get on with other useful tas$s. In the co(e )ou coul( also create an arra) of count(own "ariables up(ate( in the interrupt an( ma)be actione( in the interrupt to (o a specific tas$ when the) e'pire an( in this wa) )ou can create man) timers using onl) one main interrupt timer * all )ou are (oing is using up 7A0 an( a little processing time. 8he other metho( Bfor less accurate timing e.g. A $e)boar( bounce timerC where timing is not critical is for the main co(e to perio(icall) loo$ at the timer "alue an( compare it to a store( one an( this is shown in the co(e below. If the "alue is abo"e a set limit then the "ariable is reset an( an action is ta$en * in this case toggling a port bit. 11.3.1 1.F *eartbeat Timer Code ction P#78A is use( to (ispla) the actions for each interrupt * an( each port bit is connecte( to a forwar( biase( 9+ to groun( "ia a 1$ resistor using a 33-#hm resistor if )ou want to but 1$ wor$s well enough for test wor$C. 8he onl) other connections to the 1@;88 are V=, an( D4+ an( the 6 IC>P programmer connections Bleft permanentl) connecte( for this testC. 7A- * 8he pin is toggle( at each =--ms inter"al using interrupt 8I097- 7A1 - 8he pin is toggle( at each &=-ms inter"al using interrupt 8I0971 7A& - 8he pin is toggle( at each 1&=ms inter"al using interrupt 8I097& 8his allows )ou to chec$ the action of each. Note: -urning off individua" interrupt !its wi"" prove that each interrupt is wor#ing as e7pected. 11.3.2 16F Heart Beat Timer C Code ////////////////////////////////////////////////////////////////////// http://www.best-microcontroller-projects.com Page =1 of 83. Effective PIC Interrupts // // ;ile: 1@;88-heartbeat-timer.c // // Author: / ; 0ain. // // +escription: // // 1ms %eartbeat 8imer Interrupt Co(e. // // 2sing 8imer- or 8imer1 or 8imer&. // // Compiler : mi$roC5 mi$ro9le$troni$a C compiler // for 0icrochip PIC microcontrollers // ,ersion: 8.&.-.- // // 4ote 8esting: // // 8este( on 1@;88 // // 7eEuirements: // // Cloc$ : 80%3 BInternalC // // 8arget : 1@;88 // // ,ersion: // 1.-- - Initial release. // // Cop)right : Cop)right 1 /ohn 0ain &--8 // http://www.best-microcontroller-projects.com // ;or use onl) if purchase( with eboo$ // ZPIC Interrupt >ecretsZ // a"ailable from website abo"e. // ////////////////////////////////////////////////////////////////////// Hinclu(e Zbit.hZ ////////////////////////////////////////////////////////////////////// // +efines ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // file scope "ariables ////////////////////////////////////////////////////////////////////// static unsigne( long 8-timeP-5 81timeP-5 8&timeP-L http://www.best-microcontroller-projects.com Page =& of 83. Effective PIC Interrupts ////////////////////////////////////////////////////////////////////// "oi( initB"oi(C T #>CC#4 P -'A-L // b@..6 P 11- P 60%35 111 P 80%3 A4>9 P -L // all A+C pins to (igital I/# // 8imer - // DPP2 bA P 1 : Pullups (isable( B1C. // I489+D b@ P - : Interrupt e(ge P low to high B-C. // 8-C> b= P - : Cloc$ select Internal ;osc/6 B-C. // 8->9 b6 P - : 8imer - e(ge low to high B-C. // P>A b3 P - : Prescaler assigne( to <+8 B1C 8imer- B-C. // P> b&..- P 11- : PrescaleP1:1&8 Bnote P>P--[ 1:& for 807-C. // --- P 1:& // --1 P 1:6 // -11 P 1:1@ #P8I#4O79D P -'--L #P8I#4O79D \P -'-3L //prescale 1:1@ #P8I#4O79D \P B1SSACL //pullups off // 8imer 1 81C#4 P B1SS8071#4CL // 8imer & P7&P&6:L // postscale P 1:&5 #4 5 prescale P 1:6 8&C#4 P B-'-1SS3C \ B1SS807C \ -'-1L W ////////////////////////////////////////////////////////////////////// "oi( initOportsB"oi(C T P#78A P -L 87I>A P -L // -Po/p. P#78. P -L 87I>. P -L // -Po/p. W ////////////////////////////////////////////////////////////////////// "oi( enableOinterruptsB"oi(C T // 8imer - :#sc off5 Internal cl$5 #n53ero 8-I; I48C#4 P B1SS8-I9CL http://www.best-microcontroller-projects.com Page =3 of 83. Effective PIC Interrupts // Interrupt enable. 8071 PI91 P -'--L PI91 \P B1SS8071I9CL PI91 \P B1SS807&I9CL // Dlobal J Peripheral interrupt enable. I48C#4 \P B1SSDI9C \ B1SSP9I9CL W ////////////////////////////////////////////////////////////////////// "oi( (isableOinterruptsB"oi(C T I48C#4 JP UB1SSDI9CL // (isable interrupts W ////////////////////////////////////////////////////////////////////// "oi( 8imer-OactionB"oi(C T static unsigne( long t P -L static unsigne( char 9+ P -L ifBtPP-C T // restart time count t P 8-timeL W else T // toggle (ela) if B B8-time - tC[P=-- C T 9+ P U9+L if B9+C set.itBP#78A5-CL else res.itBP#78A5-CL t P -L // start a new time count W W W ////////////////////////////////////////////////////////////////////// "oi( 8imer1OactionB"oi(C T static unsigne( long t P -L static unsigne( char 9+ P -L ifBtPP-C T // restart time count t P 81timeL W else T // toggle (ela) if B B81time - tC[P&=- C T 9+ P U9+L if B9+C set.itBP#78A51CL else res.itBP#78A51CL t P -L // start a new time count W W http://www.best-microcontroller-projects.com Page =6 of 83. Effective PIC Interrupts W ////////////////////////////////////////////////////////////////////// "oi( 8imer&OactionB"oi(C T static unsigne( long t P -L static unsigne( char 9+ P -L ifBtPP-C T // restart time count t P 8&timeL W else T // toggle (ela) if B B8&time - tC[P1&= C T 9+ P U9+L if B9+C set.itBP#78A5&CL else res.itBP#78A5&CL t P -L // start a new time count W W W //////////////////////////////////////////////////////////////////////// // >tart here // "oi( mainBC T initOportsBCL initBCL enableOinterruptsBCL whileB1C T // infinite loop. 8imer-OactionBCL 8imer1OactionBCL 8imer&OactionBCL W W //////////////////////////////////////////////////////////////////////// "oi( interruptB"oi(C T // 8imer - if B I48C#4 J B1SS8-I9C C T // Int. 9nable(? if BI48C#4 J B1SS8-I;C C T // 8- o"erflowe( ? I48C#4 JP UB1SS8-I;CL // clear timer- o"erflow bit. http://www.best-microcontroller-projects.com Page == of 83. Effective PIC Interrupts // ;osc/6 ' BPrescale1:1@C ' Bcount to o"erflowC P repeat rate. // &us ' 1&8 ' 131 P 1ms BC // 4ote count to o"erflow uses & when up(ating hence 133 not 131 807- P 133L // ;rom PIC 8imer - calculator. 8-timeVVL W W // 8imer 1 if B PI91 J B1SS8071I9C C T // Int. 9nable(? if BPI71 J B1SS8071I;C C T // 81 o"erflowe( ? PI71 JP UB1SS8071I;CL // clear timer1 o"erflow bit. 8071 P 68L 8071% P &68L 81timeVVL W W // 8imer & if B PI91 J B1SS807&I9C C T // Int. 9nable(? if BPI71 J B1SS807&I;C C T // 81 o"erflowe( ? PI71 JP UB1SS807&I;CL // clear timer1 o"erflow bit. 8&timeVVL W W // 4ote DI9 set b) 798;I9 instruction Bsee assembler outputC. W 11.$ Transmit Interrupts /no code but some important information0. Although this (ocument (oes not show 8ransmit Interrupts Bthe) are just the mirror image of the recei"e an( so are "er) eas) to set up i.e. a goo( e'ercise for )ouC there is an a("antage to using them. Consi(er when )ou (onFt use interruptsL what )ou will (o is transmit a message http://www.best-microcontroller-projects.com Page =@ of 83. Effective PIC Interrupts to the serial port one b)te at a time but thin$ about this * the transmit har(ware can onl) go as fast as the bau( rate )ou ha"e selecte( for the transmitter whether that is :@-- bau(5 1&-- bau( or =@---- bau(. 8his has an impact on )our co(e since )ou can not o"erwrite the output buffer Bthere is onl) one output bufferC until the (ata has been transmitte( i.e. I#2 02>8 <AI8. <ithout interrupts )ou ha"e to wait b) using a fi'e( BwastefulC (ela) an( thatFs where interrupts come in han(). 8his is because the transmit interrupt har(ware can interrupt the software to sa) X)es IF"e transmitte( the b)te5 gi"e me another pleaseY - thereFs no wasteful (ela)s * all )ou (o is gi"e )our transmit routine a string of (ata an( the interrupts will reEuest the ne't b)te from it. <hen the buffer is empt) a flag can in(icate to the main co(e that the string was transmitte( an( itFs rea() for the ne't one. 11.' R)232 Interrupt Reception Note: -his techni=ue can !e adapted to any systeFdevice. Note: Use Hyperterina" on the 0& and setup the paraeters shown here: %eria" port configuration &hapter 11.1.;. 11.'.1 1.F R)232 Interrupt Reception Code ction 8he co(e uses the same 8imer1 Interrupt to show acti"it) on an 9+ at 7A-. <hen a $e) is hit on the PC terminal the 7A& 9+ is flashe( to show reception of (ata. In a((ition the 7ecei"e( (ata is loope( bac$ to the transmit 7>&3& output to show information on the PC terminal i.e. it shows the A>CII $e) that was originall) presse( at the PC terminal. 11.'.2 1.F R)232 Interrupt Reception C Code ////////////////////////////////////////////////////////////////////// // // ;ile: 1@;88-rs&3&-r'.c // // Author: / ; 0ain. // // +escription: // // 7ecei"e 7>&3& Interrupt Co(e. // // 7ecei"e (ata is obtaine( "ia interrupt // an( re-transmitte( bac$ to the 7>&3& port // in the main loop co(e. http://www.best-microcontroller-projects.com Page =A of 83. Effective PIC Interrupts // // Compiler : mi$roC5 mi$ro9le$troni$a C compiler // for 0icrochip PIC microcontrollers // ,ersion: 8.&.-.- // // 4ote 8esting: // // 8este( on 1@;88 // // 7eEuirements: // // Cloc$ : 60%3 BInternalC // // 8arget : 1@;88 // // ,ersion: // 1.-- - Initial release. // // Cop)right : Cop)right 1 /ohn 0ain &--8 // http://www.best-microcontroller-projects.com // ;or use onl) if purchase( with eboo$ // ZPIC Interrupt >ecretsZ // a"ailable from website abo"e. // ////////////////////////////////////////////////////////////////////// Hinclu(e Zbit.hZ Hinclu(e ZusartOsupport.hZ ////////////////////////////////////////////////////////////////////// // +efines ////////////////////////////////////////////////////////////////////// H(efine 0AMOI49 @- ////////////////////////////////////////////////////////////////////// // file scope "ariables ////////////////////////////////////////////////////////////////////// static unsigne( char r'O(ata P -L static unsigne( long 81timeP-L ////////////////////////////////////////////////////////////////////// "oi( initB"oi(C T #>CC#4 P -'@-L // b@..6 P 11- P 60%35 111 P 80%3 A4>9 P -L // all A+C pins to (igital I/# // 8imer - http://www.best-microcontroller-projects.com Page =8 of 83. Effective PIC Interrupts // DPP2 bA P 1 : Pullups (isable( B1C. // I489+D b@ P - : Interrupt e(ge P low to high B-C. // 8-C> b= P - : Cloc$ select Internal ;osc/6 B-C. // 8->9 b6 P - : 8imer - e(ge low to high B-C. // P>A b3 P - : Prescaler assigne( to <+8 B1C 8imer- B-C. // P> b&..- P 11- : PrescaleP1:1&8 Bnote P>P--[ 1:& for 807-C. #P8I#4O79D P B1SSACL
// 8imer 1 81C#4 P B1SS8071#4CL W ////////////////////////////////////////////////////////////////////// "oi( initOportsB"oi(C T P#78A P -L 87I>A P -L // -Po/p. P#78. P -L 87I>. P -L // -Po/p. W ////////////////////////////////////////////////////////////////////// "oi( enableOinterruptsB"oi(C T PI91 P -'--L
// Interrupt enable. 7>&3& 7M PI91 \P B1SS7CI9CL
// Interrupt enable. 8071 PI91 \P B1SS8071I9CL // Dlobal J Peripheral interrupt enable. I48C#4 \P B1SSDI9C \ B1SSP9I9CL W ////////////////////////////////////////////////////////////////////// "oi( (isableOinterruptsB"oi(C T I48C#4 JP UB1SSDI9CL // (isable interrupts W ////////////////////////////////////////////////////////////////////// "oi( 8imer1OactionB"oi(C T static unsigne( long t P -L static unsigne( char 9+ P -L http://www.best-microcontroller-projects.com Page =: of 83. Effective PIC Interrupts ifBtPP-C T // restart time count t P 81timeL W else T // toggle (ela) if B B81time - tC[P=-- C T 9+ P U9+L if B9+C set.itBP#78A5-CL else res.itBP#78A5-CL t P -L // start a new time count W W W //////////////////////////////////////////////////////////////////////// // >tart here // "oi( mainBC T unsigne( short $e) L // 4ew $e) (etect. unsigne( short blin$cP- L // .lin$ toggle. char op]6^ L // >cratch area. unsigne( char cP0AMOI49L initOportsBCL initBCL
// 2se internal 2>A78 : // et the compiler ta$e care // of te(ious register initiali3ation. 2>A78OInitB:@--CL (ela)OmsB1--CL //let hw settle. enableOinterruptsBCL 2>A78OPrintBZ_n_n_rhttp://www..est-0icrocontroller-Projects.comZCL forBLLC T // 8ransmit (ata if it is recei"e( if Br'O(ataC T .)te8o>trBr'O(ata5opCL 2>A78OPrintBZ_r_n7M: ZCL 2>A78OPrintBopCL 2>A78OchrB3&CL 2>A78OchrBr'O(ataCL r'O(ata P -L // consume the (ata. http://www.best-microcontroller-projects.com Page @- of 83. Effective PIC Interrupts
// ;lash an 9+ to show +ata 7M set.itBP#78A5&CL (ela)OmsB1--CL res.itBP#78A5&CL
W else T if BcVVPP0AMOI49C T 2>A78OPrintlnBZZCL 2>A78OPrintBZ4# +A8AZCL cP-L W else 2>A78OPrintBZ.ZCL W W // Infinite loop. W //////////////////////////////////////////////////////////////////////// "oi( interruptB"oi(C T // 7>&3& 7ecei"e Interrupt if B PI91 J B1SS7CI9C C T if BPI71 J B1SS7CI;C C T // 7M +ata ? PI71 JP UB1SS7CI;CL // clear flag - re enable ints r'O(ata P 7C79DL W W
// 8imer 1 if B PI91 J B1SS8071I9C C T // Int. 9nable(? if BPI71 J B1SS8071I;C C T // 81 o"erflowe( ? PI71 JP UB1SS8071I;CL // clear timer1 o"erflow bit. 8071 P 68L 8071% P &68L 81timeVVL
8imer1OactionBCL W W
W http://www.best-microcontroller-projects.com Page @1 of 83. Effective PIC Interrupts 11.. )imple Flag E3ample Note: -his techni=ue can !e adapted to any systeFdevice. 11...1 1.F )imple Flag Interrupt Code ction As with the other e'amples three 9+ are use( to in(icate status an( attache( in(i"i(uall) "ia 1-$ resistor to groun(. In this case: 7A- is an interrupt (ri"en ali"e in(icator at =--ms perio(. 7A1 in(icates a calculation is being ma(e as a result of being Fflagge(F 7A& is a loop generate ali"e in(icator Bstops (uring calculationKC. 8his co(e is onl) s$eleton co(e Bto show )ou the i(eaC an( not a real e'ample see Chapter 8.1 for an appropriate use of this co(e. It (oes howe"er illustrate the fact that interrupts continue while main co(e is hel( up since the flashing 9+ on 7A& is stoppe( while the FcalculationF is (one * (uring this calculation 7A- continues toggling as if nothing has happene(. 11...2 1.F )imple Flag Interrupt C Code ////////////////////////////////////////////////////////////////////// // // ;ile: 1@;88-interrupt-flag-e'ample.c // // Author: / ; 0ain. // // +escription: // // ;lag Co(e 8o +elegate Processing to 0ain co(e // // Compiler : mi$roC5 mi$ro9le$troni$a C compiler // for 0icrochip PIC microcontrollers // ,ersion: 8.&.-.- // // 4ote 8esting: // // 8este( on 1@;88 // // 7eEuirements: // // Cloc$ : 80%3 BInternalC // // 8arget : 1@;88 http://www.best-microcontroller-projects.com Page @& of 83. Effective PIC Interrupts // // ,ersion: // 1.-- - Initial release. // // Cop)right : Cop)right 1 /ohn 0ain &--8 // http://www.best-microcontroller-projects.com // ;or use onl) if purchase( with eboo$ // ZPIC Interrupt >ecretsZ // a"ailable from website abo"e. // ////////////////////////////////////////////////////////////////////// Hinclu(e Zbit.hZ ////////////////////////////////////////////////////////////////////// // +efines ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // file scope "ariables ////////////////////////////////////////////////////////////////////// static unsigne( long 81timeP-L static unsigne( char m)flagP-L ////////////////////////////////////////////////////////////////////// "oi( initB"oi(C T #>CC#4 P -'A-L // b@..6 P 11- P 60%35 111 P 80%3 A4>9 P -L // all A+C pins to (igital I/# // 8imer 1 81C#4 P B1SS8071#4CL W ////////////////////////////////////////////////////////////////////// "oi( initOportsB"oi(C T P#78A P -L 87I>A P -L // -Po/p. P#78. P -L 87I>. P -L // -Po/p. W ////////////////////////////////////////////////////////////////////// "oi( enableOinterruptsB"oi(C T http://www.best-microcontroller-projects.com Page @3 of 83. Effective PIC Interrupts // Interrupt enable. 8071 PI91 P -'--L PI91 \P B1SS8071I9CL // Dlobal J Peripheral interrupt enable. I48C#4 \P B1SSDI9C \ B1SSP9I9CL W ////////////////////////////////////////////////////////////////////// "oi( (isableOinterruptsB"oi(C T I48C#4 JP UB1SSDI9CL // (isable interrupts W ////////////////////////////////////////////////////////////////////// "oi( 8imer1OactionB"oi(C T static unsigne( long t P -L static unsigne( char 9+ P -L ifBtPP-C T // restart time count t P 81timeL W else T // toggle (ela) if B B81time - tC[P&=- C T 9+ P U9+L if B9+C set.itBP#78A5-CL else res.itBP#78A5-CL t P -L // start a new time count W W W ////////////////////////////////////////////////////////////////////// "oi( (oOcalcB"oi(C T (ela)OmsB1&--CL // Preten( (oing something comple'. W //////////////////////////////////////////////////////////////////////// // >tart here // "oi( mainBC T float ( P -5 r P -L signe( char c5resL int iL initOportsBCL http://www.best-microcontroller-projects.com Page @6 of 83. Effective PIC Interrupts initBCL enableOinterruptsBCL whileB1C T // infinite loop. (ela)OmsB&--CL set.itBP#78A5&CL (ela)OmsB&--CL res.itBP#78A5&CL if Bm)flagC T m)flag P -L set.itBP#78A51CL (oOcalcBCL res.itBP#78A51CL W W W //////////////////////////////////////////////////////////////////////// "oi( interruptB"oi(C T static unsigne( long tP-L // 8imer 1 if B PI91 J B1SS8071I9C C T // Int. 9nable(? if BPI71 J B1SS8071I;C C T // 81 o"erflowe( ? PI71 JP UB1SS8071I;CL // clear timer1 o"erflow bit. 8071 P 68L 8071% P &68L 81timeVVL // Call (elegate( co(e // e"er) 3 secon(s if BKm)flag JJ B81time-tC[P3---C T m)flag P 1L tP81timeL W // Ali"e in(icator 8imer1OactionBCL W W http://www.best-microcontroller-projects.com Page @= of 83. Effective PIC Interrupts // 4ote DI9 set b) 798;I9 instruction Bsee assembler outputC. W 11.5 Interrupt )imulation using "acros Note: -his techni=ue can !e adapted to any systeFdevice. 11.5.1 1.F Interrupt )imulation Code ction Iou can test interrupt co(e b) cheating an( using the built in pre-processor i.e. using H(efine macro (irecti"es. 8he pre-processor wor$s as the name suggests before the program is compile( an( )ou can use it to hi(e or re"eal sections of co(e. In this case )ou nee( to change the co(e to present a FrealF interrupt Bfor use in the har(wareC an( when simulating )ou nee( a Ffa$e interruptF routine. 8he processing macros let )ou control the sections of co(e ma(e a"ailable for use (epen(ing on a H(efine (irecti"e. 8he best wa) to e'plain this is to wor$ through the affecte( sections of pre-processor (irecti"es. 8he first section is the control Bwhich )ou place at the topmost file le"el or e"en in a top le"el hea(er file if there are multiple files in the projectC: ////////////////////////////////////////////////////////////////////// // comment out the following H(efine to stop simulating the macro // Ban( 79C#0PI9C // H(efine >I02A89OI489772P8 1 8his pre-processor (efines a pre-processing macro "ariable labele( >I02A89OI489772P8. /umping to the en( of co(e )ou ha"e: //////////////////////////////////////////////////////////////////////// Hif(ef >I02A89OI489772P8 // Compiler complains if interrupt calle( so rename it "oi( OinterruptB"oi(C T Helse "oi( interruptB"oi(C T Hen(if 8his sa)s that when the macro "ariable >I02A89OI489772P8 is (efine( then the http://www.best-microcontroller-projects.com Page @@ of 83. Effective PIC Interrupts function is (eclare( as: B"oi(C OinterruptB"oi(C T ...an( when not (eclare( )ou ha"e: "oi( interruptB"oi(C T ...so when not (eclare( )ou ha"e the real interrupt (eclaration an( when (eclare( )ou ha"e the interrupt simulation co(e. ItFs (one li$e this since the compiler will not allow the special $e)wor( FinterruptF to be calle( an)where in the program so itFs is change( to Ointerrupt which it (oes allow. In the main part of the co(e )ou ha"e: initOportsBCL initBCL enableOinterruptsBCL
/////////////////////////// // +ebug co(e Hif(ef >I02A89OI489772P8 whileB1C T PI71 P B1SS8071I;CL OinterruptBCL // call the interrupt (irectl) after initiali3ation W Hen(if // 9n( of +ebug Co(e /////////////////////////// 8he (ebug co(e is place( after initiali3ation co(e an( before an) other main co(e Bwhich is not e'ecute( while simulating interruptsC. 8he (ebug co(e sets a flag Bsimulating the har(ware mo(ule an( )ou can set a brea$point on the ne't line at FOinterruptF an( step into the interrupt co(e itself so that )ou can anal)3e what is going on in the interrupt. Note: (f you don.t use this ethod then then there is no way that the interrupt code wi"" ever !e ca""ed during siu"ation !ecause there is no trigger to do so i.e. interrupt hardware is not siu"ated in ost siu"ators. <hen )ou ha"e finishe( simulating the interrupt just comment out the original control in the top most file as follows. // H(efine >I02A89OI489772P8 1 8his then sets all the co(e bac$ to normal operation i.e. interrupts will wor$ as http://www.best-microcontroller-projects.com Page @A of 83. Effective PIC Interrupts e'pecte( on the har(ware. 8he power of this techniEue is that itFs eas) to switch from testing mo(e to operational mo(e an( the (rawbac$ is that it ma$es co(e mess) to rea(. ;or that reason use it sparingl). 11.5.2 1.F Interrupt )imulation C Code ////////////////////////////////////////////////////////////////////// // // ;ile: 1@;88-interrupt-sim.c // // Author: / ; 0ain. // // +escription: // // Interrupt >imulation using H(efine 0acros // // Compiler : mi$roC5 mi$ro9le$troni$a C compiler // for 0icrochip PIC microcontrollers // ,ersion: 8.&.-.- // // 4ote 8esting: // // 8este( on 1@;88 // // 7eEuirements: // // Cloc$ : 60%3 BInternalC // // 8arget : 1@;88 // // ,ersion: // 1.-- - Initial release. // // Cop)right : Cop)right 1 /ohn 0ain &--8 // http://www.best-microcontroller-projects.com // ;or use onl) if purchase( with eboo$ // ZPIC Interrupt >ecretsZ // a"ailable from website abo"e. // ////////////////////////////////////////////////////////////////////// Hinclu(e Zbit.hZ ////////////////////////////////////////////////////////////////////// // +efines ////////////////////////////////////////////////////////////////////// // comment out the follwing H(efine to stop simulating the macro // Ban( 79C#0PI9C // http://www.best-microcontroller-projects.com Page @8 of 83. Effective PIC Interrupts H(efine >I02A89OI489772P8 1 ////////////////////////////////////////////////////////////////////// // file scope "ariables ////////////////////////////////////////////////////////////////////// static unsigne( long 818imeP-L // Protot)pes "oi( OinterruptB"oi(CL // 8his is ////////////////////////////////////////////////////////////////////// "oi( initB"oi(C T #>CC#4 P -'@-L // b@..6 P 11- P 60%35 111 P 80%3 A4>9 P -L // all A+C pins to (igital I/# // 8imer - // DPP2 bA P 1 : Pullups (isable( B1C. // I489+D b@ P - : Interrupt e(ge P low to high B-C. // 8-C> b= P - : Cloc$ select Internal ;osc/6 B-C. // 8->9 b6 P - : 8imer - e(ge low to high B-C. // P>A b3 P - : Prescaler assigne( to <+8 B1C 8imer- B-C. // P> b&..- P 11- : PrescaleP1:1&8 Bnote P>P--[ 1:& for 807-C. #P8I#4O79D P -'-@ \ B1SSACL // 8imer 1 81C#4 P B1SS8071#4CL // 8imer & P7&P::L 8&C#4 P B1SS807CL W ////////////////////////////////////////////////////////////////////// "oi( initOportsB"oi(C T P#78A P -L 87I>A P -L // -Po/p. P#78. P -L 87I>. P -L // -Po/p. W ////////////////////////////////////////////////////////////////////// "oi( enableOinterruptsB"oi(C T // Interrupt enable. 8071 PI91 P B1SS8071I9CL http://www.best-microcontroller-projects.com Page @: of 83. Effective PIC Interrupts // Dlobal J Peripheral interrupt enable. I48C#4 \P B1SSDI9C \ B1SSP9I9CL W ////////////////////////////////////////////////////////////////////// "oi( (isableOinterruptsB"oi(C T I48C#4 JP UB1SSDI9CL // (isable interrupts W ////////////////////////////////////////////////////////////////////// "oi( 8imer1OactionB"oi(C T static unsigne( long t P -L static unsigne( char 9+ P -L ifBtPP-C T // restart time count t P 81timeL W else T // toggle (ela) if B B81time - tC[P=-- C T 9+ P U9+L if B9+C set.itBP#78A5-CL else res.itBP#78A5-CL t P -L // start a new time count W W W //////////////////////////////////////////////////////////////////////// // >tart here // "oi( mainBC T initOportsBCL initBCL enableOinterruptsBCL
/////////////////////////// // +ebug co(e Hif(ef >I02A89OI489772P8 whileB1C T PI71 P B1SS8071I;CL OinterruptBCL // call the interrupt (irectl) after initiali3ation W Hen(if // 9n( of +ebug Co(e /////////////////////////// whileB1C L // infinite loop. W //////////////////////////////////////////////////////////////////////// http://www.best-microcontroller-projects.com Page A- of 83. Effective PIC Interrupts Hif(ef >I02A89OI489772P8 // Compiler complains if interrupt calle( so rename it "oi( OinterruptB"oi(C T Helse "oi( interruptB"oi(C T Hen(if // 8imer 1 if B PI91 J B1SS8071I9C C T // Int. 9nable(? if BPI71 J B1SS8071I;C C T // 81 o"erflowe( ? PI71 JP UB1SS8071I;CL // clear timer1 o"erflow bit. 8071 P 68L 8071% P &68L 81timeVVL
8imer1OactionBCL
W W // 4ote DI9 set b) 798;I9 instruction Bsee assembler outputC. W 11.: 1:F Interrupt +riven 4lin-ing LE+ E3ample Note: -his code provide a usefu" way of transitioning fro 15F to 18F devices. 11.:.1 1:F Interrupt +riven 4lin-ing LE+ Code ction 8his is simple template co(e to get )ou going an( it is compatible with 1@; (e"ices since it (oes not use the prioriti3e( interrupt s)stem so this is useful co(e to start using if )ou ha"e been using the 1@; series PIC (e"ices Bor an) single "ector processorC. It is a simple heartbeat timer Busing 807-C which simpl) increments a local static "ariable FtimerF e"er) millisecon(. 8he "alue of the timer is teste( in the main co(e to gi"e a perio( of =--ms. >o e"er) =--ms P#78C is toggle( * an 9+ attache( to an) pin on that port will flash with a perio( of 1 secon(. http://www.best-microcontroller-projects.com Page A1 of 83. Effective PIC Interrupts 11.:.2 1:F Interrupt +riven 4lin-ing LE+ C Code ////////////////////////////////////////////////////////////////////// // // ;ile: 18;&==-O9+O.lin$ingOint.c // // Author: / ; 0ain. // // +escription: // // 8est 18; &==- Interrupts using 8imer - - flashes Port C. // // Compiler : mi$roC5 mi$ro9le$troni$a C compiler // for 0icrochip PIC microcontrollers // ,ersion: 8.&.-.- // // 4ote 8esting: // // 8este( on 18;&==- // // 7eEuirements: // // Cloc$ : 80%3 BInternalC // // 8arget : 18;&==- // // ,ersion: // 1.-- - Initial release. // // Cop)right : Cop)right 1 /ohn 0ain &--8 // http://www.best-microcontroller-projects.com // ;or use onl) if purchase( with eboo$ http://www.best-microcontroller-projects.com Page A& of 83. Effective PIC Interrupts // ZPIC Interrupt >ecretsZ // a"ailable from website abo"e. // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // local scope static unsigne( int timerP-L ////////////////////////////////////////////////////////////////////// "oi( initBC T // #scillator internal configuration #>CC#4.I7C;& P 1L // 80%3 #>CC#4.I7C;1 P 1L #>CC#4.I7C;- P 1L #>CC#4.>C>1 P 1L // Internal oscillator >)stem Cloc$ >ource #>CC#4.>C>- P 1L W ////////////////////////////////////////////////////////////////////// "oi( initOportsB"oi(C T P#78C P -L // Initiali3e P#78C. 87I>C P -L // Configure P#78C as output. W ////////////////////////////////////////////////////////////////////// "oi( enableOinterruptsB"oi(C T // 4ote ;or the 18; series 8imer - is not controller "ia #P8I#4O79D 8-C#4.807-#4 P 1L http://www.best-microcontroller-projects.com Page A3 of 83. Effective PIC Interrupts 8-C#4.8-8.I8 P 1L 8-C#4.8-C> P -L // internal cloc$ 8-C#4.P>A P -L // 2se prescaler 8-C#4.8-P>& P -L // prescaler set to 1:1@ B-'-11C 8-C#4.8-P>1 P 1L 8-C#4.8-P>- P 1L // 8imer - :#sc off5 Internal cl$5 #n53ero 8-I; I48C#4 P B1SS807-I9CL // Dlobal J Peripheral interrupt enable Bhigh an( low I9 in 18;C. I48C#4 \P B1SSDI9%C \ B1SSDI9CL // 4ote: DI9 has become the high proiorit) interrupt enable or DI9% // an( P9I9 has become the low proprit) interrupt enable or DI9 // both must be high for low priorit) interrupts. W ////////////////////////////////////////////////////////////////////// "oi( (isableOinterruptsB"oi(C T I48C#4 JP UB1SSDI9CL // (isable interrupts W ////////////////////////////////////////////////////////////////////// "oi( mainBC T initOportsBCL initBCL enableOinterruptsBCL whileB1C T if Btimer[P=--C T http://www.best-microcontroller-projects.com Page A6 of 83. Effective PIC Interrupts P#78C P UP#78CL // toggle all P#78C pins timer P -L W
W // infinite loop W //////////////////////////////////////////////////////////////////////// // 0i$roC (ocumentation uses interruptOlowBC but this // function interruptBC is use( b) the compiler for // the low priorit) interrupt Bteste( on har(wareC. // "oi( interruptB"oi(C T // 8imer - if BI48C#4 J B1SS807-I;C C T // 8- o"erflowe( ? I48C#4 JP UB1SS807-I;CL // clear timer- o"erflow bit. // ;osc/6 ' BPrescale1:1@C ' Bcount to o"erflowC P repeat rate. // &us ' 1&8 ' 131 P 1ms BC // 4ote count to o"erflow uses & when up(ating hence 133 not 131 807- P 133L // ;rom PIC 8imer - calculator. timerVVL W // 4ote DI9 set b) 798;I9 instruction Bsee assembler outputC. W 11.B 1:F Prioriti=ed Interrupt E3ample Note: -his code is specific to the 0(& 18F series devices since it uses the 18F prioritized hardware syste !"oc# to wor#. http://www.best-microcontroller-projects.com Page A= of 83. Effective PIC Interrupts 11.B.1 1:F Prioriti=ed Interrupt Code ction 8his simple co(e (emonstrates clearl) the priorit) mechanism at wor$ an( gi"es )ou all the setup co(e that )ou nee( to ma$e prioriti3e( interrupts wor$. $arning : 0"ease note that this code is deonstration on"y and is not to !e e7act"y copied in a rea" syste as it uses !ad a design decision very specifica""y to show you the priority interrupt echanis. %o don.t <ust copy this code without odifying it :6ou !%S& mo'ify it so that the ain heart !eat tier is a high priority interrupt. 8his co(e uses two timers 807- an( 8071. 8071 * heartbeat timer * 1ms * #< I489772P8 Priorit). 807- * (ela)ing timer - &ms * %ID% I489772P8 Priorit). 8here are also two timing "ariables timer1 an( timer& an( these are use( to measure out timing perio(s within the main co(e bloc$. 8hese two "ariables are up(ate( within the heartbeat timer interrupt B8071C. 8071 has been purposel) set as a #< P7I#7I8I I489772P8 an( normall) )ou woul( ensure that this is a %ID% priorit) interrupt * but for (emonstration it is set to #<. tier8 - measures a &=ms (ela) an( then toggles the state of P#78. so an) 9+ attache( to that port will be flashing at a fast rate. tier5 * 0easures out a 1 secon( (ela) an( toggles the "alue of "ariable tog. tog - is then use( to enable an( (isable the high priorit) interrupt to (emonstrate the interrupt priorit) mechanism. http://www.best-microcontroller-projects.com Page A@ of 83. Effective PIC Interrupts 11.B.2 Priorit& Effect on LE+ at P7RT4 In normal operation when the high priorit) interrupt is (isable( the blin$ing rate of the 9+ is fast Bthe timer * 8071 - is going at 1msC but when the other interrupt "ector is allowe( to operate the 8071 interrupt gets interrupte( itself so that 8071 Binterrupt co(eC is slowe( (own. Iou can see this effect because an 9+ attache( to P#78. will flash fast for 1 secon( an( then slowl) for 1 secon(. If the priorit) interrupt mechanism were not use( then 8071 woul( not slow (own since both interrupts woul( be actione( from within one I>7. 8his (emonstrates that it is possible to ser"ice another interrupt e"en while the original interrupt is being actione( but as note( before )ou must not cop) this co(e for use in a real s)stem since the heartbeat timer is not constant * so all timings from it are wrong * it is for (emonstration onl). 11.B.3 1:F C!anging t!e interrupt priorit& As an e'ercise it is possible to change the co(e to show the correct operation with the heartbeat timer as high priorit) * .28 * itFs not a "er) impressi"e (emo since )ou will not see an) effect on P#78. (ue to the low priorit) interrupt since the high priorit) interrupt will now alwa)s ta$e prece(ence. Iou can see this co(e in the 3ip file as 18;&==-O9+O.lin$ingOpriorit)OintOswappe(.c .ut itFs not shown in this (ocument. It is simpl) changing the priorit) control register "alues an( swapping co(e between low an( high priorit) I>7s. 11.B.$ 1:FPrioriti=ed Interrupt C Code ////////////////////////////////////////////////////////////////////// // // ;ile: 18;&==-O9+O.lin$ingOpriorit)Oint.c // // Author: / ; 0ain. http://www.best-microcontroller-projects.com Page AA of 83. Effective PIC Interrupts // // +escription: // // +emonstration of propriti3e( interrupts. // // 8est 18;&==- Interrupts using 8imer - an( 8imer 1. // // ;lashes Port C 9+ at high rate using low priorit) interrupt. // 9"er) other secon( the high priorit) interrupt is enable( // an( this one interrupts the low priorit) co(e. >ince the // timing for the 9+ is (eri"e( from the low priorit) interrupt // this timer slows (own so the 9+ flashes "isibl) more slowl). // // Compiler : mi$roC5 mi$ro9le$troni$a C compiler // for 0icrochip PIC microcontrollers // ,ersion: 8.&.-.- // // 4ote 8esting: // // 8este( on 18;&==- // // 7eEuirements: // // Cloc$ : 80%3 BInternalC // // 8arget : 18;&==- // // ,ersion: // 1.-- - Initial release. // // Cop)right : Cop)right 1 /ohn 0ain &--8 // http://www.best-microcontroller-projects.com // ;ree for non commercial use as long as this entire cop)right notice // is inclu(e( in source co(e an( an) other (ocumentation. // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // local scope static unsigne( int timer1P-5timer&P-L ////////////////////////////////////////////////////////////////////// "oi( initBC T // #scillator internal configuration #>CC#4.I7C;& P 1L // 80%3 http://www.best-microcontroller-projects.com Page A8 of 83. Effective PIC Interrupts #>CC#4.I7C;1 P 1L #>CC#4.I7C;- P 1L #>CC#4.>C>1 P 1L // Internal oscillator >)stem Cloc$ >ource #>CC#4.>C>- P 1L
7C#4.IP94 P 1L // 9nable prioriti3e( interrupts
I48C#4&.807-IP P -L // >et priorit) for timer - - heartbeat timer. IP71.8071IP P 1L // >et priorit) for timer 1. W ////////////////////////////////////////////////////////////////////// "oi( initOportsB"oi(C T P#78. P -L // Initiali3e P#78.. 87I>. P -L // Configure P#78. as output. P#78C P -L // Initiali3e P#78C. 87I>C P -L // Configure P#78C as output. W ////////////////////////////////////////////////////////////////////// "oi( enableOinterruptsB"oi(C T // 4ote ;or the 18; series 8imer - is not controlle( "ia #P8I#4O79D 8-C#4.807-#4 P 1L 8-C#4.8-8.I8 P 1L 8-C#4.8-C> P -L // internal cloc$ 8-C#4.P>A P -L // 2se prescaler 8-C#4.8-P>& P -L // prescaler set to 1:1@ B-'-11C 8-C#4.8-P>1 P 1L 8-C#4.8-P>- P 1L
81C#4.7+1@ P -L // 8 bit om(e B-C 81C#4.81724 P -L // source not 81 cloc$ B-C 81C#4.81C!P>1 P 1L // Prescale 1:6 B1-C 81C#4.81C!P>- P -L // 81C#4.81#>C94 P -L // e'ternal 'tal off B-C 81C#4.81>I4C P -L // s)nce e'ternal cloc$ 81C#4.8071C> P -L // cloc$ source internal B-C 81C#4.8071#4 P 1L // 8imer 1 on B1C
// Interrupt enable. 8071 PI91.8071I9 P 1L http://www.best-microcontroller-projects.com Page A: of 83. Effective PIC Interrupts
// Dlobal J Peripheral interrupt enable Bhigh an( low I9 in 18;C. I48C#4 \P B1SSDI9%C \ B1SSDI9CL // 4ote: DI9 has become the high priorit) interrupt enable or DI9% // an( P9I9 has become the low priorit) interrupt enable or DI9 // both must be high for low priorit) interrupts. W ////////////////////////////////////////////////////////////////////// "oi( (isableOinterruptsB"oi(C T I48C#4 JP UB1SSDI9CL // (isable interrupts W ////////////////////////////////////////////////////////////////////// "oi( mainBC T short tog1 P -L initOportsBCL initBCL enableOinterruptsBCL whileB1C T
if Btimer& [P&=C T P#78C P UP#78CL // toggle all P#78C pins timer& P -L W
if Btimer1[P1---C T timer1 P -L tog1 P Ktog1L W if Btog1C T PI91.8071I9 P 1L P#78. P -'ffL W else T PI91.8071I9 P -L P#78. P -'--L W WL // infinite loop W //////////////////////////////////////////////////////////////////////// // %ID% Priorit) Interrupt. http://www.best-microcontroller-projects.com Page 8- of 83. Effective PIC Interrupts // // 8his interrupt co(e will interrupt the low priorit) co(e // an( slow the main timer resulting in a lower flash rate // for the 9+. // "oi( interruptB"oi(C T // 8imer 1 if B PI91 J B1SS8071I9C C T // Int. 9nable(? if BPI71 J B1SS8071I;C C T // 81 o"erflowe( ? PI71 JP UB1SS8071I;CL // clear timer1 o"erflow bit. 8071 P &6L // &ms repeat rate with prescale of 1:6 8071% P &=&L // ;rom PIC 8imer 1 calculator. (ela)OusB1=--CL // use (ifferent routine to main co(e W W // enable(? // 4ote DI9 set b) 798;I9 instruction Bsee assembler outputC. W //////////////////////////////////////////////////////////////////////// // #< Priorit) Interrupt. // // 8he heartbeat timer has been place( into the low priorit) // Interrupt co(e onl) to show how the interrupt timer is // slowe( (own when the higher priorit) interrupt - actuall) // interrupts this one. // // In practice )ou woul( not use this co(e - it is for (emo. onl). // // 8imer - is nominal) a 1ms timer but the higher interrupt priorit) // will change this Bso the output from this interrupt action // "ariables Btimer15timer&C (epen(s on the spee( of the // interrupting co(eC. // "oi( interruptOlowB"oi(C T // 8imer - if B I48C#4 J B1SS807-I9C C T // Int. 9nable(? if BI48C#4 J B1SS807-I;C C T // 8- o"erflowe( ? I48C#4 JP UB1SS807-I;CL // clear timer- o"erflow bit. // ;osc/6 ' BPrescale1:1@C ' Bcount to o"erflowC P repeat rate. // &us ' 1&8 ' 131 P 1ms BC http://www.best-microcontroller-projects.com Page 81 of 83. Effective PIC Interrupts // 4ote count to o"erflow uses & when up(ating hence 133 not 131 807- P 133L // ;rom PIC 8imer - calculator. timer1VVL timer&VVL W W // enable(? // 4ote DI9 set b) 798;I9 instruction Bsee assembler outputC. W 12 *ig!lig!ts 8he one thing )ou 02>8 49,97 +# when using interruptsL Chapter 6.6 Page 1=. <h) interrupts allow )ou to achie"e ;A7 0#79 than using processor co(e aloneL Chapter 3.3 Page 11. +onFt get caught out b) this simple interrupt co(ing error Bif )ou want Interrupts to wor$ correctl) an( consistentl)KCL Chapter 6.@.1 Page 1A. A simple wa) to 79+2C9 )our interrupt co(e si3e Ban( 4# its not calling a function from within the Interrupt co(e itselfCL Chapter 8.1 Page 31. 2se 8%799 ;AC8#7> that affect Interrupt Co(e Performance to impro"e )our s)stemL Chapter A.8 Page &8. <h) interrupts >8I <#7! e"en if )our co(e has C7A>%9+L Chapter 3.6 Page 1&. A simple I489772P8 >I02A8I#4 techniEue B)ou canFt (o it without this techniEueCL Chapter 8.3.& Page 36. 8he one thing that Interrupts A#< but polling ne"er canL Chapter 3.= Page 1&. %ow to a"oi( ACCI+948AI ma$ing the interrupt routine too largeL Chapter 6.@.1 Page 1A. <h) interrupts ma$e )our programs >I0P97L Chapter 6.3 Page 16. An 9ssential techniEue for using interrupts in critical co(e to a"oi( s)stem (isasterL Chapter 3.6 Page 11. <h) )ou <#4F8 ;I4+ the Xinterrupt mo(uleY on the har(ware (iagramL Chapter http://www.best-microcontroller-projects.com Page 8& of 83. Effective PIC Interrupts 6.1 Page 13. <h) interrupts are so 99DA48 an( polling is a ba( i(eaL Chapter 6.& Page 13. %ow interrupts ma$e multitas$ing possibleL Chapter 3 Page :. <h) interrupt co(e must be (ifferent to FnormalF co(eL Chapter @.3 Page &-. %ow interrupts fit into the X4ormal Processor Instruction C)cleY Chapter 6.1 Page 13. Interrupt Casca(e K?KL Chapter 8.& Page 3&. 8%799 full C Co(e e'amplesL Chapter 11 Page 63. ;2 C Co(e 8emplate for eas) co(ing of )our C interruptsL Chapter 11.& Page 6A. 8%799 (ifferent wa)s to measure an interrupt e'ecution timeL Chapter 8.3 Page 36. <h) using interrupts for timing purposes is .98897 than using built in (ela) routinesL Chapter 11.3 Page =1. ;in( out the one big error that is so eas) to ma$e an( "er) subtle to fin( an( sort outL Chapter : Page 3A. <h) using 7>&3& 8ransmit Interrupts is easier than simpl) writing (ata to the 7>&3& transmit har(wareL Chapter 11.6 Page =@. %ow to change an 18; (e"ice Iinterrupt from low to high priorit) or "ice "ersa: Chapter 11.:.3 Page AA. http://www.best-microcontroller-projects.com Page 83 of 83.