s05a: stacks / interrupts

74
S05a: Stacks 1996 1998 1982 1995 Required : PM: Ch 7.4, pgs 95-96 Wiki : Stack_( data_structure ) Recommended : Google "Activation Record" (Read 1 article)

Upload: yama

Post on 04-Jan-2016

52 views

Category:

Documents


6 download

DESCRIPTION

1996. 1998. 1982. 1995. S05a: Stacks / Interrupts. Required :PM : Ch 7.4, pgs 95-96 Wiki : Stack_( data_structure ) Recommended :Google "Activation Record" ( Read 1 article). CS 224. Learning Outcomes…. The Stack Subroutines Subroutine Linkage Saving Registers - PowerPoint PPT Presentation

TRANSCRIPT

Chapter 05 - Stacks

S05a: Stacks1996199819821995Required:PM: Ch 7.4, pgs 95-96Wiki: Stack_(data_structure)Recommended:Google "Activation Record"(Read 1 article)1CS 224BYU CS 224Stacks / Interrupts2ChapterLabHomeworkS00: IntroductionUnit 1: Digital LogicS01: Data TypesS02: Digital LogicL01: Warm-upL02: FSMHW01HW02Unit 2: ISAS03: ISAS04: MicroarchitectureS05: Stacks / InterruptsS06: AssemblyL03: BlinkyL04: Micro-archL05b: Traffic LightL06a: Morse CodeHW03HW04HW05HW06Unit 3: CS07: C LanguageS08: PointersS09: StructsS10: I/OL07b: Morse IIL08a: LifeL09b: SnakeHW07HW08HW09HW10Learning ObjectivesLearning OutcomesAfter completing this section, you should be able toExplain how subroutines are implemented in machine code.Describe what makes a subroutine cohesive and loosely coupled and why these are desirable.Give examples of what might be found in an activation record.Explain caller and callee safe subroutine.Describe how the stack is used in recursive functions.Explain how global and local variables are implemented.Explain how the stack is used by interrupt service routines.BYU CS 224Stacks / Interrupts3TopicsThe StackSubroutinesSubroutine LinkageSaving RegistersStack OperationsActivation RecordsRecursive SubroutinesInterrupt Stack Usage

Lab 5b: Traffic LightTermsActivation Record parameters activated on the stack by a subroutine callCallee-Safe subroutine saves registers used.Caller-Safe caller saves registers needing to be saved.Interrupt asynchronous subroutine call.LIFO Last In First Out, a stack.Loosely Coupled all parameters passed as arguments.Pop removing top element of stack.Push putting an element on a stackStack last in, first out abstract storage data structure. Stack Pointer address of stack.Stong Cohesion subroutine performs one specific task.Subroutine synchronous task or unit.BYU CS 224Stacks / Interrupts4StacksStacks are the fundamental data structure of computers today.A stack is a Last In, First Out (LIFO) abstract data structure.A true stack is a restricted data structure with two fundamental operations, namely push and pop.Elements are removed from a stack in the reverse order of their addition.Memory stacks are used for random access of local variables.BYU CS 224Stacks / Interrupts5The StackMSP430 StackHardware support for stackRegister R1 Stack Pointer (SP)Initialized to highest address of available RAMMSP430G2553 0x0400 (512 bytes)MSP430F2274 0x0600 (1k bytes)Stack grows down towards lower memory addresses.Initialize stack pointer at beginning of programSTACK .equ 0x0600 ; top of stackstart: mov.w #STACK,SP ; init stack ptr

BYU CS 224Stacks / Interrupts6The Stack0x00000xFFFF0x02000x06000xF800MSP430F22740x01FF0x05FFFLASHMain MemoryRAMPeripheralsPortsSFRsInterrupt Vectors6MSP430 StackThe MSP430 stack is a word structureElements of the stack are 16-bit words.The LSB of the Stack Pointer (SP) is always 0.The SP points to the last word added to the stack (TOS).The stack pointer is used byPUSH push a value on the stackPOP pop a value off the stackCALL push a return address on the stackRET pop a return address off the stackRETI pop a return address and status register off the stackInterrupts push a return address and status register on the stackBYU CS 224Stacks / Interrupts7The StackComputer Memory Up or Down?BYU CS 224Stacks / Interrupts8x0000xFFFFUpDownxFFFFx0000DownUpThe Stack1996199819821995Unlike a coin stack, a memorystack DOES NOT move theData in memory, just thepointer to the top of stack.StackTOSBYU CS 224Stacks / Interrupts9Quiz 5.1List the values found in the stack and the value of the stack pointer after each instruction.Push #0x0018Push #0x0025Push #0x0058Pop R15Push #0x00360x0282

0x0280

0x027E

0x027C

0x027A

0x0278x0280R1TOPInstructions:99SubroutinesA subroutine is a program fragment that performs some useful function.Subroutines help to organize a program.Subroutines should have strong cohesion perform only one specific task.Subroutines should be loosely coupled interfaced only through parameters (where possible).Not affected by changes to other subroutines.Subroutines keep the program smaller.Smaller programs are easier to maintain.Reduces development costs while increasing reliability.Fewer bugs copying code repeats bugs.Subroutines are often collected into libraries.

BYU CS 224Stacks / Interrupts10Subroutines10Here's some old-school software engineering terms for you. Cohesion and coupling. Cohesion is how well a subroutine holds together on its own, and coupling is how clean the interfaces between your routines are (or how self-sufficient your routines are).

With coupling, generally the looser the better. Interfacing only through parameters ("data coupling") is good low coupling, while using global variables ("common coupling") is very high coupling. When you have a high number of parameters, what is usually the case is that someone has tried to hide their common coupling with a thin veneer of data coupling. Its bad design with a paint job.

With cohesion, the higher (more cohesive) the better. Any routine that modifies eight different things is also quite likey to suffer from low cohesion. I'd have to see the code to see for sure, but I'd be willing to bet that it would be very difficult to clearly explain what that routine does in a short sentence. Sight unseen, I'd guess it is temporally cohesive (just a bunch of stuff that needs to be done at roughly the same time).The Call / Return MechanismBYU CS 224Stacks / Interrupts11SubroutinesSmaller programs.Easier to maintain.Reduces development costs.Increased reliability.Fewer bugs do to copying code.More library friendly.Faster programs.Less overhead.

