ws_oled_driver/
joystick.rs

1use anyhow::Result;
2use rppal::gpio::{Gpio, InputPin, Level};
3
4const KEY_UP_PIN: u8 = 6;
5const KEY_DOWN_PIN: u8 = 19;
6const KEY_LEFT_PIN: u8 = 5;
7const KEY_RIGHT_PIN: u8 = 26;
8const KEY_PRESS_PIN: u8 = 13;
9
10/// # Joystick
11/// the Joystick struct is a controller for the Joystick on the Device. It has 4 private fields to
12/// store the interface pins. These fields are used internally and do not offer direct access.
13pub struct Joystick {
14    up_pin: InputPin,
15    down_pin: InputPin,
16    left_pin: InputPin,
17    right_pin: InputPin,
18    click_pin: InputPin,
19}
20
21/// # Joystick State
22/// The State enum is used to represent the state of the Joystick. Which is one of:
23/// - Up  // When the joystick is pushed up
24/// - Down // when the joystick is pulled down
25/// - Left // when the joystick is pushed left
26/// - Right // when the joystick is pushed right
27/// - Click // when the joystick is clicked.
28#[derive(Debug)]
29pub enum State {
30    Up,
31    Down,
32    Left,
33    Right,
34    Click,
35}
36
37impl Joystick {
38    pub fn new() -> Result<Self> {
39        let gpio_controller = Gpio::new()?;
40        let up_pin = gpio_controller.get(KEY_UP_PIN)?.into_input_pullup();
41        let down_pin = gpio_controller.get(KEY_DOWN_PIN)?.into_input_pullup();
42        let left_pin = gpio_controller.get(KEY_LEFT_PIN)?.into_input_pullup();
43        let right_pin = gpio_controller.get(KEY_RIGHT_PIN)?.into_input_pullup();
44        let click_pin = gpio_controller.get(KEY_PRESS_PIN)?.into_input_pullup();
45
46        Ok(Self {
47            up_pin,
48            down_pin,
49            left_pin,
50            right_pin,
51            click_pin,
52        })
53    }
54
55    /// Returns `Option<State>`. When no reportable state is detected, it returns None.
56    pub fn read(&self) -> Option<State> {
57        if self.up_pin.read() == Level::Low { return Some(State::Up) }
58        if self.down_pin.read() == Level::Low { return Some(State::Down) }
59        if self.left_pin.read() == Level::Low { return Some(State::Left) }
60        if self.right_pin.read() == Level::Low { return Some(State::Right) }
61        if self.click_pin.read() == Level::Low { return Some(State::Click) }
62
63        None
64    }
65}