1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
|
//! Quadrature decoder (QDEC) driver.
#![macro_use]
use core::future::poll_fn;
use core::marker::PhantomData;
use core::task::Poll;
use embassy_hal_internal::{Peri, PeripheralType};
use embassy_sync::waitqueue::AtomicWaker;
use crate::gpio::{AnyPin, Pin as GpioPin, SealedPin as _};
use crate::interrupt::typelevel::Interrupt;
use crate::pac::gpio::vals as gpiovals;
use crate::pac::qdec::vals;
use crate::{interrupt, pac};
/// Quadrature decoder driver.
pub struct Qdec<'d> {
r: pac::qdec::Qdec,
state: &'static State,
_phantom: PhantomData<&'d ()>,
}
/// QDEC config
#[non_exhaustive]
pub struct Config {
/// Number of samples
pub num_samples: NumSamples,
/// Sample period
pub period: SamplePeriod,
/// Set LED output pin polarity
pub led_polarity: LedPolarity,
/// Enable/disable input debounce filters
pub debounce: bool,
/// Time period the LED is switched ON prior to sampling (0..511 us).
pub led_pre_usecs: u16,
}
impl Default for Config {
fn default() -> Self {
Self {
num_samples: NumSamples::_1smpl,
period: SamplePeriod::_256us,
led_polarity: LedPolarity::ActiveHigh,
debounce: true,
led_pre_usecs: 0,
}
}
}
/// Interrupt handler.
pub struct InterruptHandler<T: Instance> {
_phantom: PhantomData<T>,
}
impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
unsafe fn on_interrupt() {
T::regs().intenclr().write(|w| w.set_reportrdy(true));
T::state().waker.wake();
}
}
impl<'d> Qdec<'d> {
/// Create a new QDEC.
pub fn new<T: Instance>(
qdec: Peri<'d, T>,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
a: Peri<'d, impl GpioPin>,
b: Peri<'d, impl GpioPin>,
config: Config,
) -> Self {
Self::new_inner(qdec, a.into(), b.into(), None, config)
}
/// Create a new QDEC, with a pin for LED output.
pub fn new_with_led<T: Instance>(
qdec: Peri<'d, T>,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
a: Peri<'d, impl GpioPin>,
b: Peri<'d, impl GpioPin>,
led: Peri<'d, impl GpioPin>,
config: Config,
) -> Self {
Self::new_inner(qdec, a.into(), b.into(), Some(led.into()), config)
}
fn new_inner<T: Instance>(
_p: Peri<'d, T>,
a: Peri<'d, AnyPin>,
b: Peri<'d, AnyPin>,
led: Option<Peri<'d, AnyPin>>,
config: Config,
) -> Self {
let r = T::regs();
// Select pins.
a.conf().write(|w| {
w.set_input(gpiovals::Input::CONNECT);
w.set_pull(gpiovals::Pull::PULLUP);
});
b.conf().write(|w| {
w.set_input(gpiovals::Input::CONNECT);
w.set_pull(gpiovals::Pull::PULLUP);
});
r.psel().a().write_value(a.psel_bits());
r.psel().b().write_value(b.psel_bits());
if let Some(led_pin) = &led {
led_pin.conf().write(|w| w.set_dir(gpiovals::Dir::OUTPUT));
r.psel().led().write_value(led_pin.psel_bits());
}
// Enables/disable input debounce filters
r.dbfen().write(|w| match config.debounce {
true => w.set_dbfen(true),
false => w.set_dbfen(false),
});
// Set LED output pin polarity
r.ledpol().write(|w| match config.led_polarity {
LedPolarity::ActiveHigh => w.set_ledpol(vals::Ledpol::ACTIVE_HIGH),
LedPolarity::ActiveLow => w.set_ledpol(vals::Ledpol::ACTIVE_LOW),
});
// Set time period the LED is switched ON prior to sampling (0..511 us).
r.ledpre().write(|w| w.set_ledpre(config.led_pre_usecs.min(511)));
// Set sample period
r.sampleper().write(|w| match config.period {
SamplePeriod::_128us => w.set_sampleper(vals::Sampleper::_128US),
SamplePeriod::_256us => w.set_sampleper(vals::Sampleper::_256US),
SamplePeriod::_512us => w.set_sampleper(vals::Sampleper::_512US),
SamplePeriod::_1024us => w.set_sampleper(vals::Sampleper::_1024US),
SamplePeriod::_2048us => w.set_sampleper(vals::Sampleper::_2048US),
SamplePeriod::_4096us => w.set_sampleper(vals::Sampleper::_4096US),
SamplePeriod::_8192us => w.set_sampleper(vals::Sampleper::_8192US),
SamplePeriod::_16384us => w.set_sampleper(vals::Sampleper::_16384US),
SamplePeriod::_32ms => w.set_sampleper(vals::Sampleper::_32MS),
SamplePeriod::_65ms => w.set_sampleper(vals::Sampleper::_65MS),
SamplePeriod::_131ms => w.set_sampleper(vals::Sampleper::_131MS),
});
T::Interrupt::unpend();
unsafe { T::Interrupt::enable() };
// Enable peripheral
r.enable().write(|w| w.set_enable(true));
// Start sampling
r.tasks_start().write_value(1);
Self {
r: T::regs(),
state: T::state(),
_phantom: PhantomData,
}
}
/// Perform an asynchronous read of the decoder.
/// The returned future can be awaited to obtain the number of steps.
///
/// If the future is dropped, the read is cancelled.
///
/// # Example
///
/// ```no_run
/// use embassy_nrf::qdec::{self, Qdec};
/// use embassy_nrf::{bind_interrupts, peripherals};
///
/// bind_interrupts!(struct Irqs {
/// QDEC => qdec::InterruptHandler<peripherals::QDEC>;
/// });
///
/// # async {
/// # let p: embassy_nrf::Peripherals = todo!();
/// let config = qdec::Config::default();
/// let mut q = Qdec::new(p.QDEC, Irqs, p.P0_31, p.P0_30, config);
/// let delta = q.read().await;
/// # };
/// ```
pub async fn read(&mut self) -> i16 {
self.r.intenset().write(|w| w.set_reportrdy(true));
self.r.tasks_readclracc().write_value(1);
let state = self.state;
let r = self.r;
poll_fn(move |cx| {
state.waker.register(cx.waker());
if r.events_reportrdy().read() == 0 {
Poll::Pending
} else {
r.events_reportrdy().write_value(0);
let acc = r.accread().read();
Poll::Ready(acc as i16)
}
})
.await
}
}
/// Sample period
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum SamplePeriod {
/// 128 us
_128us,
/// 256 us
_256us,
/// 512 us
_512us,
/// 1024 us
_1024us,
/// 2048 us
_2048us,
/// 4096 us
_4096us,
/// 8192 us
_8192us,
/// 16384 us
_16384us,
/// 32 ms
_32ms,
/// 65 ms
_65ms,
/// 131 ms
_131ms,
}
/// Number of samples taken.
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum NumSamples {
/// 10 samples
_10smpl,
/// 40 samples
_40smpl,
/// 80 samples
_80smpl,
/// 120 samples
_120smpl,
/// 160 samples
_160smpl,
/// 200 samples
_200smpl,
/// 240 samples
_240smpl,
/// 280 samples
_280smpl,
/// 1 sample
_1smpl,
}
/// LED polarity
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum LedPolarity {
/// Active high (a high output turns on the LED).
ActiveHigh,
/// Active low (a low output turns on the LED).
ActiveLow,
}
/// Peripheral static state
pub(crate) struct State {
waker: AtomicWaker,
}
impl State {
pub(crate) const fn new() -> Self {
Self {
waker: AtomicWaker::new(),
}
}
}
pub(crate) trait SealedInstance {
fn regs() -> pac::qdec::Qdec;
fn state() -> &'static State;
}
/// qdec peripheral instance.
#[allow(private_bounds)]
pub trait Instance: SealedInstance + PeripheralType + 'static + Send {
/// Interrupt for this peripheral.
type Interrupt: interrupt::typelevel::Interrupt;
}
macro_rules! impl_qdec {
($type:ident, $pac_type:ident, $irq:ident) => {
impl crate::qdec::SealedInstance for peripherals::$type {
fn regs() -> pac::qdec::Qdec {
pac::$pac_type
}
fn state() -> &'static crate::qdec::State {
static STATE: crate::qdec::State = crate::qdec::State::new();
&STATE
}
}
impl crate::qdec::Instance for peripherals::$type {
type Interrupt = crate::interrupt::typelevel::$irq;
}
};
}
|