Subroutine LinkageA subroutine is called in assembly using the MSP430 CALL instruction.The address of the next instruction after the subroutine call is saved by the processor on the stack.Parameters are passed to the subroutine in registers and/or on the stack.Local variables are created on the stack at the beginning of the subroutine and popped from the stack just before returning from the subroutine.At the end of a subroutine, a RET instruction pops the top value from the stack into the program counter.BYU CS 224Stacks / Interrupts12Subroutine LinkageBYU CS 224Stacks / Interrupts13Stack OperationsSingle operand instructions:

Emulated instructions:MnemonicOperationDescriptionPUSH(.B or .W) srcSP-2SP, src@SPPush byte/word source on stackCALL dstdsttmp ,SP-2SP, PC@SP, tmpPCSubroutine call to destinationRETITOSSR, SP+2SPTOSPC, SP+2SPReturn from interruptMnemonicOperationEmulationDescriptionRET@SPPCSP+2SPMOV @SP+,PCReturn from subroutinePOP(.B or .W) dst@SPtempSP+2SPtempdstMOV(.B or .W) @SP+,dstPop byte/word from stack to destinationSubroutine LinkageQuiz 5.2BYU CS 224Stacks / Interrupts14What is the value of the stack pointer after the second call to delay?Is there a problem with the program?start:mov.w#0x0400,SPmov.w#WDTPW+WDTHOLD,&WDTCTLbis.b#0x01,&P1DIR; P1.0 as output

mainloop:bis.b#0x01,&P1OUT; turn on LEDpush#1000call#delaybic.b#0x01,&P1OUT; turn off ledcall#delayjmpmainloop

delay:mov.w2(sp),r15; get delay counter

delaylp2:sub.w#1,r15; delay over? jnzdelaylp2; nret; y

.sect".reset"; reset Vector.wordstart; start address.endLab 5b: Traffic LightSaving and Restoring RegistersCalled routine -- callee-saveAt beginning of subroutine, save all registers that will be altered (unless a register is used to return a value to the calling program or is a scratch register!)Before returning, restore saved registers in reverse order.Or, avoid using registers altogether.Calling routine -- caller-saveIf registers need to be preserved across subroutine calls, the calling program would save those registers before calling routine and restore upon returning from routine.Obviously, avoiding the use of registers altogether would be considered caller-safe.Values are saved by storing them in memory, preferably on the stack.BYU CS 224Stacks / Interrupts16Saving Registers16Caller-Save vs. Callee-SaveBYU CS 224Stacks / Interrupts17call subroutineSave RegisterssubroutineRestore Registerscall subroutinesubroutineSave RegistersRestore RegistersSaving RegistersQuiz 5.3BYU CS 224Stacks / Interrupts18loop: xor.b #0x01,&P4OUT ; toggle LED call #myDelay ; delay some jmp loop ; repeat

myDelay: mov.w #0,r15 call #delay call #delay

delay: sub.w #1,r15 jne delay retWhat is wrong (if anything) with the following code?How many times will delay execute for each loop?How long will myDelay delay?Is myDelay callee-save?SPr15r140xf826SPBYU CS 224Stacks / Interrupts19Stack OperationsSubroutine Linkage0xf820: ...0xf822: call #subroutine0xf826: ...

subroutine:0xf852: push r150xf854: push r14

...

0xf882: pop r140xf884: pop r150xf886: ret0400:03fe:03fc:03fa:03f8:03f6:03f4:03f2:Unprotected!0xf826SPr150xf826SPr15r140xf826SPr15r140xf826SPr14r150xf826SPr14r150xf826SPActivation RecordsA subroutine is activated when called and an activation record is allocated (pushed) on the stack.An activation record is a template of the relative positions of local variables on the stack as defined by the subroutine.Return addressMemory for local subroutine variablesParameters passed to subroutine from callerSaved registers used in subroutine (callee-save)A new activation record is created on the stack for each invocation of a subroutine or function.A frame pointer indicates the start of the activation record.When the subroutine ends and returns control to the caller, the activation record is discarded (popped).BYU CS 224Stacks / Interrupts20Activation RecordsBYU CS 224Stacks / Interrupts21Activation Record Example .cdecls C,"msp430.h" ; MSP430DELAY .equ (50/8)

.text ; beginning of codereset: mov.w #0x0400,SP ; init stack pointer mov.w #WDTPW+WDTHOLD,&WDTCTL ; stop WDT bis.b #0x01,&P1DIR ; set P1.0 as output

mainloop: xor.b #0x01,&P1OUT ; toggle P1.0 push.w #DELAY ; pass delay count on stack call #delay ; call delay subroutine jmp mainloop

; delay subroutine: stack usage 4| DELAY | \; 2| ret | subroutine frame (6 bytes); (SP) => 0| r15 | /delay: push.w r15 ; callee-save mov.w #0,r15 ; use R15 as inner counter

delay02: sub.w #1,r15 ; inner delay over? jne delay02 ; n sub.w #1,4(SP) ; y, outer done? jne delay02 ; n pop.w r15 ; y, restore register(s) mov.w @SP+,0(SP) ; pop input delay count ret ; return from subroutine

