driver_pal/hal/
cp2130.rs

1use std::convert::{TryFrom, TryInto};
2
3use driver_cp2130::prelude::*;
4
5use super::{
6    HalBase, HalError, HalInputPin, HalInst, HalOutputPin, HalPins, HalSpi, PinConfig, SpiConfig,
7};
8use crate::*;
9
10/// Convert a generic SPI config object into a CP2130 object
11impl TryFrom<super::SpiConfig> for driver_cp2130::SpiConfig {
12    type Error = HalError;
13
14    fn try_from(c: super::SpiConfig) -> Result<driver_cp2130::SpiConfig, Self::Error> {
15        Ok(driver_cp2130::SpiConfig {
16            clock: SpiClock::try_from(c.baud as usize)?,
17            ..driver_cp2130::SpiConfig::default()
18        })
19    }
20}
21
22/// CP2130 `Hal` implementation
23pub struct Cp2130Driver;
24
25impl Cp2130Driver {
26    /// Load base CP2130 instance
27    pub fn new(
28        index: usize,
29        spi_config: &SpiConfig,
30        pins: &PinConfig,
31    ) -> Result<HalInst, HalError> {
32        // Fetch the matching device and descriptor
33        let (device, descriptor) = Manager::device(Filter::default(), index)?;
34
35        // Create CP2130 object
36        let cp2130 = Cp2130::new(device, descriptor, UsbOptions::default())?;
37
38        // Connect SPI
39        let spi = cp2130.spi(0, spi_config.clone().try_into()?, Some(pins.chip_select as u8))?;
40
41        // Connect pins
42
43        let reset = cp2130.gpio_out(pins.reset as u8, GpioMode::PushPull, GpioLevel::High)?;
44
45        let busy = match pins.busy {
46            Some(p) => HalInputPin::Cp2130(cp2130.gpio_in(p as u8)?),
47            None => HalInputPin::None,
48        };
49
50        let ready = match pins.ready {
51            Some(p) => HalInputPin::Cp2130(cp2130.gpio_in(p as u8)?),
52            None => HalInputPin::None,
53        };
54
55        let led0 = match pins.led0 {
56            Some(p) => HalOutputPin::Cp2130(cp2130.gpio_out(
57                p as u8,
58                GpioMode::PushPull,
59                GpioLevel::Low,
60            )?),
61            None => HalOutputPin::None,
62        };
63
64        let led1 = match pins.led1 {
65            Some(p) => HalOutputPin::Cp2130(cp2130.gpio_out(
66                p as u8,
67                GpioMode::PushPull,
68                GpioLevel::Low,
69            )?),
70            None => HalOutputPin::None,
71        };
72
73        let pins = HalPins {
74            reset: HalOutputPin::Cp2130(reset),
75            busy,
76            ready,
77            led0,
78            led1,
79        };
80
81        // Return object
82        Ok(HalInst {
83            base: HalBase::Cp2130(cp2130),
84            spi: HalSpi::Cp2130(spi),
85            pins,
86        })
87    }
88}