Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
learn:courses:unit-2:start [2017/03/16 16:34] – [7. Real-time Operating Systems] Marthalearn:courses:unit-2:start [2022/10/04 11:38] (current) – external edit 127.0.0.1
Line 1: Line 1:
 ====== Unit 2: Elements of Real-time Systems ====== ====== Unit 2: Elements of Real-time Systems ======
 +[[{}/learn/courses/microprocessor-io-unit-1/start|Back to Unit 1]]
 ==Unit 2 Labs== ==Unit 2 Labs==
-  * [[https://reference.digilentinc.com/learn/courses/unit-2-lab2a/start|Lab 2a]] +  * [[/learn/courses/unit-2-lab2a/start|Lab 2a]] 
-  * [[https://reference.digilentinc.com/learn/courses/unit-2-lab2b/start|Lab 2b]]+  * [[/learn/courses/unit-2-lab2b/start|Lab 2b]]
  
  
Line 19: Line 20:
  
 ===== 2. Objectives: ===== ===== 2. Objectives: =====
-  * Implement task management based on [[https://en.wikipedia.org/wiki/Polling_(computer_science)|polling]] PIC32 timers. +  - Implement task management based on [[https://en.wikipedia.org/wiki/Polling_(computer_science)|polling]] PIC32 timers. 
-  * Implement task management based on PIC32 timer [[https://en.wikipedia.org/wiki/Interrupt_latency|interrupts]]. +  - Implement task management based on PIC32 timer [[https://en.wikipedia.org/wiki/Interrupt_latency|interrupts]]. 
-  * Understand the principles of a software implemented [[https://en.wikipedia.org/wiki/Finite-state_machine|finite state machine]] (FSM). +  - Understand the principles of a software implemented [[https://en.wikipedia.org/wiki/Finite-state_machine|finite state machine]] (FSM). 
-  * Use time management and FSM code to control the speed of rotation of the [[https://en.wikipedia.org/wiki/Stepper_motor|stepper motor rotor]]. +  - Use time management and FSM code to control the speed of rotation of the [[https://en.wikipedia.org/wiki/Stepper_motor|stepper motor rotor]]. 
-  * Implement a multitasking real-time application using [[https://en.wikipedia.org/wiki/Foreground-background|foreground-background]] scheduling.+  - Implement a multitasking real-time application using [[https://en.wikipedia.org/wiki/Foreground-background|foreground-background]] scheduling.
  
  
 ===== 3. Basic Knowledge: ===== ===== 3. Basic Knowledge: =====
-  * [[https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Seq/diff.html|Understanding of combinational logic and sequential logic]]. +  - [[https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Seq/diff.html|Understanding of combinational logic and sequential logic]]. 
-  * [[http://www.tutorialspoint.com/cprogramming/switch_statement_in_c.htm|Using the SWITCH-CASE construct in C]]. +  - [[http://www.tutorialspoint.com/cprogramming/switch_statement_in_c.htm|Using the SWITCH-CASE construct in C]]. 
-  * [[http://www.learn-c.com/schemat.htm|How to interpret a schematic diagram and electric circuits]]. +  - [[http://www.learn-c.com/schemat.htm|How to interpret a schematic diagram and electric circuits]]. 
-  * [[http://homepage.cs.uiowa.edu/~jones/step/an907a.pdf|Fundamentals of stepper motors]].+  - [[http://homepage.cs.uiowa.edu/~jones/step/an907a.pdf|Fundamentals of stepper motors]].
  
  
 ===== 4. Unit Equipment List ===== ===== 4. Unit Equipment List =====
 ==== 4.1. Hardware ==== ==== 4.1. Hardware ====
-  * [[http://store.digilentinc.com/basys-mx3-pic32mx-trainer-board-recommended-for-embedded-systems-courses/|Basys MX3 trainer board]] +  - [[https://digilent.com/shop/basys-mx3-pic32mx-trainer-board-for-embedded-systems-courses/|Basys MX3 trainer board]] 
-  * [[http://store.digilentinc.com/usb-a-to-micro-b-cable/|Micro USB cable]] +  - [[https://digilent.com/shop/usb-a-to-micro-b-cable/|Micro USB cable]] 
-  * Workstation computer running Windows 10 or higher, MAC OS, or Linux +  - Workstation computer running Windows 10 or higher, MAC OS, or Linux 
-  * [[http://store.digilentinc.com/stepper-motor/|4-wire stepper motor]] +  - [[https://digilent.com/shop/stepper-motor/|4-wire stepper motor]] 
-  * [[http://store.digilentinc.com/5v-4000ma-switching-power-supply/|5V, 4A DC power supply]]+  - [[https://digilent.com/shop/5v-4a-switching-power-supply/|5V, 4A DC power supply]]
  
 ==== 4.2. Software ==== ==== 4.2. Software ====
 The following programs must be installed on your development workstation: The following programs must be installed on your development workstation:
  
-  * [[http://www.microchip.com/mplab/mplab-x-ide|Microchip MPLAB X® v3.35 or higher]] +  - [[http://www.microchip.com/mplab/mplab-x-ide|Microchip MPLAB X® v3.35 or higher]] 
-  * [[http://www.microchip.com/xcdemo/xcpluspromo.aspx|XC32 Cross Compiler]] +  - [[http://www.microchip.com/xcdemo/xcpluspromo.aspx|XC32 Cross Compiler]] 
-  * [[http://www.microchip.com/SWLibraryWeb/product.aspx?product=PIC32%20Peripheral%20Library|PLIB Peripheral Library]]+  - [[http://www.microchip.com/SWLibraryWeb/product.aspx?product=PIC32%20Peripheral%20Library|PLIB Peripheral Library]]
  
 ===== 5. Project Takeaways ===== ===== 5. Project Takeaways =====
-  * How to set the period of a PIC32 Timer. +  - How to set the period of a PIC32 Timer. 
-  * How to write a software state machine. +  - How to write a software state machine. 
-  * How to allocate tasks to either foreground or background scheduling. +  - How to allocate tasks to either foreground or background scheduling. 
-  * Understanding of stepper motor operations and applications.+  - Understanding of stepper motor operations and applications.
    
  
Line 62: Line 63:
 The correct operation of a dynamic real-time scheduling scheme is predicated on two requirements. The first is that the worst case (longest) execution time of the timer interrupt service routine (ISR) must be less than the interrupt interval. The second is that the time remaining in the interrupt period after execution of the ISR must be sufficient so that it appears to the user that the processor is acknowledging his or her inputs in a timely manner. The correct operation of a dynamic real-time scheduling scheme is predicated on two requirements. The first is that the worst case (longest) execution time of the timer interrupt service routine (ISR) must be less than the interrupt interval. The second is that the time remaining in the interrupt period after execution of the ISR must be sufficient so that it appears to the user that the processor is acknowledging his or her inputs in a timely manner.
  
-Real-time operation has two basic requirements: correct value at the correct time. A system that cannot always meet both of these requirements is a failed system. Hence, it is not sufficient to just have the correct output values; these outputs have to be generated at the correct time. You have already developed a real-time operating system for [[https://reference.digilentinc.com/learn/courses/microprocessor-io-lab-1b/start|Lab 1b]].+Real-time operation has two basic requirements: correct value at the correct time. A system that cannot always meet both of these requirements is a failed system. Hence, it is not sufficient to just have the correct output values; these outputs have to be generated at the correct time. You have already developed a real-time operating system for [[/learn/courses/microprocessor-io-lab-1b/start|Lab 1b]].
  
 The time required to service the ISR includes the execution time of the user ISR code in addition to the time required to save and restore the system context. Using the MPLAB X Stopwatch debugging feature, we find that it requires 33 machine cycles to save and restore the system context. Using a core frequency of 80 MHz, the context saving and restoring time is 1.03 μs. The time to execute the user written code varies. In the case of Labs 2a and 2b, execution of the ISR code will vary based upon the conditional execution of the LED and stepper motor functions. The time required to service the ISR includes the execution time of the user ISR code in addition to the time required to save and restore the system context. Using the MPLAB X Stopwatch debugging feature, we find that it requires 33 machine cycles to save and restore the system context. Using a core frequency of 80 MHz, the context saving and restoring time is 1.03 μs. The time to execute the user written code varies. In the case of Labs 2a and 2b, execution of the ISR code will vary based upon the conditional execution of the LED and stepper motor functions.
Line 80: Line 81:
 Although there are different approaches to task switching, the two easiest are cooperative and preemptive. When using the cooperative scheduling approach, each task willingly gives up running its computer code to allow another task to run. To be effective, all tasks must work together “nicely” such that all tasks have an opportunity to meet their time deadlines. Each task is responsible for determining when it is time to switch tasks. The various tasks managed using a cooperative multitasking scheme are scheduled in a [[https://en.wikipedia.org/wiki/Round-robin_scheduling|round-robin]] fashion. This is how the multiple tasks needed to implement Lab 1a and Lab 1b are managed – they took turns executing in the main function’s infinite loop. Although there are different approaches to task switching, the two easiest are cooperative and preemptive. When using the cooperative scheduling approach, each task willingly gives up running its computer code to allow another task to run. To be effective, all tasks must work together “nicely” such that all tasks have an opportunity to meet their time deadlines. Each task is responsible for determining when it is time to switch tasks. The various tasks managed using a cooperative multitasking scheme are scheduled in a [[https://en.wikipedia.org/wiki/Round-robin_scheduling|round-robin]] fashion. This is how the multiple tasks needed to implement Lab 1a and Lab 1b are managed – they took turns executing in the main function’s infinite loop.
  
-==== 7.1. Preemption ====+=== 7.1.1. Preemption ===
 “In computing, preemption is the act of temporarily interrupting a task being carried out by a computer system, without requiring its cooperation, and with the intention of resuming the task at a later time. It is normally carried out by a privileged task or part of the system that has the power to interrupt, and later resume, other tasks in the system.” “In computing, preemption is the act of temporarily interrupting a task being carried out by a computer system, without requiring its cooperation, and with the intention of resuming the task at a later time. It is normally carried out by a privileged task or part of the system that has the power to interrupt, and later resume, other tasks in the system.”
  
 In software, a task is a basic unit of programming that has a constrained, defined purpose. For example, reading the state of the input pins to determine if buttons are pressed or not can be considered a task. Multitasking implies that more than one task is running at the same time. Single-core processors appear to be multitasking by time-sharing the processor resources. No time sharing is required in Lab 1a and Lab 1b, where each task in the program ran to its completion before the next task could begin. When multitasking with a single-core processor, some tasks are suspended so that higher priority tasks can be serviced (executed).   In software, a task is a basic unit of programming that has a constrained, defined purpose. For example, reading the state of the input pins to determine if buttons are pressed or not can be considered a task. Multitasking implies that more than one task is running at the same time. Single-core processors appear to be multitasking by time-sharing the processor resources. No time sharing is required in Lab 1a and Lab 1b, where each task in the program ran to its completion before the next task could begin. When multitasking with a single-core processor, some tasks are suspended so that higher priority tasks can be serviced (executed).  
  
-==== 7.2. Task Scheduling ====+ 
 +=== 7.1.2. Task Scheduling ===
 Task scheduling for preemptive multitasking requires the use of one or more interrupts to determine when each task is to be executed. These interrupts can be based on external events, such as a communications message, or internal events, such as a timer clock. Typically, real-time systems use both cooperative and preemptive scheduling to implement what’s called [[https://en.wikipedia.org/wiki/Foreground-background|foreground-background scheduling]]. High priority tasks (time critical or hard real-time tasks) are called the foreground tasks. The tasks that can be executed when no foreground tasks are pending are called background tasks. Background tasks have low priority and can, in theory, wait forever without degrading system performance. Task scheduling for preemptive multitasking requires the use of one or more interrupts to determine when each task is to be executed. These interrupts can be based on external events, such as a communications message, or internal events, such as a timer clock. Typically, real-time systems use both cooperative and preemptive scheduling to implement what’s called [[https://en.wikipedia.org/wiki/Foreground-background|foreground-background scheduling]]. High priority tasks (time critical or hard real-time tasks) are called the foreground tasks. The tasks that can be executed when no foreground tasks are pending are called background tasks. Background tasks have low priority and can, in theory, wait forever without degrading system performance.
  
Line 91: Line 93:
 In Unit 1, the order in which tasks were started and completed was strictly controlled by the order in which code was executed in the program. In this unit, we will investigate the concept of altering program code execution using [[http://www.embedded.com/electronics-blogs/beginner-s-corner/4024543/Introduction-to-Preemptive-Multitasking|preemption]]. Preemption by an interrupt causes the processor to stop the execution of the current code flow and begin execution of a special function called an “interrupt handler” or “interrupt service routine” (ISR). In a preemptive system, tasks are started and completed based on a programmed prioritization. The PIC32MX370 has up to 76 different interrupt sources and 46 interrupt vectors. References 2, 3, and 4 provide background information concerning processor interrupts. In Unit 1, the order in which tasks were started and completed was strictly controlled by the order in which code was executed in the program. In this unit, we will investigate the concept of altering program code execution using [[http://www.embedded.com/electronics-blogs/beginner-s-corner/4024543/Introduction-to-Preemptive-Multitasking|preemption]]. Preemption by an interrupt causes the processor to stop the execution of the current code flow and begin execution of a special function called an “interrupt handler” or “interrupt service routine” (ISR). In a preemptive system, tasks are started and completed based on a programmed prioritization. The PIC32MX370 has up to 76 different interrupt sources and 46 interrupt vectors. References 2, 3, and 4 provide background information concerning processor interrupts.
  
-As illustrated in Fig. 7.1, an __interrupt__ is a signal triggered by an event internal to the processor or an external signal. The computer suspends what would normally be the next instruction of a task in one part of a program and begins executing code to complete an entirely different task. This occurrence of events can be periodic (deterministic) or aperiodic (sporadic). An example of a deterministic event is a timer flag being set at a specified interval. Sporadic interrupts are the result of an unpredictable event, such as a divide by zero error, detection of low processor power, serial data received flag, or even pressing a button by a person. These signals cause the microprocessor to implement a sequence of operations resulting in an orderly way of suspending one task, executing an entirely different task, and subsequently resuming the original task.+As illustrated in Fig. 7.1, an [[http://en.wikipedia.org/wiki/Interrupt|interrupt]] is a signal triggered by an event internal to the processor or an external signal. The computer suspends what would normally be the next instruction of a task in one part of a program and begins executing code to complete an entirely different task. This occurrence of events can be periodic (deterministic) or aperiodic (sporadic). An example of a deterministic event is a timer flag being set at a specified interval. Sporadic interrupts are the result of an unpredictable event, such as a divide by zero error, detection of low processor power, serial data received flag, or even pressing a button by a person. These signals cause the microprocessor to implement a sequence of operations resulting in an orderly way of suspending one task, executing an entirely different task, and subsequently resuming the original task. 
  
 {{ :learn:courses:unit-2:figure-7-1.png?nolink |Figure 7.1. PIC32 interrupt handler block diagram.}} {{ :learn:courses:unit-2:figure-7-1.png?nolink |Figure 7.1. PIC32 interrupt handler block diagram.}}
 //Figure 7.1. PIC32 interrupt handler block diagram.// //Figure 7.1. PIC32 interrupt handler block diagram.//
  
-The three main types of interrupts are software, internal hardware, and external hardware. Software and internal hardware interrupts that are initiated by some event inside the microprocessor are also commonly referred to as exceptions or traps. Software interrupts are explicitly internally triggered by instructions within the current program, commonly referred to as __trap instructions__. Internally generated hardware interrupts triggered by timers, analog converters, serial communications, errors detected during software execution, such as illegal math scheduling instructions or operational codes (__opcodes__), are all known as exceptions. Finally, external hardware interrupts are interrupts initiated by hardware other than the CPU. Both the software code and the processor architecture determine how interrupts are prioritized and processed. +The three main types of interrupts are software, internal hardware, and external hardware. Software and internal hardware interrupts that are initiated by some event inside the microprocessor are also commonly referred to as exceptions or traps. Software interrupts are explicitly internally triggered by instructions within the current program, commonly referred to as [[http://en.wikipedia.org/wiki/Trap_(computing)|trap instructions]]. Internally generated hardware interrupts triggered by timers, analog converters, serial communications, errors detected during software execution, such as illegal math scheduling instructions or operational codes ([[https://en.wikipedia.org/wiki/Opcode|opcodes]]), are all known as exceptions. Finally, external hardware interrupts are interrupts initiated by hardware other than the CPU. Both the software code and the processor architecture determine how interrupts are prioritized and processed. 
  
-=== 7.3.1. Context ===+=== 7.1.3.1. Context ===
 The [[http://en.wikipedia.org/wiki/Context_(computing)|context]] of a microprocessor defines the state or operating conditions internal to the processor. In order to properly resume executing the task that was interrupted, the ISR is responsible for saving and restoring the context of the processor to before it was interrupted. At the very least, the context consists of the processor register values, the CPU flag registers, and the program address of the next instruction to be executed when the ISR has completed.   The [[http://en.wikipedia.org/wiki/Context_(computing)|context]] of a microprocessor defines the state or operating conditions internal to the processor. In order to properly resume executing the task that was interrupted, the ISR is responsible for saving and restoring the context of the processor to before it was interrupted. At the very least, the context consists of the processor register values, the CPU flag registers, and the program address of the next instruction to be executed when the ISR has completed.  
  
Line 105: Line 108:
 [[https://en.wikipedia.org/wiki/Interrupt_latency|Interrupt latency]] is defined as the time between the instant when an event generates the interrupt signal and the time when the first useful instruction in the ISR is executed. This latency is made up of two major components: the time required to save the processor context and the amount of time that an interrupt is disabled or deferred by higher priority interrupts as necessary.  [[https://en.wikipedia.org/wiki/Interrupt_latency|Interrupt latency]] is defined as the time between the instant when an event generates the interrupt signal and the time when the first useful instruction in the ISR is executed. This latency is made up of two major components: the time required to save the processor context and the amount of time that an interrupt is disabled or deferred by higher priority interrupts as necessary. 
  
-=== 7.3.2. Managing Interrupts === + 
-Preemptive programs usually consist of two types of tasks: [[http://books.google.com/books?id=1qDuaC17yxAC&pg=PA83&lpg=PA83&dq=real+time+foreground+background+tasks&source=bl&ots=u0tHFEwzSX&sig=QurPxPbXzB2HwGV6GxBSRmjz4hw&hl=en&sa=X&ei=ebuvUfnbM-H8igL1y4D4BA&ved=0CDMQ6AEwAg#v=onepage&q=real%20time%20foreground%20bac|foreground and background]]. Foreground tasks are those preemptive tasks that the processor executes as soon as the need arises in response to an interrupt. Interrupts are assigned priority levels that dictate the order in which interrupts will be serviced. In the case of multiple foreground tasks both needing service at the same time, the higher the interrupt priority, the sooner the microprocessor executes the code to service that interrupt. Code executed immediately following a power-up reset runs at priority level zero and has no preemptive capability. This initial background task is responsible for setting up the resources for tasks that will eventually run as foreground tasks.  +=== 7.1.3.2. Managing Interrupts === 
 +Preemptive programs usually consist of two types of tasks: foreground and background. Foreground tasks are those preemptive tasks that the processor executes as soon as the need arises in response to an interrupt. Interrupts are assigned priority levels that dictate the order in which interrupts will be serviced. In the case of multiple foreground tasks both needing service at the same time, the higher the interrupt priority, the sooner the microprocessor executes the code to service that interrupt. Code executed immediately following a power-up reset runs at priority level zero and has no preemptive capability. This initial background task is responsible for setting up the resources for tasks that will eventually run as foreground tasks.  
  
 Foreground tasks have preemptive capability by having higher priorities than background tasks. The foreground task ensures adequate response times, while the background task manages deferred processing of the foreground data. Background tasks are those that the processor executes whenever it has available time and is waiting for something more important to do. Background tasks generally run at the interrupt priority level zero within a //while(1) { … }// program loop, where event detection by polling flags and pins is common. Interrupt only systems, which are those that only have foreground processes, respond quickly to both periodic and sporadic events but ignore potential work that can be allocated to a background process. The use of interrupts falls under the broad category of [[https://en.wikipedia.org/wiki/Scheduling_(computing)|real-time task scheduling]], and a thorough investigation of this topic is beyond the scope of this project. Foreground tasks have preemptive capability by having higher priorities than background tasks. The foreground task ensures adequate response times, while the background task manages deferred processing of the foreground data. Background tasks are those that the processor executes whenever it has available time and is waiting for something more important to do. Background tasks generally run at the interrupt priority level zero within a //while(1) { … }// program loop, where event detection by polling flags and pins is common. Interrupt only systems, which are those that only have foreground processes, respond quickly to both periodic and sporadic events but ignore potential work that can be allocated to a background process. The use of interrupts falls under the broad category of [[https://en.wikipedia.org/wiki/Scheduling_(computing)|real-time task scheduling]], and a thorough investigation of this topic is beyond the scope of this project.
  
-There are two types of preemptive operating schemes: nested and non-nested. Nested interrupt schemes allow higher priority level interrupts to preempt code that is servicing a lower priority interrupt. A non-nested interrupt scheme completes the execution of the code currently servicing an interrupt before it begins to service the code for any interrupt awaiting service, regardless of interrupt priorities.   +There are two types of preemptive operating schemes: nested and non-nested. Nested interrupt schemes allow higher priority level interrupts to preempt code that is servicing a lower priority interrupt. A non-nested interrupt scheme completes the execution of the code currently servicing an interrupt before it begins to service the code for any interrupt awaiting service, regardless of interrupt priorities.  
 + 
 Non-nested preemptive schemes are usually easier to manage, but they can result in priority inversion, where a low priority task blocks a higher priority task from running. This scheme is easier to manage because the developer only has to focus on one ISR, and the operation that determines which interrupts to service resembles the process of polling, i.e., constantly checking to see if a specific event has occurred, which we did in Lab 1b. For non-nested interrupt schemes, we must individually check the flags set by the interrupting event to determine which event to service. All interrupts are assigned to priority level 1 and are vectored (sent) to the same ISR where the particular interrupt flag must be cleared. For multiple simultaneous interrupts, tasks are serviced in the order that the interrupt flags are polled. A non-nested priority scheme results whenever interrupts are enabled using the instruction //INTEnableSystemSingleVectoredINT();// provided in the peripheral library.  Non-nested preemptive schemes are usually easier to manage, but they can result in priority inversion, where a low priority task blocks a higher priority task from running. This scheme is easier to manage because the developer only has to focus on one ISR, and the operation that determines which interrupts to service resembles the process of polling, i.e., constantly checking to see if a specific event has occurred, which we did in Lab 1b. For non-nested interrupt schemes, we must individually check the flags set by the interrupting event to determine which event to service. All interrupts are assigned to priority level 1 and are vectored (sent) to the same ISR where the particular interrupt flag must be cleared. For multiple simultaneous interrupts, tasks are serviced in the order that the interrupt flags are polled. A non-nested priority scheme results whenever interrupts are enabled using the instruction //INTEnableSystemSingleVectoredINT();// provided in the peripheral library. 
  
Line 122: Line 126:
 See the [[http://ww1.microchip.com/downloads/en/DeviceDoc/61108G.pdf|PIC32MX Family Reference Manual Section 8]] for additional details of interrupt operations on the PIC32MX family of processors. See the [[http://ww1.microchip.com/downloads/en/DeviceDoc/61108G.pdf|PIC32MX Family Reference Manual Section 8]] for additional details of interrupt operations on the PIC32MX family of processors.
  
-=== 7.3.3. General Interrupt Code Requirements ===+=== 7.1.3.3. General Interrupt Code Requirements ===
 There are four essential code elements required for a program to process interrupts using C: the declaration of the functions that will be used to service the interrupts, the code to initialize the resources that generate the interrupt, the ISR code that will be executed in response to an interrupt, and the instructions that enable interrupts in a global sense. There must be a specific ISR to handle each enabled interrupt, including the instruction to clear the specific interrupt flag. Failing to clear the interrupt will cause the processor to repeatedly execute the ISR, thus preventing the processor from executing any other application code.   There are four essential code elements required for a program to process interrupts using C: the declaration of the functions that will be used to service the interrupts, the code to initialize the resources that generate the interrupt, the ISR code that will be executed in response to an interrupt, and the instructions that enable interrupts in a global sense. There must be a specific ISR to handle each enabled interrupt, including the instruction to clear the specific interrupt flag. Failing to clear the interrupt will cause the processor to repeatedly execute the ISR, thus preventing the processor from executing any other application code.  
  
Line 128: Line 132:
  
 In this project, two different interrupts will be generated: Timer 1 interrupt and an I/O pin change notice interrupt. The programming requirements for each of these two interrupts are discussed below. The two statements in Listing 7.1 apply to all interrupts and should be executed only once after all resources that are to generate an interrupt have been initialized. In this instance, the program is using multi-vectored interrupts. Selected segments of the code used in an application can be protected from preemption by any and all interrupts by bracketing the code segment with the instructions //INTEnalbeInterrupts();// and //INTDisableInterrupts();//.  In this project, two different interrupts will be generated: Timer 1 interrupt and an I/O pin change notice interrupt. The programming requirements for each of these two interrupts are discussed below. The two statements in Listing 7.1 apply to all interrupts and should be executed only once after all resources that are to generate an interrupt have been initialized. In this instance, the program is using multi-vectored interrupts. Selected segments of the code used in an application can be protected from preemption by any and all interrupts by bracketing the code segment with the instructions //INTEnalbeInterrupts();// and //INTDisableInterrupts();//. 
 +
  
 ---- ----
Line 141: Line 146:
 ---- ----
  
-==== 7.4. Microprocessor Timers and Counters ==== +==== 7.2. Microprocessor Timers and Counters ==== 
-Counter/timer hardware is a crucial component of most embedded systems. In some cases, a timer is needed to measure elapsed time; in others, we want to count or time some external events. We will use timers to pace the execution of specific segments of code either by __polling__ timer flags or using __interrupts__ generated by the timer. The PIC32MX370 has a __core timer__, a __watchdog timer__, and five general purpose counters/timers that can use one of the six __PIC32 oscillator inputs__.    +Counter/timer hardware is a crucial component of most embedded systems. In some cases, a timer is needed to measure elapsed time; in others, we want to count or time some external events. We will use timers to pace the execution of specific segments of code either by [[https://en.wikipedia.org/wiki/Polling_(computer_science)|polling]] timer flags or using [[https://en.wikipedia.org/wiki/Interrupt_latency|interrupts]] generated by the timer. The PIC32MX370 has a [[http://blog.flyingpic24.com/2009/04/02/using-the-32-bit-core-timer/|core timer]], a [[http://microchip.wikidot.com/8bit:wdt|watchdog timer]], and five general purpose counters/timers that can use one of the six [[http://microchip.wikidot.com/32bit:osc-overview|PIC32 oscillator inputs]].    
  
 The core timer and Timers 1 through 5 can be used to create blocking delays that are similar to the software delay presented in Lab 1b and shown again here in Listing 7.2. The advantages of a software time delay based on CPU execution speed, as shown here in Listing 7.2, are as follows:  The core timer and Timers 1 through 5 can be used to create blocking delays that are similar to the software delay presented in Lab 1b and shown again here in Listing 7.2. The advantages of a software time delay based on CPU execution speed, as shown here in Listing 7.2, are as follows: 
Line 201: Line 206:
 ---- ----
  
-=== 7.4.1. Timer Interrupts ===+=== 7.2.1. Timer Interrupts ===
 In the following labs, we will use Timer 1 to control the task execution timing so that the rotor of the stepper motor spins at a constant speed. The two instructions shown in Listing 7.4 will cause the Timer 1 interrupt flag to be set every tenth of a millisecond, assuming that the peripheral bus clock is running at 10 MHz. Even though an interrupt will be ever generated, the Timer 1 interrupt flag must be reset after the function that is polling the flag for timing purposes has detected that the flag has been set.  In the following labs, we will use Timer 1 to control the task execution timing so that the rotor of the stepper motor spins at a constant speed. The two instructions shown in Listing 7.4 will cause the Timer 1 interrupt flag to be set every tenth of a millisecond, assuming that the peripheral bus clock is running at 10 MHz. Even though an interrupt will be ever generated, the Timer 1 interrupt flag must be reset after the function that is polling the flag for timing purposes has detected that the flag has been set. 
  
Line 233: Line 238:
 // Listing 1. // Listing 1.
 } }
- 
 </code> </code>
  
Line 241: Line 245:
  
 The code shown in Listing 7.6 illustrates how to declare a function to be an ISR and the general format of an ISR function. For this example, the parameter //IPL2// sets the Timer 1 interrupt level to 2. This method of declaring an ISR eliminates the requirement of a function prototype.  The code shown in Listing 7.6 illustrates how to declare a function to be an ISR and the general format of an ISR function. For this example, the parameter //IPL2// sets the Timer 1 interrupt level to 2. This method of declaring an ISR eliminates the requirement of a function prototype. 
 +
  
 ---- ----
Line 246: Line 251:
 ==== Listing 7.6. Timer 1 ISR at Interrupt Level 2 ==== ==== Listing 7.6. Timer 1 ISR at Interrupt Level 2 ====
 <code> <code>
-void __ISR(_TIMER_1_VECTOR, IPL2) Timer1Handler(void) +void __ISR(_TIMER_1_VECTOR, IPL2SOFT) Timer1Handler(void) 
 {  {
  
Line 259: Line 264:
 ---- ----
  
-==== 7.5. Change Notification Interrupts ==== +==== 7.3. Change Notification Interrupts ==== 
-A change notification (CN) interrupt indicates that an input pin has changed level from a high to low or low to high. All of the PIC32MX370 IO pins are capable of generating a CN interrupt, except for RF6. All of the CN interrupts are vectored to the same ISR, thus requiring polling the CN status registers, CNSTATA through CNSTATG, to determine which pin or pins are responsible for generating the CN interrupt. The code in Listing 7.6 will initialize BTNC on the Basys MX3A trainer board to generate a change notification interrupt at group level 1, sub group level 2. Listing 7.8 provides the code for the CN interrupt service routine.+A change notification (CN) interrupt indicates that an input pin has changed level from a high to low or low to high. All of the PIC32MX370 IO pins are capable of generating a CN interrupt, except for RF6. All of the CN interrupts are vectored to the same ISR, thus requiring polling the CN status registers, CNSTATA through CNSTATG, to determine which pin or pins are responsible for generating the CN interrupt. The code in Listing 7.6 will initialize BTNC on the Basys MX3 trainer board to generate a change notification interrupt at group level 1, sub group level 2. Listing 7.8 provides the code for the CN interrupt service routine.
  
 ---- ----
Line 308: Line 313:
 A [[https://en.wikipedia.org/wiki/Finite-state_machine|finite state machine]] (FSM) is a behavior model for dynamic systems that determines what to do next based upon its current activity, the present conditions, and a stimulus. Current activities are called states. Present conditions are inputs that determine where to go and possible transitory activities. The stimulus is a trigger that indicates when to transition from one state to the next. A [[https://en.wikipedia.org/wiki/State_diagram|state diagram]] is a graphical representation (or model) of an FSM. A timer is in fact an FSM that uses a clock source as a trigger to advance the count, which is the timer’s state. A [[https://en.wikipedia.org/wiki/Finite-state_machine|finite state machine]] (FSM) is a behavior model for dynamic systems that determines what to do next based upon its current activity, the present conditions, and a stimulus. Current activities are called states. Present conditions are inputs that determine where to go and possible transitory activities. The stimulus is a trigger that indicates when to transition from one state to the next. A [[https://en.wikipedia.org/wiki/State_diagram|state diagram]] is a graphical representation (or model) of an FSM. A timer is in fact an FSM that uses a clock source as a trigger to advance the count, which is the timer’s state.
  
-As an example, consider a simple momentary contact push button that you want to operate in a push-on / push-off fashion. Although the button is in the on condition only while being pressed, we want a system that remembers that it was pressed and maintains the “on” condition. When the button is pressed the next time, we want the on condition to be remembered so the output will transition to the “off” condition. Figure 7.2 is a state diagram representation of the push-on / push-off operation. Although there are many variations to the actual drawing of a state diagram, we will use one that follows the [[http://www.sparxsystems.com/resources/uml2_tutorial/uml2_statediagram.html|UML]] approach.  +As an example, consider a simple momentary contact push button that you want to operate in a push-on / push-off fashion. Although the button is in the on condition only while being pressed, we want a system that remembers that it was pressed and maintains the “on” condition. When the button is pressed the next time, we want the on condition to be remembered so the output will transition to the “off” condition. Figure 7.2 is a state diagram representation of the push-on / push-off operation. Although there are many variations to the actual drawing of a state diagram, we will use one that follows the [[http://www.sparxsystems.com/resources/uml2_tutorial/uml2_statediagram.html|UML]] approach.   
- +
 Each rounded box in Fig. 7.2 represents a stable state and each directed arrow represents a transition between states. The circle containing the uppercase letter “I” is the initial conditions and is directed to the initial state. Each state is identified by name or number above the horizontal line. The actions ascribed to the state are described below the line. The state action is divided into two actions separated by a colon. The left action declares the action generated on entry to the state. The action to the right of the colon declares the action generated on exit from the state.  Each rounded box in Fig. 7.2 represents a stable state and each directed arrow represents a transition between states. The circle containing the uppercase letter “I” is the initial conditions and is directed to the initial state. Each state is identified by name or number above the horizontal line. The actions ascribed to the state are described below the line. The state action is divided into two actions separated by a colon. The left action declares the action generated on entry to the state. The action to the right of the colon declares the action generated on exit from the state. 
  
 Transitions describe both events (triggers) with guards and actions associated with the transaction. Guards represent conditions that inhibit the transaction. There may be multiple transitions between the same two states. Each path represents differing guard conditions and differing transaction actions.  Transitions describe both events (triggers) with guards and actions associated with the transaction. Guards represent conditions that inhibit the transaction. There may be multiple transitions between the same two states. Each path represents differing guard conditions and differing transaction actions. 
  
-{{ :learn:courses:unit-2:figure-7-2.png?nolink |Figure 7.2. State diagram for a push-on / push-off button operation.}}+{{ :learn:courses:unit-2:unit_2_fig_7_2.jpg?nolink&650 |Figure 7.2. State diagram for a push-on / push-off button operation.}}
 //Figure 7.2. State diagram for a push-on / push-off button operation.// //Figure 7.2. State diagram for a push-on / push-off button operation.//
  
-The button action described by Fig. 7.2 shows that four states are required to represent its operation: two states are needed for a button press and release when the switch is on, as well as when the switch is off. There is only one possible event that initiates a transition: the clock event, which for this example is a millisecond timer. The number of clock pulses is counted to hold the system in a fixed state until the predefined delay period has expired. This is used to eliminate multiple transitions due to [[http://www.eng.utah.edu/~cs5780/debouncing.pdf|switch contact bounce]] when a button is pressed. +The button action described by Fig. 7.2 shows that four states are required to represent its operation: two states are needed for a button press and release when the switch is on, as well as when the switch is off. There is only one possible event that initiates a transition: the clock event, which for this example is a millisecond timer. The number of clock pulses is counted to hold the system in a fixed state until the predefined delay period has expired. This is used to eliminate multiple transitions due to [[http://www.eng.utah.edu/~cs5780/debouncing.pdf|switch contact bounce]] when a button is pressed.  
    
 The guard condition on the clock event inhibits the transition between states unless the button is in the proper pressed or released condition. The action associated with the transaction controls an LED to indicate the condition of the push-on/push-off switch output, sw. It is apparent from Fig. 7.2 that even relatively simple dynamic systems can result in complex logic. The guard condition on the clock event inhibits the transition between states unless the button is in the proper pressed or released condition. The action associated with the transaction controls an LED to indicate the condition of the push-on/push-off switch output, sw. It is apparent from Fig. 7.2 that even relatively simple dynamic systems can result in complex logic.
  
-[[https://www.embeddedrelated.com/showarticle/723.php|Software state machines]] inherently define control of the computer code. Our code execution control options include “if-else” constructs, “do-while” loops, and “[[https://en.wikipedia.org/wiki/Switch_statement|switch-case]]" software constructs. The most common software control construct for software state machines is the “switch-case” implementation. Listing 7.9 is a C function that implements the control flow represented in Fig. 7.2. This function is called each millisecond and is passed the condition of the push button. Local variables are declared “static” to provide the state memory for the delay timer, the process state, and the switch output. The implementation in Listing 7.9 is [[http://www.kegel.com/dkftpbench/nonblocking.html|non-blocking]], meaning that the function immediately returns to the calling code regardless of the state of the push button or the delay timer.+[[https://www.embeddedrelated.com/showarticle/723.php|Software state machines]] inherently define control of the computer code. Our code execution control options include “if-else” constructs, “do-while” loops, and “[[https://en.wikipedia.org/wiki/Switch_statement|switch-case]]” software constructs. The most common software control construct for software state machines is the “switch-case” implementation. Listing 7.9 is a C function that implements the control flow represented in Fig. 7.2. This function is called each millisecond and is passed the condition of the push button. Local variables are declared “static” to provide the state memory for the delay timer, the process state, and the switch output. The implementation in Listing 7.9 is [[http://www.kegel.com/dkftpbench/nonblocking.html|non-blocking]], meaning that the function immediately returns to the calling code regardless of the state of the push button or the delay timer.
  
 ---- ----
Line 338: Line 343:
    {    {
        case 0:        case 0:
-if(button) /* Button pressed - switch on */+           if(button) /* Button pressed - switch on */
            {            {
                setLED0(1);                setLED0(1);
Line 395: Line 400:
 The main component of such a timing system is a free running binary counter. The counter increments with each incoming timing pulse. The counter counts continuously from 0 to 2n-1, where n is the number of bits in the counter. Since it runs independently, it can count inputs or clock pulses concurrently while the microcontroller is executing the main program. If the input clock to the binary counter has a fixed known frequency, we can make an accurate measurement of time interval by counting the pulses of the clock. The PIC32MX370 processor has a watchdog timer, five 16-bit counters/timers, and a 32-bit core timer.   The main component of such a timing system is a free running binary counter. The counter increments with each incoming timing pulse. The counter counts continuously from 0 to 2n-1, where n is the number of bits in the counter. Since it runs independently, it can count inputs or clock pulses concurrently while the microcontroller is executing the main program. If the input clock to the binary counter has a fixed known frequency, we can make an accurate measurement of time interval by counting the pulses of the clock. The PIC32MX370 processor has a watchdog timer, five 16-bit counters/timers, and a 32-bit core timer.  
  
-==== Watchdog Timer ==== +==== A.1. Watchdog Timer ==== 
-A __watchdog timer__ (WDT) is a device used to protect a system from specific software or hardware failures that may cause the system to stop responding. The application is first registered with the watchdog device. Once the watchdog is running on your system, the application must periodically send information to the watchdog device. The PIC32 [[http://ww1.microchip.com/downloads/en/DeviceDoc/61114E.pdf|watchdog timer]] is powered from the low power RC oscillator, and once enabled, must be reset periodically or the system will undergo a power-on reset using software instructions. Although watchdog timers are an important concept in developing secure and dependable code, their usage is beyond the scope of this unit.+A [[https://en.wikipedia.org/wiki/Watchdog_timer|watchdog timer]] (WDT) is a device used to protect a system from specific software or hardware failures that may cause the system to stop responding. The application is first registered with the watchdog device. Once the watchdog is running on your system, the application must periodically send information to the watchdog device. The PIC32 [[http://ww1.microchip.com/downloads/en/DeviceDoc/61114E.pdf|watchdog timer]] is powered from the low power RC oscillator, and once enabled, must be reset periodically or the system will undergo a power-on reset using software instructions. Although watchdog timers are an important concept in developing secure and dependable code, their usage is beyond the scope of this unit.
  
-==== The Core Timer ==== +==== A.2. The Core Timer ==== 
-Unlike 8 and 16-bit Microchip PIC processors, the PIC32 processor that uses the MIPS32® M4K® core has a core timer that keeps time using the 32-bit MIPS32 internal register 9 named “Count.” Although infrequently used, the [[http://blog.flyingpic24.com/2009/04/02/using-the-32-bit-core-timer/|core timer]] can generate an interrupt using the MIPS32 internal register 11 named “Compare.” The core oscillator counts at one half the System Clock frequency, as shown in Fig. A.1, and can be used to generate a millisecond software delay using the code shown in Listing A.1.   +Unlike 8- and 16-bit Microchip PIC processors, the PIC32 processor that uses the MIPS32® M4K® core has a core timer that keeps time using the 32-bit MIPS32 internal register 9 named “Count.” Although infrequently used, the [[http://blog.flyingpic24.com/2009/04/02/using-the-32-bit-core-timer/|core timer]] can generate an interrupt using the MIPS32 internal register 11 named “Compare.” The core oscillator counts at one half the System Clock frequency, as shown in Fig. A.1, and can be used to generate a millisecond software delay using the code shown in Listing A.1.    
  
 ---- ----
Line 405: Line 410:
 ==== Listing A.1. Millisecond Delay Based on Polling the Core Timer ==== ==== Listing A.1. Millisecond Delay Based on Polling the Core Timer ====
 <code> <code>
-#define CORE_MS_TICK_RATE CORE_OSCILLATOR_FREQUERNCY/2/1000+#define CORE_MS_TICK_RATE CORE_OSCILLATOR_FREQUENCY/2/1000
 void msDelay(unsigned int mS) void msDelay(unsigned int mS)
 { {
Line 417: Line 422:
 Refer to Section 2.12 of the [[http://ww1.microchip.com/downloads/en/DeviceDoc/61113E.pdf|PIC32 Family Reference Manual]] for additional information concerning uses of the core timer. Refer to Section 2.12 of the [[http://ww1.microchip.com/downloads/en/DeviceDoc/61113E.pdf|PIC32 Family Reference Manual]] for additional information concerning uses of the core timer.
  
-{{ :learn:courses:unit-2:figure-a-1.png?nolink |Figure A.1. Core timer block diagram.}}+{{ :learn:courses:unit-2:unit_2_fig_a_1.jpg?nolink |Figure A.1. Core timer block diagram.}}
 //Figure A.1. Core timer block diagram.// //Figure A.1. Core timer block diagram.//
- +==== A.3. Types of Timers ====
-==== Types of Timers ====+
 [[http://ww1.microchip.com/downloads/en/DeviceDoc/61105E.pdf|Section 14 of the PIC32 Family Reference Manual]] identifies two types of timers. Generically, all timers have a block diagram, as shown in Fig. A.2. A Type A timer is a 16-bit counter that can be clocked from either the peripheral bus clock or from a secondary oscillator that typically uses a 32 kHz crystal and is used for the real-time clock applications. This timer can be used to generate an interrupt that will wake up the processor after it has been put into a sleep mode. The clock source for the timer has the option of four software-programmable pre-scale dividers: 1, 8, 64, or 256. The PIC32 Timer 1 is a Type A timer or counter. [[http://ww1.microchip.com/downloads/en/DeviceDoc/61105E.pdf|Section 14 of the PIC32 Family Reference Manual]] identifies two types of timers. Generically, all timers have a block diagram, as shown in Fig. A.2. A Type A timer is a 16-bit counter that can be clocked from either the peripheral bus clock or from a secondary oscillator that typically uses a 32 kHz crystal and is used for the real-time clock applications. This timer can be used to generate an interrupt that will wake up the processor after it has been put into a sleep mode. The clock source for the timer has the option of four software-programmable pre-scale dividers: 1, 8, 64, or 256. The PIC32 Timer 1 is a Type A timer or counter.
  
 Timers 1 through 5 are 16-bit timers which support both synchronous external timer modes of operation. Timer 1 also allows asynchronous external mode which enables operations during sleep mode when the master oscillator is turned off and controller operation is done using a secondary oscillator. Timers 1 through 5 are 16-bit timers which support both synchronous external timer modes of operation. Timer 1 also allows asynchronous external mode which enables operations during sleep mode when the master oscillator is turned off and controller operation is done using a secondary oscillator.
  
-{{ :learn:courses:unit-2:figure-a-2.png?nolink |Figure A.2. Simplified PIC32 timer block diagram.}}+{{ :learn:courses:unit-2:unit_2_fig_a_2.jpg?nolink&550 |Figure A.2. Simplified PIC32 timer block diagram.}}
 //Figure A.2. Simplified PIC32 timer block diagram.// //Figure A.2. Simplified PIC32 timer block diagram.//
  
Line 431: Line 435:
  
 The clock source for Timers 1 through 5 can be an external input or the peripheral clock. The external input for Timer 1 is the output from the secondary oscillator. All timers can be gated by software that generates a timing window.   The clock source for Timers 1 through 5 can be an external input or the peripheral clock. The external input for Timer 1 is the output from the secondary oscillator. All timers can be gated by software that generates a timing window.  
 + 
  
-==== Determining the Timer Input Clock and Rollover Frequency ==== +==== A.4. Determining the Timer Input Clock and Rollover Frequency ==== 
-The maximum counter value is determined by the size of the register that holds the counts. Common sizes for microprocessors are 8, 16, and 32-bit. Including the core timer, The the PIC32 processor has six timers that can be used for delay timing. The core timer is 32 bits wide. Timers 2 and 3 along with Timers 4 and 5 can be used together as 32-bit counters respectively, extending the count value range from 65,536 to 4,294,967,296. As shown in Fig. A.3, when the counter register equals the value of the period register (PR), the counter is reset to zero and the timer interrupt flag is set. Although the core timer can be reset to any value, PIC32 documentation recommends that such practices be avoided. +The maximum counter value is determined by the size of the register that holds the counts. Common sizes for microprocessors are 8-, 16-, and 32-bit. Including the core timer, the PIC32 processor has six timers that can be used for delay timing. The core timer is 32 bits wide. Timers 2 and 3 along with Timers 4 and 5 can be used together as 32-bit counters, respectively, extending the count value range from 65,536 to 4,294,967,296. As shown in Fig. A.3, when the counter register equals the value of the period register (PR), the counter is reset to zero and the timer interrupt flag is set. Although the core timer can be reset to any value, PIC32 documentation recommends that such practices be avoided. 
  
-The period register is used to set the timer’s maximum count. If a period equal to a value of N is set, then N-1 is written to the PR register. The period registers are declared as PR1 for Timer 1, PR2 for Timer 2, and so on. Each Timer 1 count is compared to the value of the PR1 register. When the PR1 register equals the Timer 1 register, the timer has reached its terminal count and initiates two actions: first, the Timer 1 register is reset to zero, and second, the Timer 1 Interrupt Flag (T1IF) bit is set in the Interrupt Flag Status register (IFS0). (See the [[http://ww1.microchip.com/downloads/en/DeviceDoc/61156G.pdf|PIC32MX3xx/4xx/5xx Users Manual]] Sheet Section 7, Table 7-1 for additional information.) +The period register is used to set the timer’s maximum count. If a period equal to a value of N is set, then N-1 is written to the PR register. The period registers are declared as PR1 for Timer 1, PR2 for Timer 2, and so on. Each Timer 1 count is compared to the value of the PR1 register. When the PR1 register equals the Timer 1 register, the timer has reached its terminal count and initiates two actions: first, the Timer 1 register is reset to zero, and second, the Timer 1 Interrupt Flag (T1IF) bit is set in the Interrupt Flag Status register (IFS0). (See the [[http://ww1.microchip.com/downloads/en/DeviceDoc/60001185F.pdf|PIC32MX3xx/4xx/5xx User’s Manual]] Sheet Section 7, Table 7-1 for additional information.) 
  
-As Fig. A.3 illustrates, the Timer 1 clock frequency (T1CLK) is determined from the crystal frequency on the Basys MX3 trainer board (XTAL), the PLL input divider (FPLLIDIV), the PLL multiplier (FPLLMUL), the PLL output divider (FPLLODIV), the peripheral bus clock divider (FPBDIV), and the Timer pre-scale (TCKPS). This frequency is computed using Eq.1. The values of XTAL, FPLLMUL, FPLLDIV, FPLLODIV, and FPBDIV are set in the common “//config_bits.h//” header file.+As Fig. A.3 illustrates, the Timer 1 clock frequency (T1CLK) is determined from the crystal frequency on the Basys MX3 trainer board (XTAL), the PLL input divider (FPLLIDIV), the PLL multiplier (FPLLMUL), the PLL output divider (FPLLODIV), the peripheral bus clock divider (FPBDIV), and the Timer pre-scale (TCKPS). This frequency is computed using Eq.1. The values of XTAL, FPLLMUL, FPLLDIV, FPLLODIV, and FPBDIV are set in the common “config_bits.h” header file.  
  
 $$T1CLK = (XTAL * FPLLMUL / ( FPLLIDIV * FPLLODIV * FPBDIV ))  /  TCKPS)  (Eq. 1)$$ $$T1CLK = (XTAL * FPLLMUL / ( FPLLIDIV * FPLLODIV * FPBDIV ))  /  TCKPS)  (Eq. 1)$$
  
-{{ :learn:courses:unit-2:figure-a-3.png?nolink |Figure A.3. Divider chain from the CPU crystal (oscillator) to the Timer 1 Interrupt flag.}}+{{ :learn:courses:unit-2:unit_2_fig_a_3.jpg?nolink |Figure A.3. Divider chain from the CPU crystal (oscillator) to the Timer 1 Interrupt flag.}}
 //Figure A.3. Divider chain from the CPU crystal (oscillator) to the Timer 1 Interrupt flag.// //Figure A.3. Divider chain from the CPU crystal (oscillator) to the Timer 1 Interrupt flag.//
  
-Since the Timer 1 register is reset to zero, the value set into the PR register is one less than the desired number of Timer 1 clock counts. Hence, the rate that the timer interrupt flag is set equals the timer clock frequency divided by the value written to the PR register, as expressed by Eq. 2. For example, using the values shown in Fig. A.4, the T1PS is set for 8 and the PR1 register is set to 24999. The result of these settings is that the T1 interrupt flag is set at the rate of 50 Hz, provided that the subsequent interrupt flag is cleared in software. The T1IF can be polled or used to generate interrupts. Timers 2 through 5 are similar to Timer 1, with the differences being the timer pre-scale options and the period register.+Since the Timer 1 register is reset to zero, the value set into the PR register is one less than the desired number of Timer 1 clock counts. Hence, the rate that the timer interrupt flag is set equals the timer clock frequency divided by the value written to the PR register, as expressed by Eq. 2. For example, using the values shown in Fig. A.3, the T1PS is set for 8 and the PR1 register is set to 24999. The result of these settings is that the T1 interrupt flag is set at the rate of 50 Hz, provided that the subsequent interrupt flag is cleared in software. The T1IF can be polled or used to generate interrupts. Timers 2 through 5 are similar to Timer 1, with the differences being the timer pre-scale options and the period register.
  
-==== Timer Interrupts ====+==== A.5. Timer Interrupts ====
 Once the timer interrupt flag is set, it will remain set until a software instruction clears the flag. (Since the timer interrupt has not been enabled, although the timer interrupt flag is set, no interrupt will be generated. Thus, all peripherals that can potentially be used to generate an interrupt can also be used in a polled mode.) Once the timer interrupt flag is set, it will remain set until a software instruction clears the flag. (Since the timer interrupt has not been enabled, although the timer interrupt flag is set, no interrupt will be generated. Thus, all peripherals that can potentially be used to generate an interrupt can also be used in a polled mode.)
  
 [[http://ww1.microchip.com/downloads/en/DeviceDoc/32bitPeripheralLibraryGuide.pdf|Section 11 of the 32-bit Peripheral Library Guide]] contains the functions pertaining to the core timer and Timers 1 through 5. Timers are initialized using the //OpenTimer// function that requires two arguments: the configuration argument and the initial PR value. For example, initializing Timer 1 to use the peripheral bus clock, a pre-scale value of 8, and an initial period of 1000 requires the following assignment: [[http://ww1.microchip.com/downloads/en/DeviceDoc/32bitPeripheralLibraryGuide.pdf|Section 11 of the 32-bit Peripheral Library Guide]] contains the functions pertaining to the core timer and Timers 1 through 5. Timers are initialized using the //OpenTimer// function that requires two arguments: the configuration argument and the initial PR value. For example, initializing Timer 1 to use the peripheral bus clock, a pre-scale value of 8, and an initial period of 1000 requires the following assignment:
 +
  
 <code> <code>
Line 457: Line 463:
 The arguments to this procedure are defined in timers.h of the peripheral library. The timer interrupt flag is polled using the macro statement, //mTxGetIntFlag();//, and can be cleared using the macro //mTxClearFlag()//. Both macros are defined by the peripheral library. The arguments to this procedure are defined in timers.h of the peripheral library. The timer interrupt flag is polled using the macro statement, //mTxGetIntFlag();//, and can be cleared using the macro //mTxClearFlag()//. Both macros are defined by the peripheral library.
  
-The PR register for the timers can be changed within the software at any time by simply using the assignment: //PRx = ###//; or //WritePeriodx (###);//, where x is the timer number (1 through 5) and ### is the value to be set into the PR register. The program shown in Listing A.3 illustrates using Timer 1 to implement a delay by polling the interrupt flag.  +The PR register for the timers can be changed within the software at any time by simply using the assignment: //PRx = ###;// or //WritePeriodx (###);//, where x is the timer number (1 through 5) and ### is the value to be set into the PR register. The program shown in Listing A.3 illustrates using Timer 1 to implement a delay by polling the interrupt flag.   
  
 ---- ----
Line 478: Line 485:
 * *
 * Oscillator Configuration Bit Settings: config_bits.h * Oscillator Configuration Bit Settings: config_bits.h
-* Basys MX3 hardware initialization is provided by Hardware_Setup.c +* Basys MX3 hardware initialization is provided by hardware.c and should be included as a project source file.
 * Notes: * Notes:
 *   - Peripheral clock: BPCLK = FOSC/PB_DIV = 80E6/8 = 10MHz *   - Peripheral clock: BPCLK = FOSC/PB_DIV = 80E6/8 = 10MHz
 *   - Timer 1 clock = T1_CLK = PBCLK / T1PS = 10E6 / 8 = 1.25E5 *   - Timer 1 clock = T1_CLK = PBCLK / T1PS = 10E6 / 8 = 1.25E5
-*   - To generate a 1 ms delay, PR1 is loaded with T1_TICK = (10000-1) = 9999+*   - To generate a 1 ms delay, PR1 is loaded with T1_TICK - 1 = (1250 - 1) = 1249
 * *
 ********************************************************************/ ********************************************************************/
-#include "config_bits.h" 
 #include <plib.h> #include <plib.h>
 +#include "config_bits.h"
 +#include "hardware.h"
  
 /* Application constant */ /* Application constant */
Line 499: Line 507:
  
 /* Configure Timer1 to roll over once each second */ /* Configure Timer1 to roll over once each second */
-   OpenTimer1(T1_ON | T1_SOURCE_INT | T1_PS_1_256, T1_TICK - 1);+   OpenTimer1(T1_ON | T1_SOURCE_INT | T1_PS_1_8, T1_TICK - 1);
  
    while (1)     while (1) 
Line 512: Line 520:
    }     } 
        
-   return (EXIT_FAILURE);  /* System has failed is this line is reached */+   return (EXIT_FAILURE);  /* System has failed if this line is reached */
 } /* End of File main.c */  } /* End of File main.c */ 
 </code> </code>
Line 556: Line 564:
 /********************************************************************* /*********************************************************************
 * The purpose of this example code is to demonstrate the use of the Type A  * The purpose of this example code is to demonstrate the use of the Type A 
-* Timer 1 interrupts to generate a 1 ms delay.+* Timer 1 interrupts to generate a 1 second delay.
 * *
 * Platform:     Basys MX3  * Platform:     Basys MX3 
Line 569: Line 577:
 * *
 * Oscillator Configuration Bit Settings: config_bits.h * Oscillator Configuration Bit Settings: config_bits.h
-* Basys MX3 hardware initialization is provided by Hardware_Setup.c +* Basys MX3 hardware initialization is provided by hardware.c 
 * Notes: * Notes:
 *        - Peripheral Clock: PBCLK = 80E6 / 8 = 10E6  *        - Peripheral Clock: PBCLK = 80E6 / 8 = 10E6 
Line 576: Line 584:
 * *
 ********************************************************************/ ********************************************************************/
 +
 +#include <plib.h>       /* Include peripheral library */
 #include "config_bits.h"   /* System configuration */ #include "config_bits.h"   /* System configuration */
-#include <plib.h>    /* Include peripheral library */+#include "hardware.h"      /* Includes GetPeripheralClock() */
                                                
 /* Application constant */ /* Application constant */
-#define T1_PRESCALE      8 +#define T1_PRESCALE      256 
-#define TOGGLES_PER_SEC  1000+#define TOGGLES_PER_SEC  1
 #define T1_TICK          (GetPeripheralClock() / T1_PRESCALE / TOGGLES_PER_SEC) #define T1_TICK          (GetPeripheralClock() / T1_PRESCALE / TOGGLES_PER_SEC)
  
Line 610: Line 620:
        /* Code background tasks */        /* Code background tasks */
    }     } 
-   return (EXIT_FAILURE);  /* System has failed is this line is reached */+   return (EXIT_FAILURE);  /* System has failed if this line is reached */
 } /* End of main */  } /* End of main */ 
  
Line 617: Line 627:
 * SYNTAX:         void __ISR(_TIMER_1_VECTOR, IPL2SOFT) Timer1Handler(void) * SYNTAX:         void __ISR(_TIMER_1_VECTOR, IPL2SOFT) Timer1Handler(void)
 * KEYWORDS:       millisecond, hardware delay, Timer A, timer * KEYWORDS:       millisecond, hardware delay, Timer A, timer
-* DESCRIPTION:    Services the Timer 1 interrupt and toggles LED1+* DESCRIPTION:    Services the Timer 1 interrupt and toggles LED0
 * Parameters:     None * Parameters:     None
 * RETURN:         None * RETURN:         None
Line 633: Line 643:
 /* End of File main.c  */ /* End of File main.c  */
 </code> </code>
 +
 +----
 +
 +[[{}learn/courses/microprocessor-io-unit-1/start|Back to Unit 1]]
 +[[{}/learn/courses/unit-2-lab2a/start|Go to Lab 2a]]
 +[[{}/learn/courses/unit-2-lab2b/start|Go to Lab 2b]]
 +[[{}/learn/courses/unit-3/start|Go to Unit 3]]
 +
 +----
 +
 +{{tag>reference learn microprocessor courses basys-mx3}}