.sect ".reset" ; MSP430 reset Vector .word reset ; start address .endDelay Activation Record: 4(SP) = delay count 2(SP) = return address 0(SP) = r15Activation RecordsStack: 2(SP) = delay count 0(SP) = return addressStack: 0(SP) = return addressStack: (emply)BYU CS 224Stacks / Interrupts22Recursive SubroutineA subroutine that makes a call to itself is said to be a recursive subroutine.Recursion allows direct implementation of functions defined by mathematical induction and recursive divide and conquer algorithmsFactorial, Fibonacci, summation, data analysisTree traversal, binary searchRecursion solves a big problem by solving one or more smaller problems, and using the solutions of the smaller problems, to solve the bigger problem.Reduces duplication of code.MUST USE STACK! Recursive SubroutinesBYU CS 224Stacks / Interrupts23Subroutine CallCALLSubroutineSyntaxCALL dstOperationdst tmp(SP2) SPPC @SPtmp PCDescriptionA subroutine call is made to an address anywhere in the 64K address space. All addressing modes can be used. The return address (the address of the following instruction) is stored on the stack. The call instruction is a word instruction.Status BitsStatus bits are not affected.ExampleSubroutine LinkagefuncMemoryBYU CS 224Stacks / Interrupts24CallRegistersCPUCall Instructioncall #func ; M(--sp) = PC; PC = M(func)PCPCPCIRData Bus (1 cycle)0x12b00x12b0fffe(+1 cycle)SPAddress BusSP0x4130Data Bus (+1 cycle)Data Bus (+1 cycle)(+1 cycle)PCALUADDERPCSP0x801eAddress Bus+2+2BYU CS 224Stacks / Interrupts25CALL ExamplesCALL #EXEC; Call on label EXEC or immediate address (e.g. #0A4h); @PC+ tmp, SP2 SP, PC @SP, tmp PCCALL EXEC; Call on the address contained in EXEC; X(PC)tmp, PC+2PC, SP2SP, PC@SP, tmpPCCALL &EXEC; Call on the address contained in absolute address EXEC; X(0)tmp, PC+2PC, SP2SP, PC@SP, tmpPCCALL R5; Call on the address contained in R5; R5tmp, SP2SP, PC@SP, tmpPCCALL @R5; Call on the address contained in the word pointed to by R5; @R5tmp, SP2SP, PC@SP, tmpPCCALL @R5+; Call on the address contained in the word pointed to by R5 ; and increment pointer in R5.; @R5+tmp, SP2SP, PC@SP, tmpPCCALL X(R5); Call on the address contained in the address pointed to by ; R5 + X (e.g. table with address starting at X); X can be an address or a label; X(R5)tmp, PC+2PC, SP2SP, PC@SP, tmpPCSubroutine LinkageBYU CS 224Stacks / Interrupts26Return from SubroutineRETReturn from subroutineSyntaxRETOperation@SP PCSP + 2 SPEmulationMOV @SP+,PCDescriptionThe return address pushed onto the stack by a CALL instruction is moved to the program counter. The program continues at the code address following the subroutine call.Status BitsStatus bits are not affected.ExampleSubroutine LinkageMemoryBYU CS 224Stacks / Interrupts27ReturnRegistersALUCPUADDERReturn Instructionret ; mov.w @sp+,PC0x801ePCIR0x12b00002SPAddress Bus(+1 cycle)Data Bus (+1 cycle)0x4130Data Bus (+1 cycle)0x4130PCPCPCAddress BusSPSPPCSPPC+2Quiz 5.4BYU CS 224Stacks / Interrupts28Change the following code to use a callee-save, loosely coupled, cohesive subroutine..cdeclsC,"msp430.h".textstart:mov.w#0x0400,SPmov.w#WDTPW+WDTHOLD,&WDTCTLbis.b#0x01,&P1DIR; P1.0 as output

mainloop:bis.b#0x01,&P1OUT; turn on LEDmov.w#10000,r15; delay counter

delaylp1:sub.w#1,r15; delay over? jnzdelaylp1; nbic.b#0x01,&P1OUT; turn off ledmov.w#0,r15; delay counter

delaylp2:sub.w#1,r15; delay over? jnzdelaylp2; nmov.w#0,r15; delay counter

delaylp3:sub.w#1,r15; delay over? jnzdelaylp3; njmpmainloop; y, toggle led

.sect".reset"; reset vector.wordstart; start address.endS05b: InterruptsRequired:PM: Ch 9.1-7, pgs 129-139PM: Ch 10.1-2, pgs 151-156PM: Ch 10.4-5, pgs 159-166PM: Ch 10.7-8, pgs 169-188PM: Ch 11.5, pgs 227-229Recommended:Intro to PWMFUG: Watchdog Timer+

29Learning ObjectivesLearning OutcomesAfter completing this section, you should be able toExplain what an interrupt is.Write an Interrupt Service Routine (ISRs).Use the Watchdog as a limited feature timer.Discuss the computer energy consumption issues.Use the correct processor clock for a given problem.Use low power mode to make the process sleep.Use timer interrupts for PWM.BYU CS 224Stacks / Interrupts30TopicsInterruptsInterrupt Service RoutinesInterrupt FlagsInterrupt VectorsInterrupt StackInterrupt LatencyEnergy ConservationLow Power ModesProcessor SpeedsClocksTimersWatchdog TimerSwitch DebouncePulse Width Modulation

Lab 5b: Traffic LightMain Routine(synchronous)

Interrupt Service RoutinesBYU CS 224Stacks / Interrupts31Interrupt Service RoutineInterrupt

Interrupt Service Routine(asynchronous)

Main Routine(synchronous)

Interrupt Service Routine(asynchronous)Main Routine(synchronous)

Interrupt Service Routine(asynchronous)Main Routine(synchronous)

InterruptsExecution of a program normally proceeds predictably, with interrupts being the exception.An interrupt is an asynchronous signal indicating something needs attention.Some event has occurredSome event has completedThe processing of an interrupt subroutine uses the stack.Processor stops with it is doing,stores enough information on the stack to later resume,executes an interrupt service routine (ISR),restores saved information from stack (RETI),and then resumes execution at the point where the processor was executing before the interrupt.BYU CS 224Stacks / Interrupts32InterruptsInterrupt MPUReset / Non-Maskable (NMI)

General Interrupt Enable (GIE)

