Skip to content

Commit 4dd6958

Browse files
committed
Add interrpt exercise.
1 parent 384ae16 commit 4dd6958

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/led_with_interrupt.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Exercise: toggle LED with interrupt
2+
3+
Now that we have set up the GPIO interrupt, try using it to toggle the LED.
4+
There are many ways to achieve this, so let's set some specific requirements:
5+
6+
1. Use [`AtomicBool`][1]
7+
8+
We have already seen how to use a Mutex, so for this exercise, let's try something new.
9+
10+
1. Toggle the LED in the main loop
11+
12+
In general, we want to avoid doing any work in the interrupt handler,
13+
so use the `AtomicBool` to signal to the main loop that the LED should be toggled.
14+
Remove any other code from the loop for now.
15+
16+
1. Use `FallingEdge` interrupt type
17+
1. Take care of debouncing
18+
19+
You will encounter switch bounce - several interrupt events occurring from a single button press.
20+
Try to come up with a solution for this problem so that the LED is only toggled once per button press.
21+
There are a multitude of ways to implement this so any solution that works is fine.
22+
23+
<details>
24+
<summary><strong>Solution</strong></summary>
25+
26+
First, we'll need to import `atomic` and then declare our static object object.
27+
28+
```rust
29+
use core::sync::atomic;
30+
31+
static BUTTON_EVENT: atomic::AtomicBool = atomic::AtomicBool::new(false);
32+
```
33+
34+
Next, set the `BUTTON_EVENT` in the `button_handler()`:
35+
36+
```rust
37+
BUTTON_EVENT.store(true, atomic::Ordering::Relaxed);
38+
```
39+
40+
Finally, in the main loop, let's check the `BUTTON_EVENT` and if it's `true`, toggle the LED.
41+
42+
```rust
43+
loop {
44+
if BUTTON_EVENT.load(atomic::Ordering::Relaxed) {
45+
led.toggle();
46+
// Delay before resetting the BUTTON_EVENT acts as debouncing logic.
47+
delay.delay_millis(150);
48+
BUTTON_EVENT.store(false, atomic::Ordering::Relaxed);
49+
}
50+
}
51+
```
52+
53+
</details>
54+
55+
[1]: https://doc.rust-lang.org/nightly/std/sync/atomic/struct.AtomicBool.html#method.compare_exchange

0 commit comments

Comments
 (0)