Browse Source

Try to implement Qei

implement_qei
Evan Cameron 3 years ago
parent
commit
8c1a9c56b2
  1. 3
      Cargo.toml
  2. 52
      src/lib.rs

3
Cargo.toml

@ -1,6 +1,6 @@
[package]
name = "rotary-encoder-hal"
version = "0.2.1"
version = "0.3.0"
authors = ["Evan Cameron <cameron.evan@gmail.com>"]
edition = "2018"
description = "A simple platform agnostic rotary encoder library using embedded_hal"
@ -8,6 +8,7 @@ keywords = ["embedded-hal", "driver", "rotary", "encoder"]
categories = ["embedded", "hardware-support", "no-std"]
license = "MIT"
readme = "README.md"
repository = "github.com/leshow/rotary-encoder-hal"
[dependencies]
embedded-hal = { version = "0.2.3", features = ["unproven"] }

52
src/lib.rs

@ -1,4 +1,4 @@
#![doc(html_root_url = "https://docs.rs/rotary-encoder-hal/0.2.1")]
#![doc(html_root_url = "https://docs.rs/rotary-encoder-hal/0.3.0")]
//! # rotary-encoder-hal
//!
//! A platform agnostic rotary encoder library
@ -13,7 +13,7 @@
use either::Either;
use embedded_hal as hal;
use hal::digital::v2::InputPin;
use hal::{digital::v2::InputPin, Direction, Qei};
/// Holds current/old state and both [`InputPin`](https://docs.rs/embedded-hal/0.2.3/embedded_hal/digital/v2/trait.InputPin.html)
#[derive(Clone, Debug, Eq, PartialEq)]
@ -21,26 +21,26 @@ pub struct Rotary<A, B> {
pin_a: A,
pin_b: B,
state: u8,
count: isize,
}
/// The encoder direction is either `Clockwise`, `CounterClockwise`, or `None`
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Direction {
/// A clockwise turn
Clockwise,
/// A counterclockwise turn
CounterClockwise,
/// No change
None,
/// Takes a `u8` representing the current state of the encoder and returns a `Direction`
pub fn from_u8(s: u8) -> Option<Direction> {
match s {
0b0001 | 0b0111 | 0b1000 | 0b1110 => Some(Direction::Upcounting),
0b0010 | 0b0100 | 0b1011 | 0b1101 => Some(Direction::Downcounting),
_ => None,
}
}
impl From<u8> for Direction {
fn from(s: u8) -> Self {
match s {
0b0001 | 0b0111 | 0b1000 | 0b1110 => Direction::Clockwise,
0b0010 | 0b0100 | 0b1011 | 0b1101 => Direction::CounterClockwise,
_ => Direction::None,
}
impl<A, B> Qei for Rotary<A, B> {
type Count = isize;
fn count(&self) -> Self::Count {
self.count
}
fn direction(&self) -> Direction {
unimplemented!()
}
}
@ -56,10 +56,11 @@ where
pin_a,
pin_b,
state: 0u8,
count: 0,
}
}
/// Call `update` to evaluate the next state of the encoder, propagates errors from `InputPin` read
pub fn update(&mut self) -> Result<Direction, Either<A::Error, B::Error>> {
pub fn update(&mut self) -> Result<Option<Direction>, Either<A::Error, B::Error>> {
// use mask to get previous state value
let mut s = self.state & 0b11;
// move in the new state
@ -71,6 +72,17 @@ where
}
// move new state in
self.state = s >> 2;
Ok(s.into())
let dir = from_u8(s);
if let Some(d) = dir {
match d {
Direction::Downcounting => {
self.count = self.count.wrapping_sub(1);
}
Direction::Upcounting => {
self.count = self.count.wrapping_add(1);
}
}
}
Ok(dir)
}
}

Loading…
Cancel
Save