Interrupt EnableInterrupt FlagsEach interrupt has a flag that is raised (set) when the interrupt is pending.BYU CS 224Stacks / Interrupts33InterruptsDevice InterruptEach interrupt flag has a corresponding enable bit setting this bit allows a hardware module to request an interrupt.Most interrupts are maskable, which means they can only interrupt if1) Individually enabled and2) general interrupt enable (GIE) bit is set in the status register (SR).Reset and Non-Maskable Interrupts (NMI) are reserved for system interrupts such as power-up (PUC), external reset, oscillator fault, illegal flash access, watchdog, and illegal instruction fetch.Interrupt VectorsThe CPU must know where to fetch the next instruction following an interrupt.The address of an ISR is defined in an interrupt vector.The MSP430 uses vectored interrupts where each ISR has its own vector stored in a vector table located at the end of program memory.Note: The vector table is at a fixed location (defined by the processor data sheet), but the ISRs can be located anywhere in memory.BYU CS 224Stacks / Interrupts34Interrupts0x00000xFFFFInput/Output0x02000x01FFStack0x06000x05FFProgram Code0xC0000xBFFFInterrupt Vector Table0xFFC00xFFBF16 vectors(ISR Addresses)MSP430 Interrupt VectorsINTERRUPT SOURCEINTERRUPT FLAGSYSTEM INTERRUPTADDRESSSECTIONPRIORITYPower-upExternal resetWatchdogPORIFGRSTIFGWDTIFGReset0xFFFE.reset15, highestNMIOscillator faultFlash memory violationNMIIFGOFIFGACCDVIFGNon-maskable0xFFFC.int1414Timer_B3TBCCR0 CCIFGMaskable0xFFFA.int1313Timer_B3TBCCR1 CCIFGTBCCR2 CCIFG, TBIFGMaskable0xFFF8.int12120xFFF6.int1111Watchdog TimerWDTIFGMaskable0xFFF4.int1010Timer_A3TACCR0 CCIFGMaskable0xFFF2.int099Timer_A3TACCR1 CCIFG,TACCR2 CCIFG, TAIFGMaskable0xFFF0.int088USCI_A0/USCI_B0 RxUCA0RXIFG, USB0RXIFGMaskable0xFFEE.int077USCI_Z0/USCI_B0 TxUCA0TXIFG, UCB0TXIFGMaskable0xFFEC.int066ADC10ADC10IFGMaskable0xFFEA.int0550xFFE8.int044I/O Port P2P2IFG.0 P2IFG.7Maskable0xFFE6.int033I/O Port P1P1IFG.0 P1IFG.7Maskable0xFFE4.int0220xFFE2.int0110xFFE0.int000BYU CS 224Stacks / Interrupts35InterruptsNon-MaskableInterruptsTimersPortsProcessing an InterruptProcessor completes execution of current instruction.Master Clock (MCLK) started (if CPU was off).Processor pushes Program Counter (PC) on stack.Processor pushes Status Register (SR) on stack.Interrupt w/highest priority is selected.Interrupt request flag cleared (if single sourced).Status Register is cleared:Disables further maskable interrupts (GIE cleared)Terminates low-power modeProcessor fetches interrupt vector and stores it in the program counter.User ISR must do the rest!BYU CS 224Stacks / Interrupts36InterruptsInterrupt StackBYU CS 224Stacks / Interrupts37InterruptsExecute Interrupt Service Routine (ISR)Item 2Item 1Prior to InterruptSPadd.w r4,r7 jnc $+4add.w #1,r6

add.w r5,r6PCInterrupt (hardware)Program Counter pushed on stackStatus Register pushed on stackInterrupt vector moved to PCFurther interrupts disabledInterrupt flag clearedSRPCItem 2Item 1SPxor.b #1,&P1OUTretiPCReturn from Interrupt (reti)Status Register popped from stackProgram Counter popped from stackSRPCItem 2Item 1SPadd.w r4,r7 jnc $+4add.w #1,r6

add.w r5,r6PCInterrupt LatencyThe time between the interrupt request and the start of the ISR is called latencyMSP430 requires 6 clock cycles before the ISR begins executingAn ISR may be interrupted if interrupts are enabled in the ISRWell-written ISRs:Should be short and fast get in and get outRequire a balance between doing very little thereby leaving the background code with lots of processing and doing a lot and leaving the background code with nothing to doApplications that use interrupts should:Disable interrupts as little as possibleRespond to interrupts as quickly as possibleCommunicate w/ISR only through global variables (never through registers!!!)BYU CS 224Stacks / Interrupts38Interrupt Service RoutineQuiz 5.5What conditions must be met before a device can interrupt the computer?

What is saved on the stack when an interrupt occurs?

Where are interrupt vectors located in memory? ISRs?

(T or F) Interrupts are predictable asynchronous events.BYU CS 224Stacks / Interrupts39Clocks

BYU CS 224Stacks / Interrupts41Processor Clock SpeedsPrograms can select clock source and speed.Energy (ie. battery life) is conserved by slowing the clock down.Faster clock = Higher performance, more power requiredSlower clock = Lower performance, less power required

Processor Clocks

; Set ACLK to 12kHzmov.w #LFXT1S_2,&BCSCTL3; Set DCO to 8 MHz: mov.b #CALBC1_8MHZ,&BCSCTL1 mov.b #CALDCO_8MHZ,&DCOCTL10% loss of power60% loss of power .cdecls C,"msp430.h"SMCLK .equ 1200000 ; 1.2 Mhz clockWDT_CTL .equ WDT_MDLY_8 ; WDT SMCLK, 8 ms (@1 MHz)WDT_CPS .equ SMCLK/8000 ; WDT clocks / second count

; Code Section ------------------------------------------------------------ .textstart: mov.w #0x0400,SP ; init stack pointer mov.w #WDTPW|WDTHOLD,&WDTCTL ; stop WDT bis.b #0x01,&P1DIR ; set P1.0 as output

mainloop: xor.b #0x01,&P1OUT ; toggle P1.0 mov.w #8,r14 ; use R14 as outer loop counter

delaylp1: mov.w #0,r15 ; use R15 as delay counter

delaylp2: sub.w #1,r15 ; delay over? jne delaylp2 ; n sub.w #1,r14 ; y, outer loop done? jne delaylp1 ; n jmp mainloop ; y, toggle led

