Unformatted Document Excerpt
Coursehero >>
Utah >>
BYU >>
CS 124
Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
6
Check 186
Chapter first to see whether an intrinsic function is available to do the job without leaving C. Many of these are declared in the header file intrinsics.h to perform functions that are not possible in standard C. For example, the _ _swap_bytes() intrinsic function calls the swpb instruction. Another possibility, when only a line or two of assembly language is needed, is to use inline assembly. This looks like a function asm() whose argument is the line(s) of assembly code, such as asm("mov.b &P1IN,&dest"). There are some dangers with this approach, set out in the compiler reference guide. The third method is to write a complete subroutine in assembly language and call it from C. Obviously it is essential to get the calling convention correct. This is defined in the reference guides but there is an easier way. Write as much of the subroutine as possible in C and compile it. Copy the resulting assembly code and use it as the shell of your subroutine. This can be done from the disassembly window in the Kickstart version of EW430; you have to pay to get a real output file with the assembly code. Do not change the level of optimization afterward because this may change the code that calls the subroutine. An example will be given in "Conversion from Binary to BCD in Assembly Language" on page 272.
6.6
Interrupts
Interrupts were introduced in the section "Exceptions: Interrupts and Resets" on page 36. They are like functions but with the critical distinction that they are requested by hardware at unpredictable times rather than called by software in an orderly manner. (Well, a periodic interrupt should be highly predictable in real time, but this is not apparent to the CPU.) Interrupts are commonly used for a range of applications: Urgent tasks that must be executed promptly at higher priority than the main code. However, it is even faster to execute a task directly by hardware if this is possible. Infrequent tasks, such as handling slow input from humans. This saves the overhead of regular polling.
Waking the CPU from sleep. This is particularly important in the MSP430, which typically spends much of its time in a low-power mode and can be awakened only by an interrupt. Calls to an operating system. These are often processed through a trap or software interrupt instruction but the MSP430 does not have one. A substitute is for
www.newnespress.com
Functions, Interrupts, and Low-Power Modes software to set an unused interrupt flag for one of the peripherals, such as port P1 or P2.
187
The code to handle an interrupt is called an interrupt handler or interrupt service routine (ISR). It looks superficially like a function but there are a few crucial modifications. The feature that interrupts arise at unpredictable times means that an ISR must carry out its action and clean up thoroughly so that the main code can be resumed without error--it should not be able to tell that an interrupt occurred. Interrupts can be requested by most peripheral modules and some in the core of the MCU, such as the clock generator. Each interrupt has a flag, which is raised (set) when the condition for the interrupt occurs. For example, Timer_A sets the TAIFG flag in the TACTL register when the counter TAR returns to 0. We polled this flag to pace the loop in the section "Automatic Control: Flashing a Light by Polling Timer_A" on page 105. Each flag has a corresponding enable bit, TAIE in this case. Setting this bit allows the module to request interrupts. Most interrupts are maskable, which means that they are effective only if the general interrupt enable (GIE) bit is set in the status register (SR). They are ignored if GIE is clear. Therefore both the enable bit in the module and GIE must be set for interrupts to be generated. The (non)maskable interrupts cannot be suppressed by clearing GIE. The reason for the parentheses around (non) is that these interrupts also require bits to be set in special function or peripheral registers to enable them. Thus even the (non)maskable interrupts can be disabled and indeed all are disabled by default. I drop the parentheses around non for clarity. The MSP430 uses vectored interrupts, which means that the address of each ISR--its vector--is stored in a vector table at a defined address in memory. In most cases each vector is associated with a unique interrupt but some sources share a vector. The ISR itself must locate the source of interrupts that share vectors. For example, TAIFG shares a vector with the capture/compare interrupts for all channels of Timer_A other than 0. Channel 0 has its own interrupt flag TACCR0 CCIFG and separate vector. Each interrupt vector has a distinct priority, which is used to select which vector is taken if more than one interrupt is active when the vector is fetched. The priorities are fixed in hardware and cannot be changed by the user. They are given simply by the address of the vector: A higher address means a higher priority. The reset vector has address 0xFFFE, which gives it the top priority, followed by 0xFFFC for the single nonmaskable interrupt vector. The vectors for the maskable interrupts depend on the peripherals in a particular device and are listed in a table of Interrupt Vector Addresses in the data sheet. Taking the
www.newnespress.com
188
Chapter 6
F2013 as an example, the vector for TACCR0 CCIFG has an address 0xFFF2 and therefore has a higher priority than the shared vector for TAIFG and TACCR1 CCIFG, whose address is 0xFFF0. Five other vectors are used in this device to give a total of 9, although space for up to 32 is reserved (16 in older devices). Interrupts must be handled in such a way that the code that was interrupted can be resumed without error. This means in particular that the values in the CPU registers must be restored. The hardware can take two extreme approaches to this: Copies of all the registers are saved on the stack automatically as part of the process for entering an interrupt. This is done in the Freescale HCS08, for example, which is a CISC and has only a few registers. The disadvantage is the time required, which means that the response to an interrupt is delayed. An alternative is to switch to a second set of registers, which is done in the Z80 and descendants.
The opposite approach is for the hardware to save only the absolute minimum, which is the return address in the PC as in a subroutine. This is much faster but it is up to the user to save and restore values of the critical registers, notably the status register. The Microchip PIC16 takes this approach, consistent with its minimalist philosophy. The MSP430 is close to the second extreme but stacks both the return address and the status register. The SR gets this privileged treatment because it controls the low-power modes and the MCU must return to full power while it processes the interrupt. This is explored further in the section "Low-Power Modes of Operation" on page 198. The other registers must be saved on the stack and restored if their contents are modified in the ISR. Instructions have been added to the MSP430X to push and pop multiple registers, which makes this process faster.
6.7
What Happens when an Interrupt Is Requested?
A lengthy chain of operations lies between the cause of a maskable interrupt and the start of its ISR. It starts when a flag bit is set in the module when the condition for an interrupt occurs. For example, TAIFG is set when the counter TAR returns to 0. This is passed to the logic that controls interrupts if the corresponding enable bit is also set, TAIE in this case. The request for an interrupt is finally passed to the CPU if the GIE bit is set. Hardware then performs the following steps to launch the ISR: 1. Any currently executing instruction is completed if the CPU was active when the interrupt was requested. MCLK is started if the CPU was off.
www.newnespress.com
Functions, Interrupts, and Low-Power Modes 2. The PC, which points to the next instruction, is pushed onto the stack. 3. The SR is pushed onto the stack.
189
4. The interrupt with the highest priority is selected if multiple interrupts are waiting for service. 5. The interrupt request flag is cleared automatically for vectors that have a single source. Flags remain set for servicing by software if the vector has multiple sources, which applies to the example of TAIFG. 6. The SR is cleared, which has two effects. First, further maskable interrupts are disabled because the GIE bit is cleared; nonmaskable interrupts remain active. Second, it terminates any low-power mode, as explained in the section "Low-Power Modes of Operation" on page 198. (The SCG0 bit is not cleared in the MSP430x4xx family, which means that the frequency-locked loop is not automatically reactivated; see "Frequency-Locked Loop, FLL+" on page 172.) 7. The interrupt vector is loaded into the PC and the CPU starts to execute the interrupt service routine at that address. This sequence takes six clock cycles in the MSP430 before the ISR commences. The stack at this point is shown in Figure 6.5. The position of SR on the stack is important if the low-power mode of operation needs to be changed. The delay between an interrupt being requested and the start of the ISR is called the latency. If the CPU is already running it is given by the time to execute the current instruction, which might only just have started when the interrupt was requested, plus the six cycles needed to execute the launch sequence. This should be calculated for the slowest instruction to get the worst case. Format I instructions take up to 6 clock cycles so the overall latency is 12 cycles. The time required to start MCLK replaces the duration of the
(a) Before interrupt
SP
(b) After entering interrupt return address status register
SP
Figure 6.5: Stack before and after entering an interrupt service routine. The return address (PC) and status register (SR) have been saved, with SR on the top of the stack.
www.newnespress.com
190
Chapter 6
current instruction if the device was in a low-power mode. The delay varies on each occasion because the interrupt may be requested at different points during an instruction, whose length may also differ. Thus there is no fixed interval between the request of an interrupt and the start of its ISR. Use the hardware of a timer to read an input or change an output at a precise time. Figure 6.6 shows an example of this and there are many more in Chapter 8. An interrupt service routine must always finish with the special return from interrupt instruction reti, which has the following actions: 1. The SR pops from the stack. All previous settings of GIE and the mode control bits are now in effect, regardless of the settings used during the interrupt service routine. In particular, this reenables maskable interrupts and restores the previous low-power mode of operation if there was one. 2. The PC pops from the stack and execution resumes at the point where it was interrupted. Alternatively, the CPU stops and the device reverts to its low-power mode before the interrupt. This takes a further five cycles in the MSP430. The stack is restored to its state before the interrupt was accepted.
6.8
Interrupt Service Routines
The framework of an interrupt service routine is more straightforward in assembly language so I'll describe this before explaining how they are implemented in C.
6.8.1
Interrupt Service Routines in Assembly Language
An ISR looks almost identical to a subroutine but with two distinctions: The address of the subroutine, for which we can use its name (a label on its first line), must be stored in the appropriate interrupt vector. The routine must end with reti rather than ret so that the correct sequence of actions takes place when it returns. The other change in the program is that interrupts must be enabled or nothing happens. I use the same old example, to toggle the LEDs on the Olimex 1121STK. The program is shown in Listing 6.4, adapted from the C program in Listing 4.17. The timer runs in Up mode with a period set by the value in TACCR0.
www.newnespress.com
Functions, Interrupts, and Low-Power Modes
191
We have a choice of two interrupts. The programs in Chapter 4 polled the TAIFG flag, which is set when the counter TAR returns to 0. This flag can also generate an interrupt but it has the minor inconvenience that its vector is shared with other sources and is therefore slightly trickier to handle. It is more straightforward to use the TACCR0 CCIFG flag, which is set when TAR counts up to the value in TACCR0, because it has its own interrupt vector. This interrupt is enabled by setting the CCIE bit in the control register for channel 0, TACCTL0. It is safer to do this before starting the timer. Timer_A now requests interrupts but these are not accepted unless the GIE bit in the status register is also set. The main routine has nothing more to do after this. It can sit back and let the interrupts do all the work. Here I left the CPU in an infinite, empty loop but it would be better to put it into a low-power mode, which is done in the section "Low-Power Modes of Operation" on page 198. Listing 6.4: Program timrint1.s43 in assembly language to toggle LEDs using interrupts generated by timer_A in up mode.
; timrint1 . s43 - toggles LEDs with period of about 1 s ; TACCR0 interrupts from timer A with period of about 0.5 s ; Timer clock is SMCLK divided by 8 , up mode , period 50000 ; Olimex 1121 STK , LED1 ,2 active low on P2 .3 ,4 ; J H Davies , 2006 -09 -20; IAR Kickstart version 3.41 A ; ----------------------------------------------------------------------# include < msp430x11x1 .h > ; Header file for this device ; ----------------------------------------------------------------------; Pins for LED on port 2 LED1 EQU BIT3 LED2 EQU BIT4 ; ----------------------------------------------------------------------RSEG CSTACK ; Create stack ( in RAM ) ; ----------------------------------------------------------------------RSEG CODE ; Program goes in code memory Reset : ; Execution starts here mov .w # SFE ( CSTACK ) , SP ; Initialize stack pointer main : ; Equivalent to start of main () in C mov .w # WDTPW | WDTHOLD ,& WDTCTL ; Stop watchdog timer mov .b # LED2 ,& P2OUT ; Preload LED1 on , LED2 off bis .b # LED1 | LED2 ,& P2DIR ; Set pins with LED1 ,2 to output mov .w #49999 ,& TACCR0 ; Period for up mode mov .w # CCIE ,& TACCTL0 ; Enable interrupts on Compare 0 mov .w # MC_1 | ID_3 | TASSEL_2 | TACLR ,& TACTL ; Set up Timer A ; Up mode , divide clock by 8 , clock from SMCLK , clear TAR bis .w # GIE , SR ; Enable interrupts ( just TACCR0 ) jmp $ ; Loop forever ; interrupts do all ; ----------------------------------------------------------------------; Interrupt service routine for TACCR0 , called when TAR = TACCR0 ; No need to acknowledge interrupt explicitly - done a u t o m a t i c a l l y TA0_ISR : ; ISR for TACCR0 CCIFG xor .b # LED1 | LED2 ,& P2OUT ; Toggle LEDs
www.newnespress.com
192
Chapter 6
reti ; That 's all : return from interrupt ; ----------------------------------------------------------------------COMMON INTVEC ; Segment for vectors ( in Flash ) ORG TIMERA0_VECTOR DW TA0_ISR ; ISR for TA0 interrupt ORG RESET_VECTOR DW Reset ; Address to start execution END
The interrupt service routine TA0_ISR looks much like a subroutine and starts with the usual label to give it a name. There is no significance to the name--I chose something obvious but you can call it anything that you want. In many processors the first task is to "acknowledge" the interrupt, usually by clearing the associated flag in the peripheral register. If this is not done, the interrupt is reasserted continually and the program repeats the ISR until an interrupt of higher priority is called. This step is not needed most for interrupts in the MSP430 because the flag is cleared automatically while the ISR is launched. Although this is fast and convenient it can sometimes be a nuisance when debugging because there is no pause between interrupts. The only task in this ISR is to toggle the LEDs, which is done in the usual way, before the routine returns with reti. No registers are used so there is no need to save and restore them. The final part of the program is to associate the name of the ISR, TA0_ISR here, with the vector for the TACCR0 CCIFG interrupt. This means that the address of the routine--its vector--is stored in the corresponding entry of the vector table. The absolute addresses are listed in the data sheet and can be used with an ORG directive to locate the vector in absolute assembly:
ORG 0 xFFF2 DW TA0_ISR ; Address of TACCR0 CCIFG vector in table ; Vector : address of TACCR0 CCIFG ISR
The absolute addresses are not defined in the header files. As usual I prefer to use relocatable assembly. The vectors are stored in the segment INTVEC (what a surprise) and the addresses within this segment are defined in the header file, as used in the preceding listing. The reset vector can be defined either in the same way as the interrupt vectors, which I do here, or in a segment of its own, as done in Listing 4.4. The effect is the same. I introduce the INTVEC segment with COMMON rather than RSEG so that more than one file can store interrupt vectors in the segment. This is unnecessary in a project with only a single file but there is no harm in doing things properly.
www.newnespress.com
Functions, Interrupts, and Low-Power Modes Example 6.7
193
Try this in the simulator. Interrupts introduce several new aspects. The first is that EW430 simulates only the core of the MSP430 and not the peripherals. A full chip simulator would also model the timer and gives interrupts automatically after the correct number of clock cycles. Here we must mimic the interrupts by hand. Open the window Simulator > Forced Interrupts, which brings up a list of possible interrupts for the selected device, and select TIMERA0_VECTOR. Step through the code in the usual way. It is a good idea to open the CPU Registers window and expand SR. You see the GIE bit become set immediately before the loop. This makes interrupts possible but nothing happens if the program is stepped further; it remains stuck in the loop and only the cycle counter changes. Now click the Trigger button in the Forced Interrupt window and step again. The simulator jumps to the first instruction in the ISR, which toggles the LEDs. Control returns to the infinite loop after the reti instruction and remains there until the next interrupt is triggered. You can also see the stack grow by two words on entry to the ISR and empty again after the reti. Example 6.8 Try the emulator next. There is no need for forced interrupts and the window is not displayed. Step through the code to the infinite loop again. Note that the GIE button in the Debug toolbar becomes "pressed" when the bit is set. The counter TAR in Timer_A increases every time a single step is taken. I found that it rose by about 49 (decimal) each step, which is due to the number of clock cycles needed to read the changed registers through JTAG to the debugger. The debugger halts MCLK and SMCLK on this device (F1121A) between steps. It is clearly going to take a long time to reach the value of 49,999 in TACCR0 that triggers the interrupt. Use Edit > Toggle Breakpoint, to put a breakpoint on the first instruction in TA0_ISR (), and let the program Go. It will stop very shortly on the breakpoint. The GIE button is now "released" to show that the bit is clear, disabling further maskable interrupts. Choosing Go again toggles the LEDs and the program runs for a further 0.5 s until the next interrupt. The GIE button can be used to clear the bit and disable interrupts, which stops further toggling of the LEDs.
www.newnespress.com
194
Chapter 6
6.8.2
Interrupt Service Routines in C
An interrupt service routine cannot be written entirely in standard C because there is no way to identify it as an ISR rather than an ordinary function. In fact it would appear that the function was dead code, meaning that it could never be called, so the compiler would optimize it away. Some extensions are therefore needed and these inevitably differ between compilers. The usage for EW430 is given in Listing 6.5. Two additions are needed to the ISR. First is the #pragma line, which associates the function with a particular interrupt vector. The second is the _ _interrupt keyword at the beginning of the line that names the function. This ensures that the address of the function is stored in the vector and that the function ends with reti rather than ret. Again there is no significance to the name of the function; it is the name of the vector that matters. An intrinsic function is needed to set the GIE bit and turn on interrupts. This is called _ _enable_interrupt(), singular rather than plural. It is declared in intrinsics.h, which must be included. Listing 6.5: Program timintC1.c to toggle LEDs using interrupts generated by channel 0 of Timer_A in up mode.
// timintC1 . c - toggles LEDs with period of about 1.0 s // Toggle LEDs in ISR using interrupts from timer A CCR0 // in Up mode with period of about 0.5 s // Timer clock is SMCLK divided by 8 , up mode , period 50000 // Olimex 1121 STK , LED1 ,2 active low on P2 .3 ,4 // J H Davies , 2006 -10 -11; IAR Kickstart version 3.41 A // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # include < io430x11x1 .h > // Specific device # include < intrinsics .h > // Intrinsic functions // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Pins for LEDs # define LED1 BIT3 # define LED2 BIT4 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void main ( void ) { WDTCTL = WDTPW | WDTHOLD ; // Stop watchdog timer P2OUT = ~ LED1 ; // Preload LED1 on , LED2 off P2DIR = LED1 | LED2 ; // Set pins with LED1 ,2 to output TACCR0 = 49999; // Upper limit of count for TAR TACCTL0 = CCIE ; // Enable interrupts on Compare 0 TACTL = MC_1 | ID_3 | TASSEL_2 | TACLR ; // Set up and start Timer A // " Up to CCR0 " mode , divide clock by 8 , clock from SMCLK , clear timer __enable _interrupt (); // Enable interrupts ( intrinsic ) for (;;) { // Loop forever doing nothing } // Interrupts do the work } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Interrupt service routine for Timer A channel 0
www.newnespress.com
Functions, Interrupts, and Low-Power Modes
195
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # pragma vector = T I M E R A 0 _ V E C T O R _ _interrupt void TA0_ISR ( void ) { P2OUT ^= LED1 | LED2 ; // Toggle LEDs }
Example 6.9 This program can be simulated and emulated in much the same way as the version in assembly language. About the only difference is that the stack has an extra, permanent entry, which is because the main() function is called from a "shell" in case the user's program should exit. Additional work is needed to handle interrupts that have multiple sources. For example, the counter TAR of Timer_A and all its channels except 0 share a single interrupt vector. Similarly, all 8 bits of each input/output port share a common vector. The ISR must first determine the source of its interrupt in these cases. Timer_A has a register TAIV to identify the origin rapidly. This must be read to acknowledge the interrupt, even if only one source has been enabled and there is no other need to read TAIV. Alternatively, the flag associated with the specific source can be cleared directly, as explained in "Interrupts from Timer_A" on page 296. There seem to be "gotchas" like this associated with interrupts on all processors. The status register is cleared during the sequence of actions at the entry to an ISR. This includes GIE = 0, which disables further maskable interrupts. This prevents nested interrupts, where one ISR is interrupted by another. The problem with nested interrupts is that the stack grows by at least two words for each ISR. This can cause the stack to run out of memory--overflow--if there is a continuous stream of interrupts, probably because something is out of control. Nested interrupts are for experts only. On the other hand, clearing GIE does not affect nonmaskable interrupts, so it is possible for one of these to arise during an ISR.
6.8.3
Nonmaskable Interrupts
There are a few small differences in the handling of nonmaskable interrupts compared with the maskable type. All the sources share a single vector, which has the highest address and therefore the highest priority except for the reset vector. Three modules can request a nonmaskable interrupt:
www.newnespress.com
196
Chapter 6 Oscillator fault, OFIFG. This was described in the section "Oscillator Faults" on page 171. Remember that this flag is set by a power-up clear as a warning that the oscillator may not yet have stabilized. This interrupt should therefore not be enabled until the oscillator is running correctly.
Access violation to flash memory, ACCVIFG. An active edge on the external RST/NMI pin if it has been configured for interrupts rather than reset. The function of the RST/NMI pin is configured in the control register for the watchdog timer module, WDTCTL. By default it is an active low, reset input RST. This can be switched to an NMI interrupt input with the WDTNMI bit. It then generates an interrupt if it receives either a positive or negative edge, depending on the value of the WDTNMIES edge select bit. The interrupt is enabled by the NMIIE bit in the special function register IE1 and the corresponding flag is NMIFG in IFG1. An external pull-up or pull-down may be required. The RST/NMI pin is also used for the two-wire Spy-Bi-Wire JTAG interface in the MSP430F2xx, which may limit its usefulness for external interrupts. (External maskable interrupts can be generated by ports P1 and P2.) The shared vector means that the ISR must first identify the source of the interrupt. This is explained clearly in the family user's guides. One of the steps in starting a maskable ISR is to clear the status register, which disables other maskable interrupts. This has no effect on nonmaskable interrupts so the hardware clears all the enable flags in the modules to prevent further interrupts during the ISR. The desired nonmaskable interrupts must therefore be reenabled by the ISR as its last instruction. One of TI's standard code examples shows how to handle NMI.
6.9
Issues Associated with Interrupts
Interrupts are fun to program, if occasionally frustrating to debug. They can also give rise to problems that are very hard to locate. It is a good idea to follow a few simple rules to avoid some of these difficulties.
Keep Interrupt Service Routines Short
Other interrupts, which may be urgent, are disabled during an ISR unless you choose to allow nested interrupts. If lengthy processing is necessary, do the minimum in the ISR and send a message to the main function, perhaps by setting a flag. The main function can then
www.newnespress.com
Functions, Interrupts, and Low-Power Modes
197
do the time-consuming work between interrupts. Alternatively, use the ISR simply to wake the processor and hand control immediately to the main function. This is explained later in "Returning from a Low-Power Mode to the Main Function" on page 203.
Configure Interrupts Carefully
Make sure that unwanted interrupts are disabled. This should be the case by default and a problem is likely to arise only if an interrupt has been used at one time but not required later. Make sure that the module is fully configured before interrupts are enabled. Sometimes the flag can become set before interrupts are wanted so it should be cleared before the enable bit is set. Do not set the GIE bit until you are ready to handle interrupts.
Define All Interrupt Vectors
It is good practice for safety to fill all the defined entries of the vector table, even for interrupts that are not used. A simple approach for assembly language is to define a single ISR for unused interrupts that traps the processor in an infinite loop. The address of this routine can then be stored in all the unused interrupt vectors. Use the debugger to trace back if one of these interrupts arises. It is a little clumsier in C because a separate function must be provided for each interrupt, but the body can again be an empty, infinite loop. An infinite loop is helpful for debugging but not for a production version of a program. It would probably be better to force the device to reset itself, perhaps by writing an illegal value to the watchdog control register WDTCTL. Nagy [4] has further advice.
The Shared Data Problem
This is one of the classic issues with interrupts and multitasking systems and is explained thoroughly by Simon [25]. It arises when variables are used both in the main function and in ISRs. Here is a trivial example from a real-time clock. Suppose that a variable MinsOfDay is updated once per minute in an ISR. The main function drives separate displays for the minutes and hours, with a function for each:
DisplayMinutes ( MinsOfDay ); DisplayHours ( MinsOfDay );
(I assume that MinsOfDay has been declared volatile or there is even worse trouble.) The shared data problem arises if the ISR updates MinsOfDay between the two
www.newnespress.com
198
Chapter 6
function calls. Suppose that the time was 01:59 when DisplayMinutes was called but has been updated to 02:00 by the time that DisplayHours is called. The displayed time will be 02:59. Oops! Example 6.10 What would happen if the functions were called in the reverse sequence? What if they were called around midnight, assuming a 24-hour clock? This is typical of a shared data problem. It does not occur often, even in theory. In practice it is seen only at inconvenient times, usually during a demonstration (such as when your project is being assessed in a university). There are various solutions. In this trivial case, we could take a local copy of MinsOfDay and use the copy as the argument to both functions. More generally it may be necessary to disable interrupts during critical sections that are susceptible to this problem.
Checklist--Have You ...
Enabled interrupts both in their module and generally (GIE bit)? Provided an interrupt service routine for all enabled interrupts? Included code to acknowledge interrupts that share a vector (such as TAIFG or the input ports) even if only one source is active? Ended interrupt service routines in assembly language with reti and initialized the stack?
6.10
Low-Power Modes of Operation
The MSP430 was designed from the outset for low power and this is reflected in a range of low-power modes of operation. There are five in all but two are rarely employed in current devices (they were useful with earlier versions of the DCO). The most important modes are summarized here with typical currents I for the F2013 taken from its data sheet. These are for VCC = 3 V, the DCO running at 1 MHz, and LFXT1 at 32 KHz from a crystal. The current in active mode rises with frequency to about 4 mA at 16 MHz, although this requires a higher supply voltage. Active mode: CPU, all clocks, and enabled modules are active, I 300 A. The MSP430 starts up in this mode, which must be used when the CPU is required. An
www.newnespress.com
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more.
Course Hero has millions of course specific materials providing students with the best way to expand
their education.
Below is a small sample set of documents:
BYU - CS - 124
CHAPTER 6Functions, Interrupts, and Low-Power ModesA well-structured program should be divided into separate modules-functions in C or subroutines in assembly language. There is nothing special about this in embedded systems. If you wish to write subrou
BYU - CS - 124
330Chapter 8by one interval of two cycles. (The frequency would be 877.7 Hz if this pattern were the exact output.) The two durations are clear on the oscilloscope trace. The signal sounds terrible and is quite unusable, even if its average frequency is
BYU - CS - 124
CHAPTER 8TimersMost modern microcontrollers provide a range of timers and the MSP430 is no exception. All devices contain two types of timer and some have five. Each type of timer module works in essentially the same way in all devices. Timer_A is ident
BYU - CS - 124
Mixed-Signal Systems: Analog Input and Output393Schmitt trigger and interrupts on standard digital inputs can be used for the measurement instead of a comparator.9.2Analog-to-Digital Conversion: General IssuesAlthough Comparator_A produces digital va
BYU - CS - 124
Mixed-Signal Systems: Analog Input and Output Example 9.12475Modify Listing 9.12 so that the intensity of the LED responds to the ambient light in the opposite way: The LED gets brighter as the surroundings become darker. It is a lot easier to test this
BYU - CS - 124
534Chapter 10transmission. The results were strange because of the problems that I mentioned in the section "Digital Input and Output: Parallel Ports" on page 208. Enabling the pull resistor removes the full drive from the pin, so the sharp edges in Fig
BYU - CS - 124
Chapter 10Watchdog Timer+The watchdog timer+ (WDT+) is a 16-bit timer that can be used as a watchdog or as an interval timer. This chapter describes the WDT+ The WDT+ is implemented in all MSP430x2xx devices.TopicPage10.1 Watchdog Timer+ Introduction
BYU - CS - 124
Negative Numbers and Binary SubtractionWe have seen how simple logic gates can perform the process of binary addition. It is only logical to assume that a similar circuit could perform binary subtraction. If we look at the possibilites involved in subtra
BYU - CS - 124
Chapter 3RISC 16 Bit CPUThis chapter describes the MSP430 CPU, addressing modes, and instruction set.Topic3.1 3.2 3.3 3.4PageCPU Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2 CPU Registers
BYU - CS - 124
The 1-to-2 Line Decoder/DemultiplexerThe opposite of the multiplexer circuit, logically enough, is the demultiplexer. This circuit takes a single data input and one or more address inputs, and selects which of multiple outputs will receive the input sign
BYU - CS - 124
The Two-Input MultiplexerOne circuit I've received a number of requests for is the multiplexer circuit. This is a digital circuit with multiple signal inputs, one of which is selected by separate address inputs to be sent to the single output. It's not e
BYU - CS - 124
Prefix b c l n p w dw f fn fp t g u Type BYTE charUsage Signed 8-bit value Signed 8-bit value (usually an ASCII character) long Signed 32-bit value int Signed 16-bit value U16 : pointer Generic prefix for a pointer to the next type U16 : WORD Unsigned
BYU - CS - 124
Chapter 5 MSP430 ISA The Instruction SetTopics to Cover.n n n n n n n nMSP430 ISA Instruction Formats Double Operand Instructions Single Operand Instructions Jump Instructions Addressing Modes Instruction Disassembly Emulated InstructionsBYU CS/ECEnC
BYU - CS - 124
Clock accuracy in ppmCrystal Clock accuracy is defined in terms of ppm or parts per million and it gives a convenient way of comparing accuracies of different crystal specifications. . The following headings give practical calculations showing the typica
BYU - CS - 124
CS/ECEn 124, W2012 Homework #1 Abstraction (Ch 2)Questions:NameSectionScore/ 41Answers:1. (3 points) Can a higher level programming language instruct a computer to compute more than a lower level programming language? Explain.2. (3 points) Name th
BYU - CS - 124
CS/ECEn 124, W2012 Homework #2 Digital Logic (Ch 3)Questions:NameSectionScore/ 38Answers:1. (4 points) How many select lines and how many output lines do the following multiplexers have? a. b. c. d. 32-input multiplexer 16-input multiplexer 5-input
BYU - CS - 124
CS/ECEn 124, W2012 Homework #3 Digital Logic (Ch 3)Questions:NameSectionScore/46Answers:1. (10 points) Identify the type of logic (combinational or sequential) for each of the following: a. ALU b. D-latch c. Decoder d. Driver e. Flip-Flop f. Invert
BYU - CS - 124
CS/ECEn 124, W2012 Homework #4 Von Neumann (Ch 4) MSP430 ISA (Ch 5)Questions:NameSectionScore/ 47Answers:1. (11 points) For each statement below, indicate if a CISC or RISC architecture is best described: a. b. c. d. e. f. g. h. i. j. k. Cheaper pr
BYU - CS - 124
CS/ECEn 124, W2012 Homework #7 Stacks (Ch 8) Interrupts (9)Questions:NameSectionScore/ 36Answers:1. (3 points) Define subroutine cohesion. What properties of cohesion should be found in your subroutines?2. (3 points) Define subroutine coupling. Wh
BYU - CS - 124
An introduction to the TI MSP430 low-power microcontrollers OverviewThe MSP430 is a very clean 16-bit byte-addressed processor with a 64K unified address space, and memorymapped peripherals. The current family includes a variety of on-chip peripherals, a
BYU - CS - 124
AN-1023APPLICATION NOTEOne Technology Way P.O. Box 9106 Norwood, MA 02062-9106, U.S.A. Tel: 781.329.4700 Fax: 781.461.3113 www.analog.comFall Detection Application by Using 3-Axis Accelerometer ADXL345by Ning JiaINTRODUCTIONADXL345 MEMS ACCELEROMETE
BYU - CS - 124
AN-1025APPLICATION NOTEOne Technology Way P.O. Box 9106 Norwood, MA 02062-9106, U.S.A. Tel: 781.329.4700 Fax: 781.461.3113 www.analog.comUtilization of the First In, First Out (FIFO) Buffer in Analog Devices, Inc.Digital Accelerometersby Christopher
BYU - CS - 124
3-Axis, 2 g/4 g/8 g/16 g Digital Accelerometer ADXL345FEATURESUltralow power: as low as 40 A in measurement mode and 0.1 A in standby mode at VS = 2.5 V (typical) Power consumption scales automatically with bandwidth User-selectable resolution Fixed 10-
BYU - CS - 124
AccelerometersFantasy & RealityBy Harvey Weinberg [harvey.weinberg@analog.com]As applications engineers supporting ADIs compact, low-cost, gravity-sensitive iMEMsaccelerometers, we get to hear lots of creative ideas about how to employ accelerometers i
BYU - CS - 124
Adding Binary NumbersA key requirement of digital computers is the ability to use logical functions toperform arithmetic operations. The basis of this is addition; if we can add twobinary numbers, we can just as easily subtract them, or get a little fa
BYU - CS - 124
ASCII Chart012345670NULDLESP0@P`p1SOHDC1!1AQaq2STXDC2"2BRbr3ETXDC3#3CScsOr here's another chart:4EOTDC4$4DTdt5ENQNAK%5EUeu6ACKSYN&6FVfv7BELETB'7GWgw8BSCAN(8HXhx9HT
BYU - CS - 124
Basic Logical Functions andGatesWhile each logical element or condition must always have a logic value ofeither "0" or "1", we also need to have ways to combine different logical signalsor conditions to provide a logical result.For example, consider
BYU - CS - 124
Boolean AlgebraOne of the primary requirements when dealing with digital circuits is to findways to make them as simple as possible. This constantly requires that complexlogical expressions be reduced to simpler expressions that nevertheless produceth
BYU - CS - 124
PrefixbclnpwdwffnfptguTypeBYTEcharUsageSigned 8-bit valueSigned 8-bit value (usually anASCII character)longSigned 32-bit valueintSigned 16-bit valueU16 : pointerGeneric prefix for a pointer to thenext typeU16 : WORDUnsigned 16
BYU - CS - 124
Node:Top, Next:Preface, Previous:(dir), Up:(dir)C Programming Tutorial (K&R version 4)This is a C Programming Tutorial for people who have a little experience with aninterpreted programming language, such as Emacs Lisp or a GNU shell.Edition 4.02Copy
BYU - CS - 124
Formatting with printfThe example program above does not produce a very neat layout on the screen. Theconversion specifiers in the printf string can be extended to give more information.The % and the character type act like brackets around the extra in
BYU - CS - 124
Arrays as ParametersWhat happens if we want to pass an array as a parameter? Does the program copy theentire array into local storage? The answer is no because it would be a waste of timeand memory. Arrays can be passed as parameters, but only as varia
BYU - CS - 124
feof()This function returns a true or false result. It tests whether or not the end of a file hasbeen reached and if it has it returns `true' (which has any value except zero); otherwisethe function returns `false' (which has the value zero). The form
BYU - CS - 124
Listing Cref.c123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354/*//**//* C programming utility : variable referencer*//**//*//* See notes abov
BYU - CS - 124
Clock accuracy in ppmCrystal Clock accuracy is defined in terms of ppm or parts per million and it gives a convenient way ofcomparing accuracies of different crystal specifications..The following headings give practical calculations showing the typica
BYU - CS - 124
/- CRC functions -/u_long crc32_table[256];/* Initialized first time "crc32()" is called. If you prefer, you can* statically initialize it at compile time. [Another exercise.]*/u_long crc32(u_char *buf, int len)cfw_u_char *p;u_long crc;if (!crc32
BYU - CS - 124
INTRODUCTION TO COMPUTING SYSTEMSCS/ECEn 124 Course SyllabusWinter 2012Instructor: Paul RoperOffice: 3370 TMCB, 422-8149Office Hours: MWF 9:00-10:50 AMEmail: proper@cs.byu.eduSection 001Section 002Help SessionsMWF 1:00-1:50 PMMWF 3:00-3:50 PMM
BYU - CS - 124
A Guide to DebouncingAugust 2004Rev 1: April, 2006Rev 2: April, 2007Rev 3: June, 2008Jack G. Gansslejack@ganssle.comThe Ganssle GroupPO Box 38346Baltimore, MD 21231(410) 504-6660fax (647) 439-1454 2004 The Ganssle Group. This work may be used
BYU - CS - 124
Derived Logical Functions andGatesWhile the three basic functions AND, OR, and NOT are sufficient toaccomplish all possible logical functions and operations, some combinations areused so commonly that they have been given names and logic symbols of th
BYU - CS - 124
Deriving the XOR FunctionOn the previous page we stated that the Exclusive-OR, or XOR function can bedescribed verbally as, "Either A or B, but not both." In the realm of digital logicthere are several ways of stating this in a more detailed and precis
BYU - CS - 124
Digital LogicDigital or binary logic has fascinated many people over the years. The very idea that atwo-valued number system can possibly be the basis for the most powerful andsophisticated computers seems astounding, to say the least. Nevertheless, it
BYU - CS - 124
The replacement parts/accessories for the eZ430X Development Board are available at the BYU ECEn StockRoom (416 CB) as follows:DescriptionLCD DisplayServoTransponderJumperThermistorDevelopment BoardSound ModulePartLCD - NHD-C160100DiZ-FSW-FBWT
BYU - CS - 124
MSP-FET430 Flash Emulation Tool (FET) (for Use With Code Composer Essentials for MSP430 Version 3.1)User's GuideLiterature Number: SLAU157I May 2005 Revised February 20092SLAU157I May 2005 Revised February 2009 Submit Documentation FeedbackContentsP
BYU - CS - 124
FM24CL6464Kb Serial 3V F-RAM MemoryFeatures64K bit Ferroelectric Nonvolatile RAM Organized as 8,192 x 8 bits Unlimited Read/Write Cycles 45 year Data Retention NoDelay Writes Advanced High-Reliability Ferroelectric ProcessFast Two-wire Serial Int
BYU - CS - 124
The Function Pointer TutorialsIntroduction to C and C+ Function Pointers, Callbacks and Functorswritten by Lars HaendelJanuary 2005, Bochum, Germanyhttp:/www.newty.deemail: Have a look at the web page pleaseversion 2.07Copyright (c) 2000-2005 by La
BYU - CS - 124
REV C (February 22, 2010)Secondary (L)HDEFIIIOPin SignalSW_2ADXL345 INT1/2SW_4LCD BacklightPrimary (R)P2.0 (ACLK/A0)P2.1 (SMCLK/A1)P2.2 (TA0/A2)P2.3 (TA1/A3)P2.4 (TA2/A4)P2.6P2.7XIN - GDO0 (O)XOUT - GDO2 (O)IIIOOOOP3.0 (UCB
BYU - CS - 124
Hex File FormatsThis appendix describes the Intel hex object format and the TI-txt file format.The Intel hex object format supports 16-bit addresses and consists of a 9-character (4-field) prefix that defines the start ofrecord, byte count, load addres
BYU - CS - 124
How to Access FRAM.The FM24CL64 is a 64-kilobit nonvolatile memory employing an advancedferroelectric process. A ferroelectric random access memory or F-RAM is nonvolatileand performs reads and writes like a RAM. It provides reliable data retention for
BYU - CS - 124
How to Change Clock Speed.The MSP430 addresses the conflicting demands for high performance, lowpower, and a precise frequency by using three internal clocks, which can bederived from up to four sources. These are the internal clocks, which are thesam
BYU - CS - 124
How To Change The Processor Clock.The MSP430 was designed to power-up quickly from low-power mode withouthaving to wait a long time for the clock to settle. The Digitally ControlledOscillator (DCO) of the MSP430F2274 is an accurate and stable clock tha
BYU - CS - 124
How to Condition an Analog Signal.An analog-to-digital converter (abbreviated ADC, A/D or A to D) is a device whichconverts continuous analog signals to discrete digital numbers. Due to the finiteresolution and the unavoidable imperfections in all type
BYU - CS - 124
How To Control a Servo.What is a Servo?A servo is a small device that has a rotating output shaft. This shaft can bepositioned to specific angular positions by sending the servo a coded signal.As long as the coded signal exists on the input line, the
BYU - CS - 124
How To Debounce A Switch.A switch is a mechanical device that "opens" and "closes" a circuit. Theswitches on the eZ430X board are normally open, letting the inputs be pulledhigh (a logic one) by the internal MSP430 port pull-up resistors. A closed ord
BYU - CS - 124
How to Determine the Length of a String.A C string can be created from a binary data type by using the sprintf() function. Byincluding the standard C I/O library ("#include <stdio.h>" and defining a characterarray of sufficient size for the string, the
BYU - CS - 124
How to Draw a Continuous Line.A continuous line is drawn if neither the delta x nor delta y is greater than 1 pixel. Inthe following example, the x value always increments by 1 while the y value onlydecrements by 1 when needed to conform to the "ideal"
BYU - CS - 124
How to Draw Images and Text on theLCD.The New Haven NHD-C160100DiZ-FSW-FBW LCM (Liquid Crystal DisplayGraphic Module) is a 160 column x 100 row, 16-level dot, reflective, LiquidCrystal Display with a side white LED backlight. Display data and commands
BYU - CS - 124
How to Draw Various Shapes.Draw a circle on the LCD by calling:void lcd_circle(int x0, int y0, int r0, int pen);wherex0, y0 = coordinates of the center of the circler0 = radius of circlepen = pen value (0 = erase, 1 = single line)Example:lcd_circl
BYU - CS - 124
How To Generate A Random Number.Use the following routines found in random.asm to initialize, set, and getrandom numbers:FunctioninitRand16rand16setRandSeedgetRandSeedParametersIN: r12 = random seedOUT: r12 = random number (0-32767)IN: r12 = ra
BYU - CS - 124
How To Implement An Event Driven ProgrammingModel.In your introductory programming courses and our labs thus far, you mostlyused the basic program structures of sequential, conditional, and iterativecode associated with a procedural program. If you lo
BYU - CS - 124
How To Interface With eZ430XLibraries.eZ430X Librariesadc.h, adc.co int ADC_init(void);o int ADC_read(int channel);adxl345.h, adxl345.co int ADXL345_init(void);o unsigned char ADXL345_read(unsigned char regaddr, unsignedchar *buf, int count);o v
BYU - CS - 124
How To Link Programs.Part of systemic decomposition usually involves dividing a program intoseparate files. Smaller files are easier to maintain and support ObjectOriented Programming (OOP) by "hiding" or encapsulating data. The problemof coming up wi