added efficient toggle example

This commit is contained in:
2025-02-04 20:37:53 +05:30
parent 33fdab9c18
commit ae278424ab

View File

@@ -107,3 +107,30 @@ In the interrupt model, the code to run when an interrupt in triggered must be s
Most of the code in `main` is the same from older examples, to initialize, set the direction and supplementary settings like drive strength and pull. The new function here, `gpio_set_irq_enabled_with_callback` attaches the `ReadLED` function to a GPIO Pin. The first argument is the gpio pin to attach the interrupt, it is the same as the gpio pin use everywhere. Second argument is for providing the incidents when the function should run. Third argument is a to mention if this interrupt is enabled of not and the fourth argument is the function to call when the mentioned incident happens on the mentioned pin.
Since this is detached from the main loop, the main code can move on to run other functions, which is nothing in this case.
## EfficientToggle
This example uses the same interrupt based code execution, but this will toggle the led when the button is pressed.
The only changes are in the `readLED` function, where the state of the led output pin is toggled when a falling edge is obesrved.
```c
void ReadLED(int pin, uint32_t event)
{
// if (pin == BUTTON_PIN && event & GPIO_IRQ_EDGE_RISE)
// {
// gpio_put(LED_PIN, 1);
// }
// else
if (pin == BUTTON_PIN && event & GPIO_IRQ_EDGE_FALL)
{
gpio_put(LED_PIN, !gpio_get(LED_PIN));
}
}
```
The irq register function is also changed to remove the rising edge condition
```c
gpio_set_irq_enabled_with_callback(BUTTON_PIN, GPIO_IRQ_EDGE_FALL, true, ReadLED);
```