; Interrupt Vectors ------------------------------------------------------- .sect ".reset" ; MSP430 RESET Vector .word start ; start address .end

BYU CS 224Stacks / Interrupts42Example 5.1 Clock Speed .cdecls C,"msp430.h"SMCLK .equ 1200000 ; 1.2 Mhz clockWDT_CTL .equ WDT_MDLY_8 ; WDT SMCLK, 8 ms (@1 MHz)WDT_CPS .equ SMCLK/8000 ; WDT clocks / second count

; Code Section ------------------------------------------------------------ .textstart: mov.w #0x0400,SP ; init stack pointer mov.w #WDTPW|WDTHOLD,&WDTCTL ; stop WDT mov.b #CALBC1_8MHZ,&BCSCTL1 ; set range mov.b #CALDCO_8MHZ,&DCOCTL ; set DCO step + modulation bis.b #0x01,&P1DIR ; set P1.0 as output

mainloop: xor.b #0x01,&P1OUT ; toggle P1.0 mov.w #8,r14 ; use R14 as outer loop counter

delaylp1: mov.w #0,r15 ; use R15 as delay counter

delaylp2: sub.w #1,r15 ; delay over? jne delaylp2 ; n sub.w #1,r14 ; y, outer loop done? jne delaylp1 ; n jmp mainloop ; y, toggle led

; Interrupt Vectors ------------------------------------------------------- .sect ".reset" ; MSP430 RESET Vector .word start ; start address .end

Interrupts

Set DCO constants (for 8 MHz)Nested delay loop to blink LEDOften, the most important factor for prolonging battery life is to turn off some (or all) of the system clocks.A device is said to be sleeping when in low-power mode; waking refers to returning to active mode.BYU CS 224Stacks / Interrupts43MSP430 Clock Modes

Low Power Modes

Only Mostly Dead(7 Years vs 1 Day)Average300x Savings(1 Year vs 1 Day)43BYU CS 224Stacks / Interrupts44ReservedVSCG1SCG0OSCOFFCPUOFFGIENZCActive ModeLPM0LPM3LPM40011001100010111~ 250 A~ 35 A~ 0.8 A~ 0.1 A; enable interrupts / enter low-power mode 0 bis.w #LPM0|GIE,SR ; LPM0 w/interruptsMSP430 Clock Settings (SR)Low Power ModesSMCLK and ACLK ActiveSleep ModesOnly ACLK ActiveNo Clocks!Can be combinedTimers

TimersSystem timing is fundamental for real-time and embedded applications.The main applications of timers are to:generate events of fixed time-periodallow periodic wakeup from sleepcount transitional signal edgesreplace delay loops allowing the CPU to sleep between operations, consuming less powermaintain synchronization clocksdebounce mechanical devicesreal-time clockscontrol simulationsmeasure ratesPulse Width ModulationBYU CS 224Stacks / Interrupts46Timers

MSP430F2274 TimersBYU CS 224Stacks / Interrupts47Timers

Watchdog TimerThe MSP430 watchdog can be configured as a COP (computer operating properly) device or as a timer.The primary function of the watchdog timer (WDT+) module is to perform a controlled system restart after a software problem occurs.After a power-up cycle (PUC), the WDT+ module is automatically configured in watchdog.The user must setup or halt the WDT+ prior to the expiration of the initial reset interval, else an unmasked system reset is generated.If the watchdog function is not needed in an application, the module can be configured as an interval timer and can generate interrupts at selected time intervals.BYU CS 224Stacks / Interrupts48Watchdog

Watchdog Interrupt TimerConfigure the MSP430 watchdog as a timer using WDTCTL register:WDT_MDLY_3232 ms interval (default)WDT_MDLY_88 msWDT_MDLY_0_50.5 msWDT_MDLY_0_0640.064 msWrite a watchdog ISR (callee-safe + reti)Create a watchdog interrupt vector..sect ".int10"; Watchdog Vector.word WDT_ISR; Watchdog ISREnable watchdog to interrupt.bis.b #WDTIE,&IE1; enable WDT interruptbis.w #GIE,SR; enable interruptsBYU CS 224Stacks / Interrupts49WatchdogExample 5.2 Watchdog ISRBYU CS 224Stacks / Interrupts50 .cdecls C,"msp430.h"SMCLK .equ 1200000 ; 1.2 Mhz clockWDT_CPS .equ SMCLK/8000 ; WD clocks / second count

; Data Section ------------------------------------------------------------ .bss WDTSecCnt,2 ; WDT second counter; Code Section ------------------------------------------------------------ .textstart: mov.w #0x400,SP ; initialize stack pointer mov.w #WDT_MDLY_8,&WDTCTL ; set WD timer interval mov.w #WDT_CPS,&WDTSecCnt ; initialize 1 sec WD counter bis.b #0x01,&P1DIR ; P1.0 output bis.b #WDTIE,&IE1 ; enable WDT interrupt bis.w #GIE,SR ; enable interrupts

loop: ;> jmp loop ; loop indefinitely

; Watchdog ISR ------------------------------------------------------------WDT_ISR: sub.w #1,&WDTSecCnt ; decrement counter, 0? jne WDT_02 ; n mov.w #WDT_CPS,&WDTSecCnt ; y, re-initialize counter xor.b #0x01,&P1OUT ; toggle P1.0

WDT_02: reti ; return from interrupt

; Interrupt Vectors ------------------------------------------------------- .sect ".int10" ; Watchdog Vector .word WDT_ISR ; Watchdog ISR .sect ".reset" ; PUC Vector .word start ; RESET ISR .endWatchdog

1. Configure Watchdog as a timer2. Write a Watchdog Interrupt Service Routine3. Create aWDT Interrupt Vector4. Enable Watchdog to interruptBYU CS 224Stacks / Interrupts51Example 5.3 Low Power .cdecls C,"msp430.h"SMCLK .equ 1200000 ; 1.2 Mhz clockWDT_CPS .equ SMCLK/8000 ; WDT clocks / second count

