New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Fredy Okuneva

Microcontrollers ECE 340

Fredy Okuneva
GPA 3.81

Richard Wall

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Richard Wall
Class Notes
25 ?




Popular in Course


This 38 page Class Notes was uploaded by Fredy Okuneva on Thursday October 22, 2015. The Class Notes belongs to ECE 340 at University of Idaho taught by Richard Wall in Fall. Since its upload, it has received 6 views. For similar materials see /class/227729/ece-340-university-of-idaho in ELECTRICAL AND COMPUTER ENGINEERING at University of Idaho.

Similar to ECE 340 at UI



Reviews for Microcontrollers


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/22/15
Chapter 5 Interrupts Rev 9252008 The following chapter contains excerpts from the Rabbit Semiconductor Rabbit 3000 User s Manual1 1 Vectored Interrupts Vectored interrupts direct the computer to make an unconditional subroutine call to a xed memory address It is expected that data programmed into memory at that address and subsequent locations will either perform the instructions to service the interrupt or execute code that will cause the processor to jump to a new address in memory to execute code to service the interrupt The code that services an interrupt is called an Interrupt Service Routine or ISR The Dynamic C User s Manual Chapter 12712 describes the steps followed by an ISR The structure of the Rabbit 3000 processor is described in the Rabbit 3000 Users Manual Chapter 7103 The vector address can be located anywhere in the root memory space Flash memory address 0x0000 through OxffOO Setting the speci c block of address is controlled by the IIR register for internal interrupts and the EIR for external interrupts The values stored in the IIR and EIR hold the upper byte of the vector address and are set in the BIOS and programmed into the processor during bootup The base address for internal interrupts is determined by the expression SIDINTVECBASE RO0TCODESIZE and for external interrupts by the expression SIDINTVECBASE ROOTCODESIZE 0x100 This shows that the vector tables are placed immediately above the code space in the root memory For default Dynamic C bios settings the HR is set to 0xCE signifying that the internal interrupt vector table starts at address 0xCE00 The default setting of the EIR is 0xCF resulting in the external vector table starting at address 0xCF00 Modifying either the EIR or the HR register at run time can have disastrous results Although the speci c vector addresses are shown in Table 1 Dynamic C lls in the jump address of the user written ISR when the program is loaded into the processor It uses the function SetVectIntern that has two variables passed to it the interrupt vector number shown in Table l and the function name of the ISR that you write Some interrupts are combined into a group interrupts serviced by single vector number An example of this is the Timer A interrupts When such interrupts are received a status register must be polled to determine which timers actually generated the interrupt Table 1 Rabbit processor interupt vector numbers event 1httpWWW quot 39 39 I m I 1 moTr 11 1 1 htm 2httpwww 7w0rld 39 quot3FDFU1 1 quot 1 mm 3httpWWW quot 39 39 I m I 1 nooTT 11 1 1 htm structure an ISR C 1 two parts a setup and the runtime ISR function For timer interrupts the setup function performs the following steps Sequence 1 Disable all timer Al and A2 interrupts Clear all pending interrupts Set Timer Al and A2 constants for a 1000 Hz output from timer A2 Write the ISR function address into the vector address Enable timer A interrupts for level 12 or 3 6 Enable timer A2 interrupts MJBQNH Listing 1 Structure of an ISR written in Dynamic C define TimerAvectnum 0x0a Timer A interrupt vector number Table I define TIMERA2 0x04 Timer A2 TCSR Selects TA1 for input to TA2 define TIMERAL1 0x01 Interrupt level 1 use level 1 for debug mode TACR define TIMERAL2 0x02 Interrupt level 2 TACR define TIMERAL3 0x03 Interrupt level 3 highest level TACR define PCLKl 0 CPU XTAL for clock base frequency do not use define PCLK2 1 CPU XTALZ for clock base frequency define TIMERAENABLE 1 Enable timer A TACSR define TIMERA1INTR 2 Enable interrupt for Timer A counters 27 TACSR define TIMERA2INTR 4 Timer A2 interrupt enable TACSR define TIMERA3INTR 8 Timer A3 interrupt enable TACSR define TIMERA4INTR 0x10 Timer A4 interrupt enable TACSR define TIMERA5INTR 0x20 Timer A5 interrupt enable TACSR define TIMERA6INTR 0x40 Timer A6 interrupt enable TACSR define TIMERA7INTR 0x80 Timer A7 interrupt enable TACSR void SetupTimerA2void define A1 100 define A2 145 int TimerAstatus WrPortITACSR NULL 0 Disable all timer A interrupts TimerAstatus RdPortITACSR read the timerA control and status register to clear the interrupt flag WrPortITAPR ampTAPRShadow PCLK2 Timer A divide perclk2 for clocking WrPortITATlR ampTATlRShadow A1 Set time constant for timer A1 WrPortITAT2R ampTAT2RShadow A2 Set time constant for timer A2 SetVectInternTimerAvectnum TimerAInterrupt Establish the ISR function WrPortITACR ampTACRShadow TIMERA2T1VIERAL1 Enable timer A2 interrupt clocked by A1 use level 1 priority WrPortITACSR ampTACSRShadow TIMERAENABLE TIMERA2INTR 2 Interrupt Service Routines Internal Interrupts Either standalone assembly code or embedded assembly code may be used for ISRs The bene t of embedding assembly code in a Clanguage ISR is that there is no need to worry about saving and restoring registers or reenabling interrupts The drawback is that the C interrupt function does save all registers which takes some amount of time A standalone assembly routine needs to save and restore only the registers it uses ISR functions have a very speci c format ISR functions can use any legal function name The example ISR is shown in Listing 1 uses the function name TimerAInterrupt An ISR function must begin with the word interrupt and have a void argument list No variables can be passed to or values returned from ISR functions Variable that are used by or modi ed in ISR functions must be declared as global variables Interrupt Service Routines ISRs may be written in Dynamic C declared with the keyword interrupt 4 But since an assembly routine may be more ef cient than the equivalent C function assembly is more suitable for an ISR Even if the execution time of an ISR is not critical the latency of one ISR may affect the latency of other ISRs Some interrupts clear the interrupt request whenever the ISR function is called but this is not always true For the case of Timer A interrupts the TACSR must be read to clear the interrupts An example of this is shown for the TimerAinterrupt function in Listing 2 Further Timer interrupts are inhibited because the processor is operating at the priority level equal to the interrupt priority level This is discussed in detail in the following section Listing 2 ISR for internal interrupts example for Timer A interrupt 39139imerAInterrupt void unsigned int 39I39imerAstatus read the timerA control and status register to clear the interrupt flag 39I39imerAstatus RdPortI39139ACSR User supplied ISR code 3 External Interrupts The Rabbit 3000 microprocessor allocates two IO pins that can be used to generate external interrupts The two pins can either be PEO or PEl for INTO and PE4 or PE5 for INTl as shown in Figure l The external interrupts take place on a transition of the input which is programmable for rising falling or both edges Each of the interrupt pins has its own catcher device that can be programmed separately to catch the edge transition and request the interrupt Both the pins and the modes are set by specifying the bits in the IOC0 and IOCl registers as shown in Table 2 4 httpwww 7world 39 quotUFDFU erl ianual lOkeV htm107l949 Figure 1 External interrupt line logic Table 2 Control Registers ror External Interrupts Reg Name Reg Address Bits 76 Bits 54 Bits 32 Bits 10 l IOCR 10011000 Ear lNTOB PEA INTOA PEO Enb lNTO lIICR 10011001 Ear lNTlB PES INTlA PEI Enb lNTl edge triggered edge triggered interrupt 00dsab1ed 00disabled 00dsab1e 39 39 0 7 i1 lorriSmg irislng Olrfalling Olrfalling l rpri 2 llrboth llrboth llrpri 3 Ifthe processor is quot L L 39 r place both 39 wirlr 39 39 reset Ifboth quot quot 39 place 39 39 nearly simultaneously or because the interrupts are inhibited by the processor priority then there will be only one interrupt for e wo edges detected The interrupt service routine can read the interrupt pins Via Parallel Port E and determine which quot 39 4 a tmn itinn 39 39 39 fast Setting up the matching port E bit as an output and toggling the bit can also generate interrupm emal n The Tntemmt 4 wiii 39 39 ioliow an Instruction Fetch 1 cycle This instruction byte is ignored as will 39 39 Tntemint Acknowledge cycles are always followed by two write operations to memory to push the contents of the PC onto the stack Execution then begins at the appropriate interrupt Vector location As for the Vectored interrupts for internally generated interrupm the Vector table contains code to execute a jump to the address ofthe ISR function written in C Listing 3 is an example of the ISR for an external interrupt that is generated by the PCF8474 12C Parallel IO expander IC12 Eight exterrlal interrupts are combined to generate a single exterrlal interrupt request to the R3000 processor After the interrupt the inputs ofthe IO expander 1C must be polled to determine which of the external devices changed state to generate the request The code wrinen to read the 10 expander 1C will be discussed in the chapter on serial communications run tr 4 Listing 3 Function ror initializing an external interrupt Global definitions and declarations define 03123111901 Oxff output to make QED inputs define define define define define define IOXPOR39I O IOXPOR39I l EX39I390VEC39139OR EX39I391VEC39139OR EX39I39IN39139RCFG EX39I39IN39139ROFF 0x76 0x72 0x11 void initIOXinterruptsvoid int errorflag WrPortIIOCR EIOCRShadow EX I IN39139ROFF IOXintrflag 039 IC 13 I2C Serial IO Expansion IC 12 I2C Serial IO Expansion Rabbit 3000 UM Chapter 7102 Rabbit 3000 UM Chapter 7102 INTOB Level 1 negative edge Disable all external interrupts Reset ext int flag errorflag PCF853974IOXWrIOXPOR391390 QBDINPU 139 Make QBD data If errorflag WrPortIPEDDR EPEDDRShadow SetVectExtern3000 EX I 0VEC39139OR IOXier WrPortIIOCR EIOCRShadow EX39139IN39139RCFG for read operation report PCF853974 errors printf EXP IO device failed to initializenquot 00 Set Port E for all inputs Write ISR address into vector table Enable Port E High nibble interrupt 0x11 Interrupt is generated on falling edge Interrupt priority level 1 The project circuit board for ECE 341 uses serial to parallel integrated circuit devices to expand the external interrupt capability The code shown in Listing 4 shows how external interrupts are set up The checkibutton function calls a function that decodes the buttons status to assign values to global variables stepidirection stepftime and stepimode The reader is reminded that the only way information can be passed to and from interrupt service routines is by using global variables Listing 4 ISR for external interrupts example for serial to parallel IO expansion IC Global definitions and declarations Button 2 and 3 values when read from IC12 IO expansion chip define Button2intr define Button3intr int IOXintrflag 0x20 Bit value for BUTT2 0x40 Bit value for BUTT3 cleared outside ISR root interrupt void IOXier void You don t have to clear the interrupt flag it is done automatically for interrupt handler calls the ISR external interrupts when the WrPortIIOCR EIOCRShadow EX I IN391 ROFF bu o s PCF853974IOXRdIOXPOR391390 amp Button2intr Button3intr Use following line for decoding buttons checkbuttons buttons Decode the button input status IOXintrflag 1 Set all External interrupt flags WrPortIIOCR EIOCRShadow EX39I39IN39139RCFG Enable external interrupts Test function for observing the operations of external interrupts void mainvoid initIOXinterrupts IOXintrflag 0 while1 ifIOXintrflag Wait for button interrupt IOXintrflag 0 Reset interrupt flag Rabbit Processor Interrupt Priority Scheme The Rabbit supports four levels of processor priority Level 0 is the lowest level and it is the level that the processor normally operates The intention in the Rabbit is that most interrupting devices will use priority 1 level interrupts Devices that need extremely fast response to interrupts will use priority level 2 or 3 interrupts Since code that runs at priority level 0 or 1 never disables level 2 and level 3 interrupts these interrupts will take place within about 20 clocks the length of the longest instruction or longest sensible sequence of privileged instructions followed by an unprivileged instruction It is important that the user be careful not to overdisable interrupts in critical code sections The processorpriority should not be raised above level I except in carefully considered situations The effect of the processor priority on interrupts is shown in Table 3 The state of the bits in the IO control register associated with the hardware that creates the interrupt usually establishes the priority of the interrupt The 8bit interrupt register IP holds the processor priority in the least significant two bits When an interrupt takes place the IP register is shifted left 2 positions and the lower 2 bits are set to equal the priority of the interrupt that just took place This means that an interrupt service request ISR can only be interrupted by an interrupt of higher priority unless the priority is explicitly set lower by the programmer The IP register serves as a 4word stack of 2bit words to save and restore interrupt priorities It can be shifted right restoring the previous priority by a special instruction IPRES Since only the current processor priority and 3 previous priorities can be saved in the interrupt register instructions are also provided to PUSH and POP IP using the regular stack A new priority can be quotpushedquot into the IP register with special instructions IPSET 0 IPSET 1 IPSET 2 IPSET 3 Table 3 Processor Interrupt levels Running Effects on Interrupts Service current non current non current The virtual timers MSTIMER TICKTIMER SECTIMER as well as the printf instruction cannot be utilized in an ISR Doing so will cause a loss of connection failure fault by the Dynamic C IDE This is because the IDE expects the processor to respond to a command from the PC indicating that the processor is still connected Both the virtual timers operate using a level one priority interrupt and hence any ISR will halt the timer interrupts The printf statement uses a serial port that also uses a level one priority and hence is blocked from completion Table 4 lists all of the possible sources of interrupts for the Rabbit 3000 processor and the priority set in hardware These hardware priorities are enforced only under the following conditions 0 The processor is operating at a level that will allow the interrupts o The interrupts occur with in the same clock cycle 0 The interrupts are set for the same priority level Table 4 Inten11pts Priority and Action to Clear Requests lnterru t Prlorlty p Actlon ReqUIred to Clear the Interrupt Source Highest External 1 Automatically cleared by the interrupt acknowledge External 0 Automatically cleared by the interrupt acknowledge Periodic 2 kHz Read the status from the GCSR Quadrature Decoder Read the status from the QDCSR Timer A Read the status from the TASR Input Capture Read the status from the ICCSR Rd Read the data from the SPDOR SPDlR or SPDZR Timer B Read the status from the TBSR Slave Port Wr Write data to the SPDOR SPD 1R SPDZR or write a dummy byte to the RX Read the data from the SEDR or SEAR Serial Port E TX Write dam to the SEDR SEAR SELR or write a dummy byte to the SESR Serial Port F RX Read the data from the SFDR or SFAR TX Write dam to the SFDR SFAR SFLR or write a dummy byte to the SFSR RX Read the data from the SADR or SAAR Serial Port A TX Write dam to the SADR SAAR SALR or write a dummy byte to the SASR RX Read the data from the SBDR or SB AR Serial Port B TX Write dam to the SBDR SBAR SBLR or write a dummy byte to the SB SR RX Read the data from the SCDR or SCAR Serial Port C TX Write dam to the SCDR SCAR SCLR or write a dummy byte to the SCSR RX Read the data from the SDDR or SDAR Lowest Serial Port D TX Write date to the SDDR SDAR SDLR or write a dummy byte to the SDSR 4 Interrupt Limitations Interrupts have four attributes priority latency frequency and persistency These attributes are discussed in detail in the following sections Interrupts can also be classi ed by their pattern of occurrence either sporadic or periodic The occurrences of sporadic interrupts are not predictable Latency Interrupt latency refers to the time required for an interrupt to take place after it has been requested Generally interrupts of the same priority are disabled when an interrupt service routine is entered Sometimes interrupts mu st stay disabled until the interrupt service routine is completed other times the interrupts can be re enabled once the interrupt service routine has at least disabled its own cause of interrupt In any case if several interrupt routines are operating at the same priority this introduces interrupt latency while the next routine is waiting for the previous routine to allow more interrupts to take place If a number of devices have interrupt service routines and all interrupts are of the same priority then pending interrupts can not take place until at least the interrupt service routine in progress is nished or at least until it changes the interrupt priority As a rule of thumb Z World usually suggests that 100 us be allowed for interrupt latency on Z180 or Rabbitbased controllers This can result if for example there are five active interrupt routines and each turns off the interrupts for at most 20 us Figure 2 shows the components that make up latency computations Before a processor begins the interrupt process it must first complete the machine instruction that it is currently processing On some processors with instruction queues the next instruction in the process being interrupted must also be executed The process of saving the current context is also associated with latency Latency can be extended if additional code is required to implement nested interrupt schemes as well as additional time to complete lower priority interrupts in non nested interrupt schemes See Interrth Management below 39NTRx iillillillillillillillilliiiiiitiiililiiilililililiiiiiiiiiiiiililililililii T TLATENCV 1 gt T 2923 Time Figure 2 Breakdown of interrupt latency Frequency Frequency is a measure of the rate that periodic interrupts occur or the inverse of the shortest interval between sporadic interrupts Three things limit the frequency of interrupt signals the speed of the processor the execution time of the ISR and the worst case latency for a particular ISR The factors that in uence latency are discussed in Interrth Management section of this chapter Persistence Persistence is the duration of the interrupting signal The required persistence when polling for signals to trigger event is the processor execution time of all code between two successive polling operations Signals Whose persistence spans multiple polling operations may falsely generate multiple events unless mitigated using software or external hardware Since most processors latch external interrupts using ip ops internal to the processor the required persistence for these interrupts is generally one or two instructions cycles When interrupt signals are latched one must consider how the ip ops are reset so to be able to capture the next signal trigger As discussed in previous sections of this chapter some internally generated interrupts are cleared only when a speci c register is read The external interrupts and certain internal interrupts are automatically cleared when the ISR is serviced 5 Protected Code Controlling the stepper motor requires that the outputs PGO through PG3 be modi ed each step Since only four of the eight output pins are needed for stepper motor control the other four pins are available for additional controls or indications In Lab 4 you are required to toggle PG6 and PG7 so you can observe the realtime operations of the stepper motor speed controls This means that some pins of the same 10 port could change at different times Fortunately for the students in the Lab 4 experiment all events are synchronized However that is not always the case and the states of some pins must be unaltered While modifying other pins Consider the readmodifywrite sequence represented by the three lines of code in Listing 2 that performs the readmodifywrite operation to change the stepper motor outputs For the case of sporadic interrupts or other timer interrupts run a rate that is not a multiple of the rst timer interrupt and it too alters Port G For the later case eventually the second timer interrupt will occur between lines two and three of the code When and not if this happens the data that is written back to port G and the shadow register is outdated because it was modi ed by the interrupt after it was read in the second line Listing 2 Protecting read modify write sequences stepperoutput stepcode stepindex amp STEPPERMASK stepperoutput PGDRShadow amp S39139EPPERMASK WrPortIPGDR EPGDRShadow steppercode We must prevent one interrupt function from making changes to global variable or IO ports that are being modi ed by the function that was interrupted This requires that the three lines of code written above must be protected from interrupts The easiest way to prevent interrupts that will protect a segment of code is to promote the processor operating level to a level that is higher than the interrupt that could cause a problem The following table lists the effects of setting the lter for the four levels of priority Protecting various segments of code is accomplished using the ipset L and ipres functions where L is the level according to Table 3 6 Interrupt Management To this point we have discussed the four attributes of interrupts priority frequency persistence and latency How interrupts are be managed can result in very different latency Fundamentally there are two types of management schemes fully nested and nonnested Nonnested interrupt schemes are usually the result of systems with single level software priorities and multi level hardware priorities Non nested Priority Management Systems Figure 3 illustrates that low priority interrupts can impose large latencies on high priority interrupts Interrupt Tl shown in Figure 3 is the lowest priority interrupt and by virtue of when it occurs it has started to run before interrupt 2 occurs While interrupt T1 is running interrupt T3 Since T3 is the highest standing interrupt when interrupt Tl nishes T3 will run neXt While T2 is running interrupt T4 occurs and will begin running when T3 has nished After T4 is completed interrupt T2 that occurred shortly after Tl started running will nally get a chance to run The latency associated with T2 can be as long as the sum of the run times for all higher interrupts plus the longest run time of an interrupt with a lower priority INTRA INTRa Context Saving Restoring Useful work Increasing Priority 1 2A INTRz iillillillillillillilliliiiillillillilliliiiiillillillilIiillillillillillillilli TWEch mm ISR in waiting INTRi m gt Time Figure 3 Nonnested interrupt management scheme The latency for an interrupt of any priority can be computed using the following expression TLAT TLI TSC MAXTSC7LP TLP Z TSCrSSPrHHP TSP HHP Z TSCr HSP THSP where TU Execution time of the longest executing assembler instruction TSC Time to save context of the interrupt for which the latency is being calculated TSGLP TLP Execution time plus time to save context of interrupts of lowersoftware priority TSGSSRHHP TSGHHP Execution time plus time to save context of interrupts of same software priority but higher hardware priority TSGHSP THSP Execution time of plus time to save context of interrupts of higher software priority Nested Priority Management Operations Nesting interrupts schemes as illustrated in Figure 4 is where some interrupts are allowed to preempt interrupts that have a lower priority Although this scheme results in shortened worse case latency the execution time of low priority interrupts can be extended to include the sum of all higher priority interrupts This is the case for interrupts Tl through T3 illustrated in Figure 4 The problem can be further exacerbated if the frequency of high priority interrupts causes them to run multiple times before the low priority interrupt is able to nish A INTRA INTRS gta E E El ContextSaving D INTRZ Restoran E 3 El Usefulwork 5 mm ISRinwaiting NTR1 Maiquot Program Time Figure 4 Nested interrupt management scheme The latency for an interrupt of any priority for the fully nested scheme can be computed using the expression shown in equation 2 TLAT TLI TSC TSCrSSPr HHP TSP HHP Z TSCr HSP THSP where TU Execution time of the longest executing assembler instruction TSC Time to save context of the interrupt for which the latency is being calculated TSCVSSPVHHP TSGHHP Execution time of plus time to save context of interrupts of same software priority but higher hardware priority TSGHSP THSP Execution time of plus time to save context of interrupts of higher software priority On some processors additional code is required to enable interrupts While executing an interrupt The time to execute this additional code maybe considered part of the interrupt latency in some teXt books mm Context Saving Restoring INTRX Useful work ISR in waiting TLATENCY 1 1 Enabling Intr INTRy TINST Time Figure 5 Latency details for nested interrupts Chapter 6 PmcessorIO Expansion amp Handshaking Rev 1mm Simple Port 0 10 ports ean be used as parallel ports for exchangmg lnfonnnatlon with an e e al devlce The number ofblts that are gnoupedtogetlnen depends appllcatlon Figure 1 demonstrates the sunplest form of usmg 10 ports Thls eon gunauon assunnes tlnat tlne entemal devlce requlres bledueeuo ts upon the forparallel IO nal neeeunng and sendmg data As noted on gure l the only way for tlne entemal devlce to tlne nnlenopnoeesson39s output port The same ls true forthe nnlenopnoeesson detectmg enanges of output from tlne entemal devlce a typical gt SumplstmllnlOutpm Miuumttunm s WEI t Slmp e Pamllsl lnPul Na hdlm un haunts ha mangndl Figure I Cun gm nnufus39ng m punsfurpznllzllo Handshaking Techniques wd t t or level handshaklng Tu w r calledcommumcanons 1t mvolves botnknowledge and acknowledge Tne senderneeds Tne e sender supplles a slgnal lme tlnat ls usedto tell the neeelven two dlstlnet places of The receiver uses a signal line to tell the sender when it is ready to receive data and when it has read the data These handshaking requirements are summarized in the timing diagram shown in Figure 2 When handshaking uses hardware wires bits in a status register or bits within a stream of communications to implement the interaction between sender and receiver as shown in Figure 2 the handshaking is called explicate Some handshaking schemes assume that the receiver is always ready and can accept the data within speci ed timing constrains Such handshaking schemes are called implicate or timeimplicate handshaking Sender Receiver Time Receiver Ready New Data Ready Receiver Data Accepted Transaction Completed Figure 2 Signal action for fully explicate handshaking In strobe synchronization an additional control signal accompanies the data In the case of an input strobe the external device pulses the strobe control line when new data is present A latch either within or connected to the microcontroller captures the data and typically asserts an interrupt as shown in Figure 3 The microcontroller must read the data before the next input strobe occurs In the case of an output strobe the microcontroller generates a pulse on the strobe control line after it writes new data The external device uses the strobe to capture the data being sent The external device must be ready for new data the next time the strobe line is pulsed In some cases the circuitry to generate the output strobe is built into the microcontroller In other cases the strobe can be generated via software using another output port pin Strobes may be either positive normally low pulsed high or negative normally high pulsed low Generally strobe handshaking assumes that the transaction is concluded on the trailing edge of the strobe pulse Relative to the transaction edge the data must be held constant The period that the data must be held constant prior to the eohstant after to the txansaetaoh edge is ea11ed the data holdume aahsmoh Data Vahd DAV handshakmg eah be mdmated by anther ahxgh orlow state DAV Signal and the data holdume is relative to the DAV Signal retummg to its macuve state ouumt Davina Mluwomu m Inpm Pan Figure 3 sum handshaking demee xf the mtehoeohaoueh tests the busy bit before the output demee asserts busy however xf Wm hot be able to test the bit quxckly enough Mkzmourmoilev 39 gammavice 2va Dan emuHIM j Pm omum 51quot Jr 1 PM Inwl 5 Pm Um i Slmba next data b ausy 7 11 r Davina Indmas it Is Comm ar Mlmlas minrnm dala We naw am available new human ammdgnmm a1 dam may Figure 4 Handshaking write Struhewith Busy cnntrnl nu Eulfm u i quotquot mu external yte Dam Lam Miwmmne my bu In Mmmuauu a we Mlnmomkmlsf Mule 12 s mady for mm data hm Figure 5 Handshaldng frnm External device 39 A Full fox an Input demee The mlcmcontxollex Indicates to the denee when It IS xeady fox data mm A anahle DAV Te mororonhollm The Input remo e the data and was fox the next data quuest Amwaywile s nan In H Device W m y n M Pan an Dena mum Pun Din Request m Dam Dmcul J PM Dln nan valld ham i 7 7 Avalluble Raqna om mspnnds by driving Mkmmmmllzr ngw whales Aw abla nal low Mimwommller in I66 is newdau avallnNe W hen mass anuss In quotax rainy la amp dala Is lamh can W data Easy assented Minmcumvo ur wldiw as n has meme ana Figure 5 Prnczssm39 pull fur dam available eonuol signals are managed usmg so wam me pxocess IS called bltbangng The handshakmg Signal genemted 5mg hmdwme as shown In Figure 5 Anothex form of discussed below Example LCD Driven from IO Portsz 1 Introduction to LCDs Advances in the features miniaturization and cost of LCD Liquid Crystal Display controller chips have made LCDs usable not only in commercial products but also in hobbyist projects By themselves Liquid Crystal Displays can be difficult to drive because they require multiplexing AC drive waveforms and special voltages LCD modules make this driving simpler by attaching hardware to the raw glass LCD to assist in some or all of these rudimentary driving tasks LCD modules can be split into two groups those that have builtin controller and driver chips and those that have only driver chips LCD displays that do not have controllers are typically used with powerful hardware such as a laptop computer where a video controller is available to generate the complex drive signals necessary to run the display Most color and large greater than 320x240 monochrome displays are of this type The category of display modules that have builtin controllers can be split again into character LCD modules and graphic LCD modules Character modules can display only text and perhaps some special symbols while graphic modules can display lines circles squares and patterns in addition to text Some examples of graphic LCD controller chips are the Toshiba T6963 SeikoEpson SED1330 and Hitachi HD61202 Here we will be primarily concerned with character LCD modules that have the Hitachi HD44780 controller builtin Nearly every pixelbased alphanumeric LCD module made today uses the Hitachi HD44780 LCD controller chip or a derivative such as the SeikoEpson SED1278 This apparent standardization in character LCDs has become extremely bene cial to design engineers and hobbyists Dozens of manufacturers produce literally hundreds of models of LCD modules using this controller chip The smallest of these displays is only one line of 8 characters the largest is four lines of 40 characters each Other common sizes are 16x1 20xl 20x2 20x4 40x1 and 40x2 characters x lines Fortunately all HD44780based displays of any size use the same standard 14 wire interface Therefore code and hardware made for one sizetype display can be painlessly adapted to work for any HD44780 compatible device Information about these displays can be easily obtained on the web by including HD44780 in your search keywords Because of their widespread use these displays can be purchased surplus with typical prices of 3 for small displays to 20 for large ones 2 Interfacing your LCD module The microcontrollermicroprocessor interface to HD44780 LCD modules hereafter generically referred to as character LCD modules is almost always 14 pins Table 1 shows the basic pinout You may nd that some displays have additional pins for backlighting or other purposes but the rst 14 pins still serve as the interface 2 Excerpts from httpWWW tanfnrd 791 tutorial ndf earch0022l TD447900 7m 1300 The first three pins provide power to the LCD module Pin 1 is GND and should be grounded to the power supply Pin 2 is VCC and should be connected to 5V power Pin 3 is the LCD Display Bias By adjusting the voltage or duty cycle of pin 3 the contrast of the display can be adjusted Most character LCDs can achieve good display contrast with a voltage between 5V and 0V on pin 3 Note that greater contrast comes with lower voltage and you should never apply a VLCD higher than VCC Some displays that are specially made to work over a large temperature range may require a negative voltage to achieve readable contrast Pins 45 and 6 are the control lines for the LCD These lines indicate what kind of transaction you are proposing to do over the data lines DBO7 The state of RS indicates whether you wish to transfer commands or display data The RW line indicates whether you intend to read or write Finally the E line tells the display when you are actually ready to perform the transaction The control lines RS RW and E along with the data lines DBO7 are standard digital logic inputs or outputs Remember than when performing reads you must set the port connected to DBO7 to be input Table 1 LCD pinuut list EHUI 1 5 7 rvvv UE l gt W 3 tummy rim in 5 5 Wu 0 EH Q CTEP Ll Figure 397 RCM 3000 interface with LCD on ECE 341 project PCB As shown in Figure 7 the system used in the ECE 341 lab uses Port A of the RCM 3000 processor for data lines and bits 2 4 and 5 of port D for the handshaking and controls lines All handshaking and control lines are outpum from the RCM 3000 unit and must be bitbanged to implement the required control The RS and W line are the control signals that are connect to the RCM 3000 Port D bis 4 and 5 The El line is the handshaking signal for this interface and it is controlled by the RCM3 3000 Port D bit 2 Additional details concerning the exact sequence required to execute a data transfer to or from the LCD will discussed in later sections of this chapter The contrast adjust can be used to make the LCD more readable as viewed from various angles of incidence Some character LCD models use pin 15 for enabling additional lines These unis actually have dual controllers with shared RS and RW control lines but with separate enable handshaking signals The ECE 341 Project board is able to control multiple line LCD units and uses Port D bit 3 of the RCM 3000 processor 3 Accessing your LCD module Character LCD modules are accessed through only two registers the Command Register and the Data Register When you perform a read or write with RS low you are accessing the Command Register and giving the module instructions When you read or write with RS high you are accessing the Data Register and reading or writing charactersdata from or to the display Table 2 contains pseudocode examples of reads and writes to the two registers The p d d can be 39 J on any 39 and assumes that DBPORT is the port to which DBO7 are connected Since some microcontrollers are very fast delays may be required between the steps described in the pseudocode See the concise datasheet on the course web page for more information Table 2 LCD register access pseudo code Reading rriim 2 register Writing to a register 50K RS iiiie lilng or m to iieeigiiiiie the m RS iiiie high or low in Llcslg dic iiie rcgisicr mi v iin 0 deco rcgisicr you Wish to JCCC N sci R W lmC high in indicate a rcml set R line low 0 lmllCIIKC a who u sci DBPORT m inpm SCI DBPORT m mnpui 4 set E llnc iiiin in begin ma cycle 4 Hltcddm m DBPORT 5 pause in 411m LCD in mm iiiciiiiiii s CIElmclilghi0l1 gmH39Hl mic ii reiiiiiii fi39omDBPORT 6 misc mum LD loacccpt iiiciiiiiii 7 m E llnC im 0 ll l39li mi ri 7 scrE lmC lo m nishm39itccwlc 3a Rabbit Parallel Port A l regress for a moment to discuss the use of Port A for the bidirectional data bus In previous chapters we discussed how the direction of the data lO data lines are specified using the PxDDR register where X is CD E F or G For example when all of Port G bits are to be used for outputs we use the instruction WrPortI PGDDR ampPGDDRShadow OXFF Port A is an exception to this general rule Since Port A is also used for Rabbit processor s masterslave operation the direction of Port A and the functionality of the Port A bits are defined by the SPCR register as shown in Table 3 In order to program Port A as inputs the value 0x80 must be written to the SPCR register To make port A an output port the value 0x84 must be written to the SPCR port Port A bis may not be individually assigned as inputs or outputs Table 3 Rabbit 3000 processor SPCR bit de nitions Bit 7 Write Bits 65 Bits 10 Only Read Only B39t 4 B39t 3 2 Wr39te on Write Only 00no slave 00disable slave port port A is a byte wrde interrupt input port 0 obey Reads SMODE Oldisable slave port port A is a byte wrde ppnenable SMODE pins output port pins model x slave port l1gnore smodeo lOenable the slave port imam1 t SMODE pins llEnable the auxiliary IO bus Parallel 01 p 1 Port A is used for the data bus and Parallel 10 piig ty 2 Port B72 is used for the address bus p ty ll prrorrty 3 4 Initializing and programming your LCD Character LCD s based on the Hitachi HD44780 controller have two address pointers The display RAM DDRAM pointer contains the address of the position where the cursor is located and or where the next character entered will be located When data is written to the LCD with the RS control line asserted high the information on the data lines will be displayed on the LCD3 Data is entered as ASCII encoded text4 Non ASCII data will be displayed as either special graphics characters built into the LCD or special programmable characters5 Writing bit patterns to the character generator RAM CGRAM creates programmable characters Character LCDs must be initialized after poweron and before writing data to the display The initialization must consist of at least a Function Set command preferably followed by an Entry Mode Set Display Control and a Clear Display Issuing each of these commands after the Function Set ensures that you know the state of your display Instructions on how to issue and use these commands can be found by looking at the concise datasheet or at the HD44780 controller datasheet for more information Below is an example initialization sequence and hello world program assuming you ve programmed the C functions LCDCommandWr unsigned char command to write commands to the LCD and LCDputc unsigned char data to write data to the LCD Listing 1 Peseudo code for initializing and writing to the LCD initiatize d LCDCommandWr0x38 function set Busy flag is not valid swidelayims5 User supplied software delay function 87bit interface 2 display lines 5x7 font LCDCommandWr 0x06 entry mode set Busy flag is not valid swidelayimsl User supplied software delay function turn display on cursor on no blinking 3h n39MOmeiae 0 hm ibk dmamj 4 htggwwwlOOkuptablescom shttn39 hnmeim l html 8051 lcd userchar LCDCommandWr 0x10 shift mode direction wait for not busy see Listing 5 whileck bf addr amp 0x80 increment automatically no display shift LCDCommandWr OXOE display control wait for not busy see Listing 5 whileck7bf7addr amp 0x80 LCDCommandWr 0x01 clear display set cursor position to zero Using the user supplied LCDputc function see Listing 4 characters can be sent to the LCD by executing the following list of C instructions write hello world to the display LCDputc H LCDputc e LCDputc l LCDputc l LCDputc o LCDputc LCDputc W LCDputc o LCDputc r LCDputc l LCDputc d After initialization the text can also be displayed on the LCD using the function LCDputs Hello World Where the function LCDputs is de ned as Listing 2 C function for writing a string of ASCII tect t0 the LCD Void LCDputschar m whiles LCDputcs Refer to httphomeiaenluserspouwehalcdlcdshtml6 for additional details on the HD44780 based character LCD 5 Interface between the LCD module and the Rabbit 3000 Microprocessor Table 4 and Table 5 shows the control line states and the data values to implement LCD controls described in part 4 above The function LCDCommandWr must set the RS and RW lines low prior to asserting the LCD enable pin high The data must be written to port A prior to asserting the LCD enable pin low Figure 10 Shows the timing required to write to and read from the LCD unit Table 6 de nes the timing parameters identi ed in Figure 10 The four LCD initializing commands can now be interpreted in light of the instruction set shown in Table 4 The LCDCommandWr function writes data to the LCD with the RS and RW controls low After setting the data lines and control bits the 6httrrhnmeiae html enable bit is toggled high and back low The enable line must be set back low for the LCD to record the new control and display data The rst command in Listing 1 LCDCommandWr 0x38 quot calls a function that sets the data bits for 38h The LCD register is selected by the bit position of the most signi cant high bit of the data bus which for this case is D5 D4 controls the number of data lines used for interfacing between the microprocessor and the LCD unit Character LCD units can operate using either 4 or 8 bit data busses This will be discussed in greater detail later in this chapter For the LCD models used in the ECE 341 lab D3 must be set to a one and bit D2 is a don t care and may be either zero or one The second command in Listing 1 LCDCommandWr 0x06 quot calls the same function described in the paragraph above to set the entry mode When set high bit Dl specifies that the address pointer to the LCD display RAM should be incremented after each new display character is written to the LCD If this bit were not set the address pointer would decrement after each new character and the text would appear to be entered from right to left With bit D0 set to a zero all of the characters on the display remain fixed in their positions If bit D0 is set high the display would shift The direction of shift would be specified by the CursorDisplay Shift instruction Table 4 HD44780 instruction set Instruction RS R W D7 D6 D5 D4 D3 D2 D1 D0 Clear display 0 0 0 0 0 Cursor home 0 Entry mode 0 set Display 0 OnOff control Cursor display 0 shift Function set 0 Set CGRAM address Set DDRAM address Read busy flag and address counter Write to CGRAM or 1 DDRAM O O 0 i 0 0 0 0 0 0 0 0 0 0 0 0 0 0 l 0 0 0 0 l D S R 0 0 0 l c L 0 0 1 DL N F 0 l CGRAM address 1 DDRAM address BF CGRAM DDRAM address write data Code 0 l 1 MDS C B Description 12122113 Clears display and retains cursor to the home 1 64ms position address 0 39 Returns cursor to home position address 0 Also returns display being shifted to the 1 64ms original position DDRAM contents remains 39 unchanged Sets cursor move direction MD specifies to shift the display S These operations are 40uS perform ed during data readwrite Sets OnOff of all display CD cursor OnOff 40uS C and blink of cursor position character B Sets cursormove or displayshift SC shift direction RL DDRAM contents remains 40uS unchanged Sets interface data length DL number of 40uS display line N and character fonth Sets the CGRAM address CGRAM data is sent 40uS and received after this setting Sets the DDRAM address DDRAM data is 40uS sent and received after this setting Reads Busyflag BF indicating internal operation is being performed and reads OuS CGRAM or DDRAM address counter contents depending on previous instruction Writes data to CGRAM or DDRAM 40uS Code Execution Instruction R Description H RS W D7 D6 D5 D4 D3 D2 D1 D0 tlme Read from CGRAMor 1 1 read data Reads data from CGRAMorDDRAM 40uS DDRAM Remarks DDRAM Display Data RAM CGRAM Character Generator RAM DDRAM address corresponds to cursor position Don39t care Based on F05c 250kHz Table 5 Bit names for commands listed in Table 4 Setting Status MD 0 Decrement cursor position 1 Increment cursor position S 0 No display shift 1 Display shift D 0 Display off 1 Display on C 0 Cursor off 1 Cursor on B 0 Cursor blink off 1 Cursor blink on SC 0 Move cursor 1 Shift display M 0 Shift left 1 Shift right DL 0 4bit interface 1 8bit interface N 0 18 or 111 Duty 1 line 1 116 Duty 2 lines F 0 5x7 dots 1 5x10 dots BF 0 Can accept instruction 1 Internal operation in progress The third command in Listing 1 LCDCommandWr 0x10 quot calls the function to enter a command that sets the cursor or display shift and the direction With bits D3 and D2 both set low the cursor will shift right after each display character has been entered If D3 is set high all of the display characters will shift the direction speci ed by D2 instead of the cursor The fourth command in Listing 1 LCDCommandWr OXOE quot calls the function to enter a command that controls that turns the display off or on and controls the cursor display mode When bit D2 is set high the LCD display is turned on When bit D1 is set high the LCD cursor is turned on and when bit D0 is set high the LCD cursor will blink on and off The nal command in Listing 1 LCDCommandWr 0x01 quot calls the function to enter a command that clears the LCD puts the cursor in the left column and sets the display address pointer to zero To this point all data has been written to the LCD Data in both the CGRAM and the DDRAM can also be read if both the RS and the RW bits are asserted high If the LCD is read with the RS bit set low the RW bit must still be set high to read the LCD the address pointer of either the DDRAM or the CGRAM can be read as well as the LCD busy ag In order to read or write the CGRAM address a Set CGRAM Address command must rst be written to the LCD Likewise reading or writing to the DDRAM requires that the Set DDRAM Address command be sent to the LCD Sending the Clear Display command accomplishes that same instruction as setting the DDRAM to zero The Busy ag is the most signi cant bit when reading either the DDRAM or the CGRAM The LCD should not be written to as long as the busy ag is high The busy ag must be read with the direction of the RCM 3000 processor set for input and the control bits set as for reading the DDRAM or CGRAM The RCM 3000 Port A must be read while the LCD enable bit is high The enable line must always be set back low again before any new data can be read from the LCD Data from the LCD cannot change as long as the enable line is in the high state regardless of any internal changes of address or busy ag One nal point to note from Table 4 is the instruction execution times listed in the far right column These execution times represent the worst case conditions during which the busy ag will be read as high 5 Managing the LCD Six basic functions are required to ef ciently manage the LCD These are initializing writing commands reading the address and busy ag and writing display character data The collaboration diagram shown in Figure 8 describes the relationship of these six functions Other functions may be necessary if you go beyond displaying simple text messages on the LCD The actions of the six basic functions will be explained in detail below LCD Text String Listii ig 2 Posltion Control code ASCH Char Controi code LCD Display Commands QueW Character 5mg 3 W Listing 4 LCD Cursor 630 Position Ps 900 5b lg JPPV WE 9 Read LCD Status Figure 12 Figure 8 Collaboration diagram for basic LCD control functions 13 o Initialize LCD This function must write a sequence of commands to the LCD with RS bit low The basic setup is described by the code in Listing 1 but lack the prescribed delays between each write command This delay is necessary because the busy ag is not valid until after the initializing sequence has completed It is recommended that a 30ms delay follow the set entry mode command and 2 ms following all subsequent commands in the initializing sequence Generally each of the commands are written by calling a speci c function that asserts the RS and RW bits low as discussed in the following section 0 Write Command after initialization To write an LCD command execute the following sequence Listing 3 Write command sequence of tasks 1 Check busy ag until not busy and read DDRAM address usually accomplished in a separate function see Figure 8 RS Port D bit 4 and RW Port D bit 5 pins are asserted low Port A direction is set for output Write the command data to Port A The LCD enable pin Port D bit 2 is asserted high The LCD enable pin Port D bit 2 is asserted low P V RP N This sequence of operations meets the ordering requirements shown in Figure 10 The timing constraints from Figure 10 and Table 6 require that a minimum of 140 ns tAS be between steps 2 and 4 Steps 3 and 4 can be executed in reverse order provided that the RS and RW signals are asserted 140 ns before the enable signal is asserted high As long as the data is written to Port A 195 ns prior to step 5 the data lines can be written at any time hence the data setup time is specified by the parameter tDSW Most of the minimum timing requirements are listed in Table 6 are easily met when the RS RW and Enable controls are bitbanged on relatively slow microprocessors such as the R3000 However the Enable cycle time specification requires a onemillisecond interval between two consecutive rising edges It is very likely that the R3000 processor will violate that constraint unless a delay function is employed 14 LCDputCtrl i Yes Set RSO RWO t Set Port A Output t Output to Port A t Enforce ms delay l Pulse E high i lt Return gt Figure 9 Flow diagram for the LCDCommandWr function RS mm mm su1 1 R W Vim ViL l DBO DB7 gtltW Whom KW m Figure 10 LCD Timing Diagram Table 6 LCD control for timing diagram shown in Figure 10 Write RS RNV RS RW DBODB7 0 Write Display Character The sequence for Writing display data to the LCD is much the same as Writing LCD control commands There are however two notable exceptions The rst exception is the need to lter out ASCII control characters The LCD control actions to implement common ASCII control characters are listed in Table 7 to the left a Yes 7 do nothing No 7 Continue 2 Test address for 1 position ofLine 2 a Yes 7 set DDRAM address for end ofline 1 b No 7 decrement DDRAM A dress and write new address to LCD 3 thackspace is non destructive a nothing b Yes 7 write space character and repeat steps 2 and In general the LCD character display requires the following sequence The timing requirements shown in Figure l and Table 6 must be observed From personal experience I can guarantee that your LCD will have inconsistent and erratic behaVior including the display unless the sequences and timing constraints are observed Listing 4 Sequence of tasks for writing a display character or ASCII control character 1 Check busy flag until not busy and read DDRAM address 2 Test character for control character a send appropriate write control function b exit function 3 Test address for end of line OXOf is the cursor position for the last display character on line one and 0x4f is the last character display position on line two a send new DDRAM address to write control b test busy flag until not busy 7 ignore cursor address c continue to write display character RS Port D bit 4 is asserted high and RW Port D bit 5 pins is asserted low Port A direction is set for output The data is written to Port A The LCD enable pin Port D bit 2 is asserted high The LCD enable pin Port D bit 2 is asserted low Set Port A for input OPOSQEJ He o Read Busy Flag This function must be called after writing every of a display characters or control instructions following the initialization sequence The LCD must be read with the RW bit set high and the RS bit set low The timing requirements shown in Figure l and Table 6 must be observed for this operation as well Since reading the busy flag also results in reading the DDRAM or CGRAM address the function can return the data as a single byte or as two separate variables The following steps are needed to read the busy ag Listing 5 Sequence of tasks for reading the busy ag Set RS low Set WR high Port A is set for input Set the enable signal high Read Port A Set the enable signal low 09 99591 Should the LCD need to be read again such as may be required when polling the busy flag steps 4 through 6 must be repeated in sequence otherwise the LCD output will not change The timing for the read operation shown in Figure 11 uses parameters defined in Table 8 1 f R tax nixEli quot A gquot 1 mm quot quotH J39 quot I39 a tan 7 7 I m1 l ll39i i q tw z quot1 tt II 1quot E If VH1 VlHl quot21R If WU vnu f WU 1 H tdh 7 mm mm o e o D B 7 W W DATA ital quot 1b q F Figure 11 LCD read cycle timing l7 LC Dreadbf l Set Port A for Input l Set EN RSO RW1 l Enforce ms delay l Set E1 l Delay 12 ms t Read Port A l Set EO Geturn BFlAch Figure 12 Flow diagram for the LCD check busy and read cursor address function Table 8 LCD control timing for timing diagram shown in Figure 11 RS RW RS RNV DBODB7 6 Programmable Graphics Character Generation7 When you send the ASCII code for a character like quotAquot to an LCD module the module39s controller looks up the appropriate 5x8 pixel pattem in ROM readonly memory and displays that pattem on the LCD That charactergenerator ROM contains 192 bit maps corresponding to the alphabet numbers punctuation Japanese Kanji characters and Greek symbols The ROM is part ofthe main LCD controller eg HD44780 KS0066 etc is maskprogrammed and cannot be changed by the user The manufacturers do offer altemative symbol sets in ROM for European and Asian languages but most U S distributors stock only the standard character set shown in the LCD Serial Backpack manual Alphanumeric LCD controllers do not allow you to turn individual pixels on or offthey just let you pick a particular pattem corresponding to an ASCII code and display it on the screen If you can39t change the ROM and you can39t control pixels how do you create graphics on these LCDs Easy There39s a 64byte hunk of RAM randomaccess memory that the LCD controller uses in the same way as charactergenerator CG RAM When the controller receives an ASCII code in the range that39s mapped to the CG RAM it uses the bit patterns stored there to display a pattem on the LCD The main difference is that you can write to CG RAM thereby defining your own graphic symbols A character LCD that uses the HD44780 controller allow for eight programmable characters The character pattems must be first written to the CGRAM of the LCD First the CGRAM must be select by setting the CGRAM address for the character that is to be programmed Each eight consecutive addresses starting at CGRAM address zero are assigned to one programmable graphical character Each bit of the data at each address sets the pixel on 1 or off 0 The pixels on a particular row at the right of the character display have the lowest binary value The rows of pixels start at the top and move down the character as the addresses increase in value as shown in Figure 13 7Excerpts taken from httpwwwgeocitiescorndjnceraydin lcdcustomhtrn 18 Bitmap Layou Symbol Luca ons Commanmosel s A N s E ByleValues ASCII age 7 3 s s 5 binary decima Code Address Men DEDDD mama I W Wm GUIDE mama 4 1 72 M22 EDDD xxxauuln 2 M23 II I mum 3 2 so Wequot EDDD 2 3 88 quot5 GUIDE 4 4 as mes DEEDS 5 104 M CHEESE I 6 112 7 120 FiaurP 11 A L m umL s 29 m Ofpxxels aymuumA L 4 and dxsplaymg chamders aLLhaL new locauon The steps are Lisu39ng 6 Steps m pmgram graphical chmcms Reset RS and WW pms arms LCD m prepare me LCD m accepllnstrumuns RAM SvmchtuDATA MODE bychangmgsemng meRs pm uls cc RAM addresses1uslas n dues cursur pusuuns un me away Tu lave cc RAM switch m COMMAND MODE m seladdress cuunterlu a mud msplay ddr wnmmw hm Tu see me susmm manner yuu have de ned pnmAscu Dudes n mmugh 7 3 mm www gemues cumdmmmydmlcdcharmlc him y 19 mm www newhavendlsglay cumg dfnhdr ll klzrnsggrfuwrl gdf Chapter 4 Timing Rev 242008 How long does it take Each instruction that the processor executes requires nite time Take for example the program statement written in C to write to an IO port WrPortT PBDDR ampPBDDRShadow PBDDRShadowl 0x82 This instruction is implemented as a sequence of assembler language instructions WrPortI PBDDR ampPBDDRShadow PBDDRShadowl 0x82 laae 2AC3C6 1d hl 0xC6C3 ll labl 2600 1d h 0x00 4 lab3 EB ex de hi 2 lab4 218200 1d hl 0x0082 6 lab7 EC or bi de 2 labB 7D 1d a l 2 lab9 ED56 ipset l 4 labb D3324700 ioi 1d 0x0047 a ll labf 32C3C6 1d 0xC6C3 a 10 lac2 EDSD ipres 4 lac4 EF rst 0x28 10 The last number listed for each assembler language instruction lists the number of CPU clock cycles required for execution For this particular write port instruction the total number of clock cycles is 66 There are two crystal cycles for each clock cycle and for the RCM 3000 processors the period of the clock is 68ns Hence the write port instruction requires a total of approximately 45 us to execute The execution time required any particular C 39 39 is 39 39 39 by the l 39 39 of the C statement the assembler code that the C instruction is translated into and the speed that the processor is running Pacing the computer software delay routines Generally microprocessor base systems are designed to operate with time to spare Code must be written that allows the rest of the world to catch up This is done using time delay routines Say for example I need to delay one second How can I do this knowing that the microprocessor always wants to be executing the next line of code One way is to call a function that does nothing but kill time A delay routine has two attributes how many units of time are to be delayed and what constitutes a unit of time Common units of time are related to cycles of the CPU crystal or milliseconds of time The RCM3000 unit uses a 147456MHZ crystal with a processor clock doubler As stated above the clock frequency is the one half crystal frequency Hence the clock frequency is the same as the crystal frequency Dynamic C has three built in timing global variables MSiTIMER SECiTIMER and TICKiTIMER See text section 663 pg 204 A delay function call also be written based upon the expected time to execute code This is frequently accomplished by executing a loop that simply decrements the value stored in a variable Such aloop would look like for i 0 ilt N39UM i whereNUMis aconstant value A delay function of length 65535 ms or less including zero can be implemented as shown in Listing 1 and Listing 2 Listing 1 shows how for loops are used to create a time delay Listing 1 Software delay function void delaymsunsigned int delaytime define MSCOUN39I39 39239 Value to be determined by trial and error int ij for j0 jltdelaytime j for i 0 ilt MSCOUNT i Delay functions of longer duration than 65535 ms can be generated by calling the delayims function more than once An alternate software delay function is shown in Listing 2 The advantage of Listing 3 is that the assembler code generated from the C function results in very few lines of assembler code and would enable computing the exact value needed for MSiCOUNT rather than using trial and error methods Listing 2 Software delay function void delayms unsigned int delaytimer define MSCOU39NT Value to be determined by trial and error unsigned int loop while delaytime loop MSCOUNT while loop Listing 3 Assembler listing for delay 100p code loop MSiCOUNT lad9 21C800 1d hl 0x00C8 6 ladc D400 1d sp 0x00 hl ll while oopee lade C400 1d hl sp 0x00 9 lan 2B dec hi 2 lael D400 1d sp 0x00 hl ll lae3 23 inc hi 2 lae4 CC bool hi 2 laeS CAEBlA jp z OXlAEB 7 Although alternate methods will be presented in future chapters the software delay routine remains a timetested simple method of creating delays that all microprocessors support When code is is called for cyclic delays processing other code in the program can create delay time inaccuracies As will be discussed in following chapters an approach using interrupts should be used if highly accurate delays are required Calibrating Time Delay How accurate is the program listed on page 204 of the teXt How can this be determined If you use the delayims function listed above what value should be used for MSiCOUNT and how accurate is the delay For the delayims function you can look at the assembler code and add up the execution times You can also add software code to make the delay time observable by toggling a pin on the microprocessor This requires that eXtemal instrumentation be connected to the pin of the board connected to that IO port for the bit being toggled Suitable instrumentation for this test include frequency counters and oscilloscopes Now one must consider the appropriate place to insert the code to appropriately set the 10 pin high or low realizing the inserting such code may affect the accuracy of the delay function It is advisable to place the instrumentation code where it will be executed the minimum number of times If calibrating using trial and error methods to determine MSiCOUNT there are methods to help you converge more quickly The procedure starts by selecting a value for MSiCOUNT in the function Add instrumentation code described in the previous paragraph and shown in Listing 4 Using a test program call the delayims routine with a delay of a known delay Using an oscilloscope measure the period that PG7 is high Assign the initial MSiCOUNT to be MSiCOUNTl and the measured time to be delayl Compute the neXt guess for MSiCOUNT from the following equation MSiCOUNT MSiCOUNTlNl ms delayl where N is the desired delay in milliseconds Repeat this process until the measured delay equals the desired delay The calibration should be checked over the range of anticipated delays for your program Listing 4 Software delay function with instrumentation void delayms unsigned int delaytimer l define MSCOU39NT Value to be determined by trial and error unsigned int loop BitWriteIPGDR ampPGDRShadow 1 7 while delaytime l loop MSCOUNT while loop l BitWriteI PGDR ampPGDRShadow 0 7 l Pacing the computer hardware delay routines Hardware delays use timers that are internal to the microcontroller to generate interrupts Chapter 11 of the Rabbit 3000 users manual provides the operating details for the Timers A and B See Rabbit 3000 Microprocessor User s Manual at httpwww quot39 39 39 39 39 39 quot39quot V quot4 htm The RCM 3000 crystal frequency is 147456 MHz which is multiplied by two inside the Rabbit processor Therefore the CPU oscillator and the period clock PCLK both operate at 294912 MHZ Timer A is made up of ten 8bit counters All timers can generate an interrupt at the rate of the PERCLK divided by the constant programmed in for that timer The output from a timer register is determined from the equation FTJMERX PERCLK N where N is the timer constant Solving for N use the equation N PERCLK F HMERX With the period clock xed at 294912 MHZ the minimum frequency output is 115200 KHZ or if PERCLK2 is used then the minimum frequency is 57600 KHZ or a maximum delay for a single time of 17361111 us The values actually programmed into the Timer A registers are the divider value minus one For example to divide Timer A1 by 200 Register TATlR must be set for 199 using the WrPortI instruction WrPortI TATlR ampTAT1RShadow 199 Note Timer A timing registers TAT1R through TAT10R are write only registers The only way to ready these registers is by reading the appropriate shadow register associated with a particular Timer A register To set up a timer interrupt based upon the RCM 3000 Timer A that are longer than 1729 us two divider constants must be operated in series The output of Timer A1 can be used as an input for A2 through A7 timers See text by Hyder and Perrin page 254 To use a timer for a xed rate interrupt control you should select a timer A2 through A7 that is not being used for another function in your system For our working examples we will use timer A2 since we are not using Serial Port E If we want a 1000Hz assuming that we are using PERCLK for the input to timer A1 and the output of timer A1 as the input to timer A2 The output of timer A2 will be used to generate a 1 ms interrupt With the divider for Timer A1 set for 256 then timer A2 must be set to divide the Timer A1 output by 11565 Taking this approach results in an error because the dividers can only be set for integer values Hence timer A1 is set for 256 and A2 for 115 results in 1001739 Hz or 0174 error The problem now becomes to determine the combination of constants for A1 and A2 that produces the smallest error For example Using A1202 and A2 146 results in an error of only 0027 These values were not determined by good guessing It was determined using the power of the Rabbit processor to implement an exhaustive search of all possible combinations and selecting the combination with the smallest error The program to compute the combinations for A1 and A2 are left as an assignment for the student The developer has an option of prescaling PERCLK by two by setting bit zero of the TAPR register high This is required when using the Dynamic C development system If the input to timer A1 uses PERCLK2 instead ofPERCLK then A1101 and A2146 or A1 202 and A273 gives the same results for accuracy in generating a 1000 Hz output from A2 The order of the division makes no difference in the resulting frequency from A2 Remember that you must write N l when writing the constants to the timer registers Hence when the input to timer A1 is PERCLK then the programming statements shown in Listing 5 sets the output of timer A2 for 1000 Hz Listing 5 Code for setting Timer A constant registers WrPortI39139APR NULL 0 Set PERCLK as input for A1 WrPortI39139A391391R ETA39I39lRShadow 201 WrPortI39139A391392R ETA39I39ZRShadow 145 The exact count can be read from timer B only All of the timer A counters will only indicate when the terminal count has been reached A delay function can be written based upon polling techniques by reading the timer A status register TACSR Timer A1 through A7 will indicate that the corresponding timer has reached terminal count by setting the appropriate bit high All status bits are cleared when the status registers are read In the initialization code shown in Listing 6 the TimerA2 interrupt level is set for Level 2 using the following lines of code The various constants used in the function below are determined from the register de nitions on the Rabbit help IO registers under Timer A and B Registers This code also shows how the timers can be used to generate interrupts See Chapter 5 for more information on interrupts using the RCM 3000 rabbit processors cmwm smmm mm F39zul L39KinuAhh1kdiU h Lisljng Canme Axum mmim mg m u m mum 2 12 mum mm 2 Hum mm 1 Innsxgngd m an m Hmm I mud yum2 m 1th mhxu m mu mm H 1 Luna 1 mmxu nn unusmdmv umw an Eclnkgdfxm39l m 1 mmxu nzl un39rzxsmm my gt The following example shown in Listing 7 demonstrates using the timer status to implement a delay based upon Timer A The inititimer lnction sets up the one millisecond period as described above Bit seven of Port G is toggled to provide instrumentation that the program is functioning correctly The hwimsidelay function will delay the number of milliseconds passed to it in the argument list Since Timer A runs continuously as the heading notes indicate the delay can be off by up to l millisecond depending upon the counts in TAl and TA2 when the hwimsidelay function is called Testing of the program in Listing 7 reveals that the delay function is 99998 accurate There is no savings to processor execution time compared to other polling methods described in this chapter because the processor must continuously poll the TA2 status bit to determine when the millisecond interval has been completed Listing 7 Polled Hardware Timer Delay File name hwimsidelayc Author Richard W Wall Date Sept 10 2007 DescriptionThis program uses Timer AlA2 to establish a 100 ms delay based upon polling the Timer A2 quotTerminal Countquot status bit Bit zero of Port G is toggled after each 100 ms delay Accuracy may be up to 1 ms too short define A1 202 TATXR Values must be decremented by 1 define A2 73 define PCLK2 l Pd clk must be divided by 2 for Serial A Comm define TAiENbit 0 define TAlbit 1 define TA2bit 2 define PG7 0x80 void inititimer7Avoid void initiloiportsvoid void hwidelayimsint ms void mainvoid initiloiports inititimer7AL whilel hwidelayimslOO Delay 100 ms WrPortIPGDR ampPGDRShadowPGDRShadow A PG7 Toggle bit PGO Initialize Timer Al A2 for 1 ms clock void inititimer7Avoid Timer A divide perclk2 for clocking WrPortITAPR NULL PCLK2 Must be set high or Rabbit will crash Set time constant for timer Al WrPortITATlR ampTATlRShadow Al lL Set time constant for timer A2 WrPortTTAT2R ampTAT3RShadow A2 l Set Timer 2 to be clocked from Timer Al BitWrPortTTACR ampTACRShadow TRUE TA2bit Enable main Clock for Timer A BitWrPortTTACSR ampTACSRShadow TRUE TAiENbit Initialize TO ports direction and output void initiloiportsvoid WrPortTPGDDR ampPGDDRShadow OXFF Set Port G for output WrPortTPGDR ampPGDRShadow 0x00 CLear Port G Hardware based ms delay void hwidelayimsint ms whilems whilelBithPortTTACSRTA2bit Wait for TAZStatus bit


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Allison Fischer University of Alabama

"I signed up to be an Elite Notetaker with 2 of my sorority sisters this semester. We just posted our notes weekly and were each making over $600 per month. I LOVE StudySoup!"

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.