This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| en:iot-open:introductiontoembeddedprogramming2:cppfundamentals:interrupts [2023/07/13 12:44] – pczekalski | en:iot-open:introductiontoembeddedprogramming2:cppfundamentals:interrupts [2023/11/23 12:22] (current) – pczekalski | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | ====== Interrupts ====== | ||
| + | {{: | ||
| + | // | ||
| + | |||
| + | ISR should be as short as possible; good practice is avoiding delays and long code sequences. Suppose there is a need to trigger the execution of a long part of the code with an incoming interrupt signal. In that case, the good practice is to define the synchronization variable, modify this variable in the ISR with a single instruction, | ||
| + | |||
| + | Interrupts are used to detect critical real-time events which occur during normal code execution of the code. ISR is executed only when there is a need to do it. | ||
| + | |||
| + | ==== Polling vs. interrupts ==== | ||
| + | |||
| + | Interrupts can help in efficient data transmission. Using interrupts and checking if some situation occurred periodically is unnecessary. Such continuous checking is named polling. For example, a serial port interrupt is executed only when new data comes without polling the incoming buffer in a loop. This approach saves the processor time and, in many situations, creates code that is more energy efficient. | ||
| + | |||
| + | ==== Interrupt handling example ==== | ||
| + | |||
| + | Because interrupts need support from the hardware layer of the microcontroller, | ||
| + | |||
| + | Very often, interrupts are used together with hardware timers to generate stable frequency signals. It ensures accurate timing independent of the main loop content and delays. Because internal peripherals are very different for different microcontrollers in this chapter, the example for the external interrupt is shown. | ||
| + | |||
| + | The function '' | ||
| + | - '' | ||
| + | - '' | ||
| + | - '' | ||
| + | * '' | ||
| + | * '' | ||
| + | * '' | ||
| + | * '' | ||
| + | * '' | ||
| + | |||
| + | The example program that uses external interrupt: | ||
| + | |||
| + | <code c> | ||
| + | volatile bool button_toggle = 0; //A variable to pass the information | ||
| + | // | ||
| + | |||
| + | void setup() { | ||
| + | pinMode(13, | ||
| + | pinMode(2, | ||
| + | attachInterrupt(digitalPinToInterrupt(2), | ||
| + | // | ||
| + | } | ||
| + | |||
| + | void ButtonIRS() { //IRS function | ||
| + | button_toggle =!button_toggle; | ||
| + | } | ||
| + | |||
| + | void loop() { | ||
| + | digitalWrite (13, | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | In this example, the code needed to handle the interrupt signal is just one instruction. Still, it shows how to use the synchronization variable to pass information from ISR to the main program, keeping the ISR very short. | ||