; Data Section ------------------------------------------------------------ .bss WDTSecCnt,2 ; WDT second counter; Code Section ------------------------------------------------------------ .textstart: mov.w #0x0400,SP ; initialize stack pointer mov.w #WDT_MDLY_8,&WDTCTL ; WDT SMCLK, 8 ms (@1 Mhz) mov.w #WDT_CPS,&WDTSecCnt ; initialize 1 sec WD counter bis.b #WDTIE,&IE1 ; enable WDT interrupt bis.b #0x01,&P1DIR ; P1.0 output

loop: bis.w #LPM0|GIE,SR ; sleep/enable interrupts xor.b #0x01,&P1OUT ; toggle P1.0 jmp loop ; loop indefinitely

; Watchdog ISR ------------------------------------------------------------WDT_ISR: sub.w #1,&WDTSecCnt ; decrement counter, 0? jne WDT_02 ; n mov.w #WDT_CPS,&WDTSecCnt ; y, re-initialize counter bic.b #LPM0,0(SP) ; wakeup processor

WDT_02: reti ; return from interrupt

; Interrupt Vectors ------------------------------------------------------- .sect ".int10" ; Watchdog Vector .word WDT_ISR ; Watchdog ISR .sect ".reset" ; PUC Vector .word start ; RESET ISR .endLow-Power Mode

Enable interrupts / Goto Sleep (Low-power Mode 0)2. Blink LED when awakened1. Reset counter every second2. Set Active Mode in saved SR3. Wakeup processor on RETI300A1AactiveActivity ProfilesleepaverageConfigure Watchdog as a timer and enable device to interruptTimers A & B

Asynchronous 16-bit timer/counterFour input clocks, including externally-sourcedSelectable count modeExtensive interrupt capability3 capture/compare registers (CCR)Output not only interrupts, but also output signals (PWM)Timer_A/BBYU CS 224Stacks / Interrupts53

TimersClock Source16-bit CounterCompare RegisterInterrupt(Raises its hand)Divide by 1,2,4,8Compare Output(Assigned to a pin)Up, Continuous, Up/DownTxCTL Control RegisterBYU CS 224Stacks / Interrupts54BitDescription9-8TxSSELxTimer_x clock source:00 TxCLK 01 ACLK 10 SMCLK 11 INCLK 7-6IDxClock signal divider:00 / 1 01 / 2 10 / 4 11 / 85-4MCxClock timer operating mode:00 Stop mode 01 Up mode 10 Continuous mode 11 Up/down mode2TxCLRTimer_x clear when TxCLR = 11TxIETimer_x interrupt enable when TxIE = 10TxIFGTimer_x interrupt pending when TxIFG = 11514131211109876543210(Used only by Timer_B)TxSSELxIDxMCx-TxCLRTxIETxIFGTimersTimer ModesBYU CS 224Stacks / Interrupts55Timers

UpUp to value specified by CCR0, rolls over to 0000, back up to CCR0 value, etc.

Up/DownUp to value in CCR0, count down to 0000,back up to CCR0value in CCR0, etc.

ContinuousUp to FFFF, rollsover to 0000,back to FFFF, etc.Timer RegistersBYU CS 224Stacks / Interrupts568-bit Special Function Registers0x000F0x00008-bit Peripherals Modules0x00FF0x001016-bit Peripherals Modules0x01FF0x0100Stack0x03FF

0x0200Program Code0xFFBF

0xC000Interrupt Vector Table0xFFFF0xFFC0DescriptionTimersTimer_B

(Not available in F2013)Capture/compare registerCapture/compare registerCapture/compare registerTimer_B registerCapture/compare controlCapture/compare controlCapture/compare controlTimer_B controlTimer_B interrupt vectorTBCCR2TBCCR1TBCCR0TBRTBCCTL2TBCCTL1TBCCTL0TBCTLTBIV0x01960x01940x01920x01900x01860x01840x01820x01800x011ETimer_ACapture/compare registerCapture/compare registerCapture/compare registerTimer_A registerCapture/compare controlCapture/compare controlCapture/compare controlTimer_A controlTimer_A interrupt vectorTACCR2TACCR1TACCR0TARTACCTL2TACCTL1TACCTL0TACTLTAIV0x01760x01740x01720x01700x01660x01640x01620x01600x012EWatchdog Timer+WD ControlWDTCTL0x0120Example 5.4 Timer_ABYU CS 224Stacks / Interrupts57 .cdecls C,"msp430.h" ; MSP430TA_CTL .equ TASSEL_2|ID_3|MC_1|TAIE ; 000000 10 11 01 000 1 = SMCLK,/8,UP,IETA_FREQ .equ 0xffff ; clocksSTACK .equ 0x0400 ; top of stack

; Code Section ------------------------------------------------------------ .text ; beginning of executable codestart: mov.w #STACK,SP ; init stack pointer mov.w #WDTPW|WDTHOLD,&WDTCTL ; stop WDT bis.b #0x01,&P1DIR ; set P1.0 as output

clr.w &TAR ; reset timerA mov.w #TA_CTL,&TACTL ; set timerA control reg mov.w #TA_FREQ,&TACCR0 ; set interval (frequency) bis.w #LPM0|GIE,SR ; enter LPM0 w/interrupts

error: jmp $ ; SHOULD NEVER GET HERE!!!!!!!!!!!!

; Timer A ISR -------------------------------------------------------------TA_isr: bic.w #TAIFG,&TACTL ; acknowledge interrupt xor.b #0x01,&P1OUT ; toggle P1.0 reti

; Interrupt Vectors ------------------------------------------------------- .sect ".int08" ; timer A section .word TA_isr ; timer A isr .sect ".reset" ; MSP430 RESET Vector .word start ; start address .endBlinky ExampleTASSEL_2 = SMCLKID_3 = /8MC_1 = UP ModeEnable InterruptPut its hand downTimer A ISRPut the processor to sleep!

NEVER EXECUTE!!!

Quiz 5.6How could I speed up the blink?

