diff options
author | Cristian Eigel <cristian.eigel@esrlabs.com> | 2022-02-16 21:22:35 +0100 |
---|---|---|
committer | Cristian Eigel <cristian.eigel@esrlabs.com> | 2022-02-16 21:22:35 +0100 |
commit | f4ac3cf3648494dfbe6c18148bbef55ddc7f9f48 (patch) | |
tree | 01372a186cda2dd1603b1f83e8d42087179988a7 /examples/stm32f3/src/bin/button_events.rs | |
parent | 59f909e66533097b56093ec55fdd1341dbff6744 (diff) | |
download | embassy-f4ac3cf3648494dfbe6c18148bbef55ddc7f9f48.zip |
Improve logic for processing button events
Diffstat (limited to 'examples/stm32f3/src/bin/button_events.rs')
-rw-r--r-- | examples/stm32f3/src/bin/button_events.rs | 40 |
1 files changed, 25 insertions, 15 deletions
diff --git a/examples/stm32f3/src/bin/button_events.rs b/examples/stm32f3/src/bin/button_events.rs index 1218edd2..0bd7b342 100644 --- a/examples/stm32f3/src/bin/button_events.rs +++ b/examples/stm32f3/src/bin/button_events.rs @@ -50,11 +50,17 @@ impl<'a> Leds<'a> { } } - async fn blink(&mut self) { + async fn show(&mut self, queue: &mut Receiver<'static, NoopRawMutex, ButtonEvent, 4>) { self.leds[self.current_led].set_high(); - Timer::after(Duration::from_millis(500)).await; - self.leds[self.current_led].set_low(); - Timer::after(Duration::from_millis(200)).await; + if let Ok(new_message) = with_timeout(Duration::from_millis(500), queue.recv()).await { + self.leds[self.current_led].set_low(); + self.process_event(new_message).await; + } else { + self.leds[self.current_led].set_low(); + if let Ok(new_message) = with_timeout(Duration::from_millis(200), queue.recv()).await { + self.process_event(new_message).await; + } + } } async fn flash(&mut self) { @@ -69,8 +75,21 @@ impl<'a> Leds<'a> { Timer::after(Duration::from_millis(200)).await; } } + + async fn process_event(&mut self, event: Option<ButtonEvent>) { + match event { + Some(ButtonEvent::SingleClick) => self.move_next(), + Some(ButtonEvent::DoubleClick) => { + self.change_direction(); + self.move_next() + } + Some(ButtonEvent::Hold) => self.flash().await, + _ => {} + } + } } +#[derive(Format)] enum ButtonEvent { SingleClick, DoubleClick, @@ -105,19 +124,10 @@ async fn main(spawner: Spawner, p: Peripherals) { #[embassy::task] async fn led_blinker( mut leds: Leds<'static>, - queue: Receiver<'static, NoopRawMutex, ButtonEvent, 4>, + mut queue: Receiver<'static, NoopRawMutex, ButtonEvent, 4>, ) { loop { - leds.blink().await; - match queue.try_recv() { - Ok(ButtonEvent::SingleClick) => leds.move_next(), - Ok(ButtonEvent::DoubleClick) => { - leds.change_direction(); - leds.move_next() - } - Ok(ButtonEvent::Hold) => leds.flash().await, - _ => {} - } + leds.show(&mut queue).await; } } |