wasefire_board_api/gpio.rs
1// Copyright 2023 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Low-level GPIO interface.
16
17use derive_where::derive_where;
18
19use crate::{Error, Id, Support};
20
21/// GPIO event.
22#[cfg_attr(feature = "defmt", derive(defmt::Format))]
23#[derive_where(Debug, PartialEq, Eq)]
24pub struct Event<B: crate::Api + ?Sized> {
25 /// The GPIO that triggered the event.
26 pub gpio: Id<crate::Gpio<B>>,
27}
28
29impl<B: crate::Api> From<Event<B>> for crate::Event<B> {
30 fn from(event: Event<B>) -> Self {
31 crate::Event::Gpio(event)
32 }
33}
34
35/// Input GPIO configuration.
36#[derive(Debug, Copy, Clone, bytemuck::CheckedBitPattern)]
37#[repr(u8)]
38pub enum InputConfig {
39 /// Input is disabled.
40 Disabled = 0,
41
42 /// Input is floating.
43 Floating = 1,
44
45 /// Input has a pull-down resistor.
46 PullDown = 2,
47
48 /// Input has a pull-up resistor.
49 PullUp = 3,
50}
51
52/// Output GPIO configuration.
53#[derive(Debug, Copy, Clone, bytemuck::CheckedBitPattern)]
54#[repr(u8)]
55pub enum OutputConfig {
56 /// Output is disabled.
57 Disabled = 0,
58
59 /// Output can only drive low.
60 OpenDrain = 1,
61
62 /// Output can only drive high.
63 OpenSource = 2,
64
65 /// Output can drive both low and high.
66 PushPull = 3,
67}
68
69/// GPIO configuration.
70#[derive(Debug, Copy, Clone, bytemuck::CheckedBitPattern)]
71#[repr(C)]
72pub struct Config {
73 /// Input configuration.
74 pub input: InputConfig,
75
76 /// Output configuration.
77 pub output: OutputConfig,
78
79 /// Initial output value.
80 pub initial: bool,
81
82 reserved: u8,
83}
84
85/// Low-level GPIO interface.
86pub trait Api: Support<usize> + Send {
87 /// Configures a GPIO.
88 fn configure(gpio: Id<Self>, config: Config) -> Result<(), Error>;
89
90 /// Reads from a GPIO (must be configured as input).
91 fn read(gpio: Id<Self>) -> Result<bool, Error>;
92
93 /// Writes to a GPIO (must be configured as output).
94 fn write(gpio: Id<Self>, value: bool) -> Result<(), Error>;
95
96 /// Returns the last logical value written to a GPIO (must be configured as output).
97 fn last_write(gpio: Id<Self>) -> Result<bool, Error>;
98
99 /// Enables an event to be triggered on the given conditions (at least one must be true).
100 fn enable(gpio: Id<Self>, falling: bool, rising: bool) -> Result<(), Error>;
101
102 /// Disables an event from being triggered on all conditions.
103 fn disable(gpio: Id<Self>) -> Result<(), Error>;
104}