What happens if the Timer_A ISR doesnt acknowledge the interrupt?BYU CS 224Stacks / Interrupts58 .cdecls C,"msp430.h" ; MSP430TA_CTL .equ TASSEL_2|ID_3|MC_1|TAIETA_FREQ .equ 0xffff ; clocksSTACK .equ 0x0400 ; top of stack

; Code Section ------------------------------------- .textstart: mov.w #STACK,SP ; init stack pointer mov.w #WDTPW|WDTHOLD,&WDTCTL bis.b #0x01,&P1DIR ; set P1.0 as output

clr.w &TAR ; reset timerA mov.w #TA_CTL,&TACTL ; configure timerA mov.w #TA_FREQ,&TACCR0 ; set interval bis.w #LPM0|GIE,SR ; LPM0 w/interrupts

error: jmp $ ; NEVER GET HERE

; Timer A ISR -------------------------------------TA_isr: bic.w #TAIFG,&TACTL ; acknowledge xor.b #0x01,&P1OUT ; toggle P1.0 reti

; Interrupt Vectors ------------------------------- .sect ".int08" ; timer A section .word TA_isr ; timer A isr .sect ".reset" ; MSP430 RESET Vector .word start ; start address .endPulse Width Modulation

Examples of PWM MachinesBYU CS 224Stacks / Interrupts60Pulse Width Modulation

Pulse Width Modulation (PWM)PWM is a technique of digitally generating analog signals.BYU CS 224Stacks / Interrupts61Pulse Width Modulation

The average value of voltage (and current) is generated by switching the supply on and off at a fast pace.Longer ON periods compared OFF periods results in higher power.The PWM signal is still digital because, at any given instant of time, the full DC supply is either fully on or fully off. Given a sufficient bandwidth, any analog value can be encoded with PWM.Longer OFF periods compared ON periods results in lower power.

PWM Frequency/Duty CycleBYU CS 224Stacks / Interrupts62Pulse Width ModulationDeviceFrequencyDuty CycleSpeakerPitchVolumeLEDFlickerBrightnessMotorSpeedSpeedHeaterSteadinessHeat

Example 5.5 Watchdog PWMBYU CS 224Stacks / Interrupts63 .cdecls C,"msp430.h" ; include c headerWDT_CPS .equ 1200000/500 ; WD clocks / second countSTACK .equ 0x0400 ; stack

.bss WDTSecCnt,2 ; WDT second counter .bss buzzON,1 ; buzzer on flag; Code Section ------------------------------------------------------------ .text ; program sectionstart: mov.w #STACK,SP ; initialize stack pointer mov.w #WDT_MDLY_0_5,&WDTCTL ; set WD timer interval to 0.5 ms mov.w #WDT_CPS,&WDTSecCnt ; initialize 1 sec WD counter mov.b #WDTIE,&IE1 ; enable WDT interrupt bis.b #0x07,&P1DIR ; P1.0 (LED) P1.1-2 (speaker) mov.b #0x04,&P1OUT ; set P1.1 & P1.2 to toggle clr.b buzzON ; turn off buzzer bis.w #LPM0|GIE,SR ; enable interrupts / sleep jmp $ ; (should never get here!)

; Watchdog ISR ------------------------------------------------------------WDT_ISR: tst.b buzzON ; buzzer on? jeq WDT_02 ; n xor.b #0x06,&P1OUT ; y, use 50% PWM

WDT_02: sub.w #1,&WDTSecCnt ; decrement counter, 0? jne WDT_04 ; n mov.w #WDT_CPS,&WDTSecCnt ; y, re-initialize counter xor.b #0x01,&P1OUT ; toggle led xor.b #0xff,buzzON ; toggle buzzer on/off

WDT_04: reti ; return from WDT

.sect ".int10" .word WDT_ISR ; Watchdog ISR .sect ".reset" .word start ; RESET ISR .endPWM speaker (toggle P1.1/P1.2) when buzzON is non-zero(50% duty cycle)

Toggle buzzON every secondPulse Width ModulationP4.5Timer_B Output ModesBYU CS 224Stacks / Interrupts640xFFFFTBCCR0TBCCR20x0000Mode 3:Set/ResetEQU0TBIFGEQU0TBIFGEQU0TBIFGEQU0TBIFGEQU2EQU2EQU2Duty CycleFrequency

Pulse Width ModulationTBCCTL2 Control RegisterBYU CS 224Stacks / Interrupts65BitDescription15-8Capture Configuration (Set to 0) 7-5OUTMODxOutput mode:000 bit OUT001 Set010 Toggle/Reset011 Set / Reset 100 Toggle101 Reset110 Toggle / Set111 Reset / Set4CCIECapture/compare interrupt enable when CCIE = 1.3CCICapture/compare input2OUTOutput state1COVCapture overflow when COV = 10CCIFGCapture/compare interrupt flag CCIFG = 1 when interrupt pending1514131211109876543210Capture ConfigurationOUTMODxCCIECCIOUTCOVCCIFGOUTMOD3 controls TB2 (P4.5):sets TB2 when TBCCR2 == TBR andresets TB2 when TBCCR0 == 0Pulse Width ModulationTimer_B PWM ExampleUse PWM w/Timer B for transducer tones:BYU CS 224Stacks / Interrupts66; reset TimerB clr.w &TBR

; SMCLK, /1, up mode (no interrupts) mov.w #TBSSEL_2|ID_0|MC_1,&TBCTL

; TB2 output mode = set/reset bis.b #0x20,&P4SEL ; P4.5 TimerB (TB2) mov.w #OUTMOD_3,&TBCCTL2 ; set/reset

; load "DO" tone (frequency) mov.w #DO,&TBCCR0

; load volume (50% duty cycle) mov.w #DO/2,&TBCCR2Pulse Width ModulationExample 5.6 Timer_B PWM BYU CS 224Stacks / Interrupts67 .cdecls C,"msp430.h"SMCLK .set 1200000 ; 1200000 clocks / secondTIME_A3 .set 1000000/440/2/2 ; A = 440 HzTB_CTL .set TBSSEL_2|ID_0|MC_1 ; SMCLK, /1, UP (No interrupts)TB_FREQ .set SMCLK/TIME_A3 ; clocks / 440 HzSTACK .set 0x0600 ; stack

