#encoder #rotary #embedded-hal #embedded-hal-driver #driver

no-std rotary-encoder-hal

A simple platform agnostic rotary encoder library using embedded_hal

4 releases (breaking)

new 0.6.0 Feb 11, 2025
0.5.0 Jan 20, 2022
0.3.0 Dec 11, 2020
0.2.1 Oct 22, 2019
0.1.0 Oct 22, 2019

#225 in Embedded development

Download history 24/week @ 2024-12-07 13/week @ 2024-12-14 1/week @ 2024-12-21 3/week @ 2025-01-11 2/week @ 2025-01-18 7/week @ 2025-02-01 114/week @ 2025-02-08

126 downloads per month
Used in 2 crates

MIT license

12KB
116 lines

rotary-encoder-hal

Crate API

A simple, platform agnostic rotary encoder library.

An alternate decoder algorithm that is more tolerant of noise is enabled by the Cargo feature table-decoder. It follows the discussion of noisy decoding here.

You can call update from an ISR. You may get many spurious interrupts from switch bounce, though the algorithm handles them appropriately. When polling update, a poll time of about 1 ms seems to work well.

Examples

#![no_std]
#![no_main]

extern crate panic_semihosting;

use cortex_m_rt::entry;
use hal::{delay::Delay, prelude::*, stm32};
use stm32f3xx_hal as hal;

use rotary_encoder_hal::{Direction, Rotary};

#[entry]
fn main() -> ! {
    let cp = cortex_m::Peripherals::take().unwrap();
    let peripherals = stm32::Peripherals::take().unwrap();

    let mut flash = peripherals.FLASH.constrain();
    let mut rcc = peripherals.RCC.constrain();

    let clocks = rcc.cfgr.freeze(&mut flash.acr);

    let mut delay = Delay::new(cp.SYST, clocks);

    let mut gpiob = peripherals.GPIOB.split(&mut rcc.ahb);
    let pin_a = gpiob
        .pb10
        .into_pull_up_input(&mut gpiob.moder, &mut gpiob.pupdr);
    let pin_b = gpiob
        .pb11
        .into_pull_up_input(&mut gpiob.moder, &mut gpiob.pupdr);

    let mut enc = Rotary::new(pin_a, pin_b);
    let mut pos: isize = 0;

    loop {
        match enc.update().unwrap() {
            Direction::Clockwise => {
                pos += 1;
            }
            Direction::CounterClockwise => {
                pos -= 1;
            }
            Direction::None => {}
        }
    }
}

Dependencies

~87–255KB