The third video introduces interrupts and shows how to program an interrupt to manage complex applications.
In the first video, we made a direct connection between the push button and the pin driving the LED. In a second video, we had to use the CyDelay function to toggle the LED at 1 Hz. Most of the time, these are not an optimized way to use the microcontroller. It’s better to trigger interrupts to perform a given action and then free the microcontroller for more tasks to manage complex applications or put it in low power mode to decrease the average current consumption of the application.
For this new project the red LED is connected to port 2 pin 6 again and with no hardware connection as pin level to turn on and off the LED will be handled by interrupt and C code.
An input pin to detect the switch is closed. As the switch connects to ground when closed, this pin must be configured with an interrupt on a falling edge, a driving mode as resistive pull up and an initial drive state at high. An interrupt component can then be attached. The interrupt component is named Pin_SW_Int.
All the information about the available APIs is in the datasheets. To detect an interrupt, the function Pin_SW_Int_StartEx with the name of handler as parameter makes the job. It calls the function CY_ISR where we toggle the red LED and clear the interrupt
To automatically toggle the LED, a TCPWM component configured as a timer is connected to an interrupt component. To make math simple, a 32 kHz clock feeds the timer and the period is programmed at 32,000 counts. Hence, an interrupt is triggered every second.
The C code is very simple again. The timer must be started, then the detection of the interrupt to call the Interrupt Service Routine. The LED is then toggled and the interrupt is cleared.