; Code Section ------------------------------------------------------------ .textRESET: mov.w #STACK,SP ; initialize SP mov.w #WDTPW|WDTHOLD,&WDTCTL ; stop WDT bis.b #0x20,&P4DIR ; P4.5 transducer output bis.b #0x20,&P4SEL ; P4.5 timerB output clr.w &TBR ; reset timerB mov.w #TB_CTL,&TBCTL ; set timerB control reg mov.w #OUTMOD_3,&TBCCTL2 ; TB2 output mode - set/reset mov.w #TB_FREQ,&TBCCR0 ; set interval (frequency) mov.w #TB_FREQ/2,&TBCCR2 ; set volume (duty cycle) bis.w #LPM0,SR ; enter LPM0 jmp $ ; will never get here!

; NO ISR!!!! --------------------------------------------------------------

; Interrupt Vectors ------------------------------------------------------- .sect ".reset" ; reset vector section .word RESET ; reset vector ISR .endSet P4.5 as output from TB2UP mode, TB2 set/reset50% Duty Cycle

Pulse Width ModulationQuiz 5.7What properties of PWM are exhibited by an LED?

What properties of PWM are exhibited by a speaker?

What properties of PWM are exhibited by a motor?

What properties of PWM are exhibited by a servo?

BYU CS 224Stacks / Interrupts68Switch Debounce

BYU CS 224Stacks / Interrupts70Switch DebounceSwitch DebounceSwitch "debounced" after signal remains low for specified time2.43.30.50.0Logic "Low"Logic "High"Switch PressedSwitch ReleasedUndefinedExample 5.7 SW Switch DebounceBYU CS 224Stacks / Interrupts71 .cdecls C,"msp430.h" .textRESET: mov.w #0x0600,SP ; init stack pointer mov.w #WDT_MDLY_8,&WDTCTL ; stop WDT bis.b #0x0f,&P4DIR ; set P4.0-3 as outputs bic.b #0x0f,&P1DIR ; set P1.0-3 as inputs bis.b #0x0f,&P1OUT ; use pull-ups bis.b #0x0f,&P1REN

mainloop: call #get_switch ; wait for switch xor.b r12,&P4OUT ; output (toggle) P4.0-3 jmp mainloop

; Switch debounce subroutine -----------------------------------------DB_DELAY .equ 1200*10/13 ; 10 ms debounce delay countget_switch: push r15 ; callee save

deb02: mov.b &P1IN,r12 ; read switches xor.b #0x0f,r12 ; SW1-4 and.b #0x0f,r12 ; any switch low? jne deb02 ; y, wait until all off

deb04: mov.w #DB_DELAY,r15 ; minimum delay

deb06: mov.b &P1IN,r12 ; read switches xor.b #0x0f,r12 ; SW1-4 and.b #0x0f,r12 ; all switches high? jeq deb04 ; n, restart delay dec.w r15 ; y, long enough delay? jne deb06 ; n, keep going pop r15 ; y, switches debounced ret

.sect ".reset" ; PUC Vector .word RESET ; RESET ISR .endReset timing counter if all of the switches read 0Switch DebounceReturn if R15 counts down to 0Wait until all switches offBYU CS 124Interrupts72 .cdecls C,"msp430.h" .bss WDT_dcnt,2 ; WDT second counter .bss switches,2 ; switches .textRESET: mov.w #0x0600,SP ; init stack pointer mov.w #WDT_MDLY_8,&WDTCTL ; WDT SMCLK, 8 ms (@1 Mhz) bis.b #WDTIE,&IE1 ; enable WDT interrupt clr.w WDT_dcnt ; clear debounce counter bis.b #0x0f,&P4DIR ; set P4.0-3 as outputs bic.b #0x0f,&P1DIR ; set P1.0-3 as inputs bis.b #0x0f,&P1OUT ; pull-up bis.b #0x0f,&P1REN ; enable pull-ups bis.b #0x0f,&P1IES ; high to low transition bis.b #0x0f,&P1IE ; enable interrupts

mainloop: bis.w #LPM0|GIE,SR ; enable interrupts/goto sleep xor.b switches,&P4OUT ; output (toggle) P4.0-3 jmp mainloop

; Port 1 ISR --------------------------------------------------------------DEBOUNCE .equ 5 ; debounce count (~40 ms)P1_ISR: bic.b #0x0f,&P1IFG ; put its hand down mov.w #DEBOUNCE,WDT_dcnt ; reset debounce counter reti

; Watchdog ISR ------------------------------------------------------------WDT_ISR: cmp.w #0,WDT_dcnt ; debouncing? jeq WDT_02 ; n sub.w #1,WDT_dcnt ; y, decrement counter, 0? jne WDT_02 ; n mov.b &P1IN,switches ; y, read switches xor.b #0x0f,switches ; positive assertion and.b #0x0f,switches ; mask low 4 bits (switches) bic.b #LPM0,0(SP) ; wake up

WDT_02: reti ; return from interrupt

.sect ".int02" .word P1_ISR ; Port 1 ISR .sect ".int10 .word WDT_ISR ; Watchdog ISR .sect ".reset" .word RESET ; RESET ISR .endExample 5.8 HW Switch DebounceWatchdog ISRDecrement WDT_cnt (if non-zero), read switch and wakeup main routine.Switch DebouncePort 1 interrupt vectorPort 1 ISRReset debounce counterConfigure Switches:High to LowPull-upsEnable interruptsSummaryBy coding efficiently you can run multiple peripherals at high speeds on the MSP430Polling is to be avoided use interrupts to deal with each peripheral only when attention is requiredAllocate processes to peripherals based on existing (fixed) interrupt priorities - certain peripherals can tolerate substantial latencyUse GIE when its shown to be most efficient and the application can tolerate it otherwise, control individual IE bits to minimize system interrupt latency.An interrupt-based approach eases the handling of asynchronous eventsBYU CS 224Stacks / Interrupts73Interrupt Service RoutineBYU CS 224Stacks / Interrupts74