Skip to main content

device_envoy/led4/
output_array.rs

1use crate::Result;
2use crate::error::Error::IndexOutOfBounds;
3use core::num::NonZeroU8;
4use embassy_rp::gpio::{self, Level};
5
6/// Array of GPIO output pins for LED displays.
7///
8/// See the [`Led4`](crate::led4::Led4) documentation for usage examples.
9pub struct OutputArray<'a, const N: usize>([gpio::Output<'a>; N]);
10
11impl<'a, const N: usize> OutputArray<'a, N> {
12    /// Creates a new output array from GPIO pins.
13    pub const fn new(outputs: [gpio::Output<'a>; N]) -> Self {
14        Self(outputs)
15    }
16
17    #[inline]
18    pub(crate) fn set_levels_at_indexes(&mut self, indexes: &[u8], level: Level) -> Result<()> {
19        for &index in indexes {
20            self.set_level_at_index(index, level)?;
21        }
22        Ok(())
23    }
24
25    #[inline]
26    pub(crate) fn set_level_at_index(&mut self, index: u8, level: Level) -> Result<()> {
27        self.get_mut(index as usize)
28            .ok_or(IndexOutOfBounds)?
29            .set_level(level);
30        Ok(())
31    }
32
33    #[inline]
34    pub(crate) fn get_mut(&mut self, index: usize) -> Option<&mut gpio::Output<'a>> {
35        self.0.get_mut(index)
36    }
37}
38
39impl OutputArray<'_, { u8::BITS as usize }> {
40    #[expect(clippy::shadow_reuse, reason = "Converting NonZeroU8 to u8")]
41    #[inline]
42    pub(crate) fn set_from_nonzero_bits(&mut self, bits: NonZeroU8) {
43        let mut bits = bits.get();
44        for output in &mut self.0 {
45            let level: Level = ((bits & 1) == 1).into();
46            output.set_level(level);
47            bits >>= 1;
48        }
49    }
50}