1use core::marker::PhantomData;
8
9use crate::pac::timer::vals;
10use embassy_hal_internal::{into_ref, PeripheralRef};
11
12use super::low_level::Timer;
13use super::{Channel1Pin, Channel2Pin, GeneralInstance4Channel};
14use crate::gpio::{AfType, AnyPin, Pull};
15use crate::Peripheral;
16
17pub enum Direction {
19 Upcounting,
21 Downcounting,
23}
24
25pub enum Ch1 {}
27pub enum Ch2 {}
29
30pub struct QeiPin<'d, T, Channel> {
32 _pin: PeripheralRef<'d, AnyPin>,
33 phantom: PhantomData<(T, Channel)>,
34}
35
36macro_rules! channel_impl {
37 ($new_chx:ident, $channel:ident, $pin_trait:ident) => {
38 impl<'d, T: GeneralInstance4Channel> QeiPin<'d, T, $channel> {
39 #[doc = concat!("Create a new ", stringify!($channel), " QEI pin instance.")]
40 pub fn $new_chx(pin: impl Peripheral<P = impl $pin_trait<T>> + 'd) -> Self {
41 into_ref!(pin);
42 critical_section::with(|_| {
43 pin.set_low();
44 pin.set_as_af(pin.af_num(), AfType::input(Pull::None));
45 });
46 QeiPin {
47 _pin: pin.map_into(),
48 phantom: PhantomData,
49 }
50 }
51 }
52 };
53}
54
55channel_impl!(new_ch1, Ch1, Channel1Pin);
56channel_impl!(new_ch2, Ch2, Channel2Pin);
57
58pub struct Qei<'d, T: GeneralInstance4Channel> {
60 inner: Timer<'d, T>,
61}
62
63impl<'d, T: GeneralInstance4Channel> Qei<'d, T> {
64 pub fn new(
66 tim: impl Peripheral<P = T> + 'd,
67 _ch1: QeiPin<'d, T, Ch1>,
68 _ch2: QeiPin<'d, T, Ch2>,
69 ) -> Self {
70 Self::new_inner(tim)
71 }
72
73 fn new_inner(tim: impl Peripheral<P = T> + 'd) -> Self {
74 let inner = Timer::new(tim);
75 let r = inner.regs_gp16();
76
77 r.ccmr_input(0).modify(|w| {
79 w.set_ccs(0, vals::CcmrInputCcs::TI4);
80 w.set_ccs(1, vals::CcmrInputCcs::TI4);
81 });
82
83 r.ccer().modify(|w| {
85 w.set_cce(0, true);
86 w.set_cce(1, true);
87
88 w.set_ccp(0, false);
89 w.set_ccp(1, false);
90 });
91
92 r.smcr().modify(|w| {
93 w.set_sms(vals::Sms::ENCODER_MODE_3);
94 });
95
96 r.arr().modify(|w| w.set_arr(u16::MAX));
97 r.cr1().modify(|w| w.set_cen(true));
98
99 Self { inner }
100 }
101
102 pub fn read_direction(&self) -> Direction {
104 match self.inner.regs_gp16().cr1().read().dir() {
105 vals::Dir::DOWN => Direction::Downcounting,
106 vals::Dir::UP => Direction::Upcounting,
107 }
108 }
109
110 pub fn count(&self) -> u16 {
112 self.inner.regs_gp16().cnt().read().cnt()
113 }
114}