summaryrefslogtreecommitdiff
path: root/examples/stm32f3/src/bin/button_events.rs
blob: 02c475f6621e29ca1e18c237ee5949ecddd0edf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
//! This example showcases channels and timing utilities of embassy.
//!
//! This example works best on STM32F3DISCOVERY board. It flashes a single LED, then if the USER
//! button is pressed the next LED is flashed (in clockwise fashion). If the USER button is double
//! clicked, then the direction changes. If the USER button is pressed for 1 second, then all the
//! LEDS flash 3 times.
//!

#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]

use defmt::*;
use embassy_executor::Spawner;
use embassy_stm32::exti::ExtiInput;
use embassy_stm32::gpio::{AnyPin, Input, Level, Output, Pin, Pull, Speed};
use embassy_stm32::peripherals::PA0;
use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex;
use embassy_sync::channel::Channel;
use embassy_time::{with_timeout, Duration, Timer};
use {defmt_rtt as _, panic_probe as _};

struct Leds<'a> {
    leds: [Output<'a, AnyPin>; 8],
    direction: i8,
    current_led: usize,
}

impl<'a> Leds<'a> {
    fn new(pins: [Output<'a, AnyPin>; 8]) -> Self {
        Self {
            leds: pins,
            direction: 1,
            current_led: 0,
        }
    }

    fn change_direction(&mut self) {
        self.direction *= -1;
    }

    fn move_next(&mut self) {
        if self.direction > 0 {
            self.current_led = (self.current_led + 1) & 7;
        } else {
            self.current_led = (8 + self.current_led - 1) & 7;
        }
    }

    async fn show(&mut self) {
        self.leds[self.current_led].set_high();
        if let Ok(new_message) = with_timeout(Duration::from_millis(500), CHANNEL.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), CHANNEL.recv()).await {
                self.process_event(new_message).await;
            }
        }
    }

    async fn flash(&mut self) {
        for _ in 0..3 {
            for led in &mut self.leds {
                led.set_high();
            }
            Timer::after(Duration::from_millis(500)).await;
            for led in &mut self.leds {
                led.set_low();
            }
            Timer::after(Duration::from_millis(200)).await;
        }
    }

    async fn process_event(&mut self, event: ButtonEvent) {
        match event {
            ButtonEvent::SingleClick => {
                self.move_next();
            }
            ButtonEvent::DoubleClick => {
                self.change_direction();
                self.move_next();
            }
            ButtonEvent::Hold => {
                self.flash().await;
            }
        }
    }
}

#[derive(Format)]
enum ButtonEvent {
    SingleClick,
    DoubleClick,
    Hold,
}

static CHANNEL: Channel<ThreadModeRawMutex, ButtonEvent, 4> = Channel::new();

#[embassy_executor::main]
async fn main(spawner: Spawner) {
    let p = embassy_stm32::init(Default::default());
    let button = Input::new(p.PA0, Pull::Down);
    let button = ExtiInput::new(button, p.EXTI0);
    info!("Press the USER button...");
    let leds = [
        Output::new(p.PE9.degrade(), Level::Low, Speed::Low),
        Output::new(p.PE10.degrade(), Level::Low, Speed::Low),
        Output::new(p.PE11.degrade(), Level::Low, Speed::Low),
        Output::new(p.PE12.degrade(), Level::Low, Speed::Low),
        Output::new(p.PE13.degrade(), Level::Low, Speed::Low),
        Output::new(p.PE14.degrade(), Level::Low, Speed::Low),
        Output::new(p.PE15.degrade(), Level::Low, Speed::Low),
        Output::new(p.PE8.degrade(), Level::Low, Speed::Low),
    ];
    let leds = Leds::new(leds);

    spawner.spawn(button_waiter(button)).unwrap();
    spawner.spawn(led_blinker(leds)).unwrap();
}

#[embassy_executor::task]
async fn led_blinker(mut leds: Leds<'static>) {
    loop {
        leds.show().await;
    }
}

#[embassy_executor::task]
async fn button_waiter(mut button: ExtiInput<'static, PA0>) {
    const DOUBLE_CLICK_DELAY: u64 = 250;
    const HOLD_DELAY: u64 = 1000;

    button.wait_for_rising_edge().await;
    loop {
        if with_timeout(Duration::from_millis(HOLD_DELAY), button.wait_for_falling_edge())
            .await
            .is_err()
        {
            info!("Hold");
            CHANNEL.send(ButtonEvent::Hold).await;
            button.wait_for_falling_edge().await;
        } else if with_timeout(Duration::from_millis(DOUBLE_CLICK_DELAY), button.wait_for_rising_edge())
            .await
            .is_err()
        {
            info!("Single click");
            CHANNEL.send(ButtonEvent::SingleClick).await;
        } else {
            info!("Double click");
            CHANNEL.send(ButtonEvent::DoubleClick).await;
            button.wait_for_falling_edge().await;
        }
        button.wait_for_rising_edge().await;
    }
}