Skip to main content

conduyt/modules/
encoder.rs

1//! CONDUYT Quadrature Encoder Module — typed wrapper
2
3use crate::device::{Device, DeviceError};
4use crate::transports::Transport;
5
6/// Encoder module wrapper.
7pub struct Encoder<'a, T: Transport> {
8    device: &'a mut Device<T>,
9    module_id: u8,
10}
11
12impl<'a, T: Transport> Encoder<'a, T> {
13    pub fn new(device: &'a mut Device<T>, module_id: u8) -> Self {
14        Self { device, module_id }
15    }
16
17    /// Claim two pins for A/B inputs.
18    pub fn attach(&mut self, pin_a: u8, pin_b: u8) -> Result<(), DeviceError<T::Error>> {
19        self.device.mod_cmd(&[self.module_id, 0x01, pin_a, pin_b])?;
20        Ok(())
21    }
22
23    /// Read the accumulated tick count. Firmware echoes module id, then a LE int32.
24    pub fn read(&mut self) -> Result<i32, DeviceError<T::Error>> {
25        let resp = self.device.mod_cmd(&[self.module_id, 0x02])?;
26        if resp.len() < 5 {
27            return Err(DeviceError::WireError(crate::wire::WireError::IncompletePkt));
28        }
29        Ok(i32::from_le_bytes([resp[1], resp[2], resp[3], resp[4]]))
30    }
31
32    /// Reset the count to zero.
33    pub fn reset(&mut self) -> Result<(), DeviceError<T::Error>> {
34        self.device.mod_cmd(&[self.module_id, 0x03])?;
35        Ok(())
36    }
37}