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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! HAL interface to the TIMER peripheral.
//!
//! See product specification, chapter 24.
#[cfg(any(feature = "9160", feature = "5340-app", feature = "5340-net"))]
use crate::pac::{
timer0_ns::{
RegisterBlock as RegBlock0, EVENTS_COMPARE, TASKS_CAPTURE, TASKS_CLEAR, TASKS_COUNT,
TASKS_START, TASKS_STOP,
},
Interrupt, TIMER0_NS as TIMER0, TIMER1_NS as TIMER1, TIMER2_NS as TIMER2,
};
#[cfg(not(any(feature = "9160", feature = "5340-app", feature = "5340-net")))]
use crate::pac::{
timer0::{
RegisterBlock as RegBlock0, EVENTS_COMPARE, TASKS_CAPTURE, TASKS_CLEAR, TASKS_COUNT,
TASKS_START, TASKS_STOP,
},
Interrupt, TIMER0, TIMER1, TIMER2,
};
#[cfg(feature = "embedded-hal-02")]
use cast::u32;
use embedded_hal::delay::DelayNs;
#[cfg(any(feature = "52832", feature = "52833", feature = "52840"))]
use crate::pac::{TIMER3, TIMER4};
// The 832 and 840 expose TIMER3 and TIMER for as timer3::RegisterBlock...
#[cfg(any(feature = "52832", feature = "52840"))]
use crate::pac::timer3::{
RegisterBlock as RegBlock3, EVENTS_COMPARE as EventsCompare3, TASKS_CAPTURE as TasksCapture3,
};
// ...but the 833 exposes them as timer0::RegisterBlock. This might be a bug
// in the PAC, and could be fixed later. For now, it is equivalent anyway.
#[cfg(feature = "52833")]
use crate::pac::timer0::{
RegisterBlock as RegBlock3, EVENTS_COMPARE as EventsCompare3, TASKS_CAPTURE as TasksCapture3,
};
use core::{hint::spin_loop, marker::PhantomData};
pub struct OneShot;
pub struct Periodic;
/// Interface to a TIMER instance.
///
/// Right now, this is a very basic interface. The timer will always be
/// hardcoded to a frequency of 1 MHz and 32 bits accuracy.
///
/// CC\[0\] is used for the current/most-recent delay period and CC\[1\] is used
/// to grab the current value of the counter at a given instant.
pub struct Timer<T, U = OneShot>(T, PhantomData<U>);
impl<T> Timer<T, OneShot>
where
T: Instance,
{
pub fn one_shot(timer: T) -> Timer<T, OneShot> {
timer.set_oneshot();
Timer::<T, OneShot>(timer, PhantomData)
}
pub fn new(timer: T) -> Timer<T, OneShot> {
Timer::<T, OneShot>::one_shot(timer)
}
}
impl<T> Timer<T, Periodic>
where
T: Instance,
{
pub fn periodic(timer: T) -> Timer<T, Periodic> {
timer.set_periodic();
Timer::<T, Periodic>(timer, PhantomData)
}
}
impl<T, U> Timer<T, U>
where
T: Instance,
{
pub const TICKS_PER_SECOND: u32 = 1_000_000;
pub fn into_periodic(self) -> Timer<T, Periodic> {
self.0.set_shorts_periodic();
Timer::<T, Periodic>(self.free(), PhantomData)
}
pub fn into_oneshot(self) -> Timer<T, OneShot> {
self.0.set_shorts_oneshot();
Timer::<T, OneShot>(self.free(), PhantomData)
}
/// Return the raw interface to the underlying timer peripheral.
pub fn free(self) -> T {
self.0
}
/// Return the current value of the counter, by capturing to CC\[1\].
pub fn read(&self) -> u32 {
self.0.read_counter()
}
/// Reset the interrupt event flag
pub fn reset_event(&self) {
self.0.timer_reset_event()
}
/// Enables the interrupt for this timer.
///
/// Enables an interrupt that is fired when the timer reaches the value that
/// is given as an argument to `start`.
///
/// Note that the interrupt also has to be unmasked in the NVIC, or the
/// handler won't get called.
pub fn enable_interrupt(&mut self) {
// As of this writing, the timer code only uses
// `cc[0]`/`events_compare[0]`. If the code is extended to use other
// compare registers, the following needs to be adapted.
self.0.enable_interrupt();
}
/// Disables the interrupt for this timer.
///
/// Disables an interrupt that is fired when the timer reaches the value
/// that is given as an argument to `start`.
///
/// Note that the interrupt also has to be unmasked in the NVIC, or the
/// handler won't get called.
pub fn disable_interrupt(&mut self) {
// As of this writing, the timer code only uses
// `cc[0]`/`events_compare[0]`. If the code is extended to use other
// compare registers, the following needs to be adapted.
self.0.disable_interrupt();
}
/// Starts the timer.
///
/// The timer will run for the given number of cycles, then it will stop and
/// reset.
pub fn start(&mut self, cycles: u32) {
self.0.timer_start(cycles)
}
/// If the timer has finished, resets it and returns true.
///
/// Returns false if the timer is still running.
pub fn reset_if_finished(&mut self) -> bool {
if self.0.timer_running() {
// EVENTS_COMPARE has not been triggered yet
return false;
}
self.0.timer_reset_event();
true
}
/// Starts the timer for the given number of cycles and waits for it to
/// finish.
pub fn delay(&mut self, cycles: u32) {
self.start(cycles);
while !self.reset_if_finished() {
spin_loop();
}
}
/// Returns reference to the `START` task endpoint for PPI.
/// Starts timer.
#[inline(always)]
pub fn task_start(&self) -> &TASKS_START {
&self.0.as_timer0().tasks_start
}
/// Returns reference to the `STOP` task endpoint for PPI.
/// Stops timer.
#[inline(always)]
pub fn task_stop(&self) -> &TASKS_STOP {
&self.0.as_timer0().tasks_stop
}
/// Returns reference to the `COUNT` task endpoint for PPI.
/// Increments timer (counter mode only).
#[inline(always)]
pub fn task_count(&self) -> &TASKS_COUNT {
&self.0.as_timer0().tasks_count
}
/// Returns reference to the `CLEAR` task endpoint for PPI.
/// Clears timer.
#[inline(always)]
pub fn task_clear(&self) -> &TASKS_CLEAR {
&self.0.as_timer0().tasks_clear
}
/// Returns reference to the CC\[0\] `CAPTURE` task endpoint for PPI.
/// Captures timer value to the CC\[0\] register.
#[inline(always)]
pub fn task_capture_cc0(&self) -> &TASKS_CAPTURE {
&self.0.as_timer0().tasks_capture[0]
}
/// Returns reference to the CC\[1\] `CAPTURE` task endpoint for PPI.
/// Captures timer value to the CC\[1\] register.
#[inline(always)]
pub fn task_capture_cc1(&self) -> &TASKS_CAPTURE {
&self.0.as_timer0().tasks_capture[1]
}
/// Returns reference to the CC\[2\] `CAPTURE` task endpoint for PPI.
/// Captures timer value to the CC\[2\] register.
#[inline(always)]
pub fn task_capture_cc2(&self) -> &TASKS_CAPTURE {
&self.0.as_timer0().tasks_capture[2]
}
/// Returns reference to the CC\[3\] `CAPTURE` task endpoint for PPI.
/// Captures timer value to the CC\[3\] register.
#[inline(always)]
pub fn task_capture_cc3(&self) -> &TASKS_CAPTURE {
&self.0.as_timer0().tasks_capture[3]
}
/// Returns reference to the CC\[0\] `COMPARE` event endpoint for PPI.
/// Generated when the counter is incremented and then matches the value
/// specified in the CC\[0\] register.
#[inline(always)]
pub fn event_compare_cc0(&self) -> &EVENTS_COMPARE {
&self.0.as_timer0().events_compare[0]
}
/// Returns reference to the CC\[1\] `COMPARE` event endpoint for PPI.
/// Generated when the counter is incremented and then matches the value
/// specified in the CC\[1\] register.
#[inline(always)]
pub fn event_compare_cc1(&self) -> &EVENTS_COMPARE {
&self.0.as_timer0().events_compare[1]
}
/// Returns reference to the CC\[2\] `COMPARE` event endpoint for PPI.
/// Generated when the counter is incremented and then matches the value
/// specified in the CC\[2\] register.
#[inline(always)]
pub fn event_compare_cc2(&self) -> &EVENTS_COMPARE {
&self.0.as_timer0().events_compare[2]
}
/// Returns reference to the CC\[3\] `COMPARE` event endpoint for PPI.
/// Generated when the counter is incremented and then matches the value
/// specified in the CC\[3\] register.
#[inline(always)]
pub fn event_compare_cc3(&self) -> &EVENTS_COMPARE {
&self.0.as_timer0().events_compare[3]
}
}
#[cfg(feature = "embedded-hal-02")]
impl<T, U> embedded_hal_02::timer::CountDown for Timer<T, U>
where
T: Instance,
{
type Time = u32;
/// Start the timer.
///
/// The timer will run for the given number of cycles, then it will stop and
/// reset.
fn start<Time>(&mut self, cycles: Time)
where
Time: Into<Self::Time>,
{
self.0.timer_start(cycles);
}
/// Wait for the timer to stop.
///
/// Will return `Err(nb::Error::WouldBlock)` while the timer is still
/// running. Once the timer reached the number of cycles given in the
/// `start` method, it will return `Ok(())`.
///
/// To block until the timer has stopped, use the `block!` macro from the
/// `nb` crate. Please refer to the documentation of `nb` for other options.
fn wait(&mut self) -> nb::Result<(), void::Void> {
if self.reset_if_finished() {
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
}
#[cfg(feature = "embedded-hal-02")]
impl<T, U> embedded_hal_02::timer::Cancel for Timer<T, U>
where
T: Instance,
{
type Error = ();
fn cancel(&mut self) -> Result<(), Self::Error> {
self.0.timer_cancel();
Ok(())
}
}
#[cfg(feature = "embedded-hal-02")]
impl<T> embedded_hal_02::timer::Periodic for Timer<T, Periodic> where T: Instance {}
#[cfg(feature = "embedded-hal-02")]
impl<T, U> embedded_hal_02::blocking::delay::DelayMs<u32> for Timer<T, U>
where
T: Instance,
{
fn delay_ms(&mut self, ms: u32) {
embedded_hal_02::blocking::delay::DelayUs::delay_us(self, ms * 1_000);
}
}
#[cfg(feature = "embedded-hal-02")]
impl<T, U> embedded_hal_02::blocking::delay::DelayMs<u16> for Timer<T, U>
where
T: Instance,
{
fn delay_ms(&mut self, ms: u16) {
embedded_hal_02::blocking::delay::DelayMs::delay_ms(self, u32(ms));
}
}
#[cfg(feature = "embedded-hal-02")]
impl<T, U> embedded_hal_02::blocking::delay::DelayMs<u8> for Timer<T, U>
where
T: Instance,
{
fn delay_ms(&mut self, ms: u8) {
embedded_hal_02::blocking::delay::DelayMs::delay_ms(self, u32(ms));
}
}
#[cfg(feature = "embedded-hal-02")]
impl<T, U> embedded_hal_02::blocking::delay::DelayUs<u32> for Timer<T, U>
where
T: Instance,
{
fn delay_us(&mut self, us: u32) {
self.delay(us);
}
}
#[cfg(feature = "embedded-hal-02")]
impl<T, U> embedded_hal_02::blocking::delay::DelayUs<u16> for Timer<T, U>
where
T: Instance,
{
fn delay_us(&mut self, us: u16) {
embedded_hal_02::blocking::delay::DelayUs::delay_us(self, u32(us))
}
}
#[cfg(feature = "embedded-hal-02")]
impl<T, U> embedded_hal_02::blocking::delay::DelayUs<u8> for Timer<T, U>
where
T: Instance,
{
fn delay_us(&mut self, us: u8) {
embedded_hal_02::blocking::delay::DelayUs::delay_us(self, u32(us))
}
}
impl<T: Instance, U> DelayNs for Timer<T, U> {
fn delay_ns(&mut self, ns: u32) {
self.delay(ns / 1_000);
}
}
/// Implemented by all TIMER* instances.
pub trait Instance: sealed::Sealed {
/// The interrupt associated with this RTC instance.
const INTERRUPT: Interrupt;
/// Returns the register block for the timer instance.
fn as_timer0(&self) -> &RegBlock0;
/// Starts the timer after clearing the counter register and setting the events compare trigger
/// correctly to the numer of `cycles`.
fn timer_start<Time>(&self, cycles: Time)
where
Time: Into<u32>,
{
// If the following sequence of events occurs, the COMPARE event will be
// set here:
// 1. `start` is called.
// 2. The timer runs out but `wait` is _not_ called.
// 3. `start` is called again
//
// If that happens, then we need to reset the event here explicitly, as
// nothing else this method does will reset the event, and if it's still
// active after this method exits, then the next call to `wait` will
// return immediately, no matter how much time has actually passed.
self.timer_reset_event();
// Configure timer to trigger EVENTS_COMPARE when given number of cycles
// is reached.
#[cfg(not(feature = "51"))]
self.as_timer0().cc[0].write(|w|
// The timer mode was set to 32 bits above, so all possible values
// of `cycles` are valid.
unsafe { w.cc().bits(cycles.into()) });
#[cfg(feature = "51")]
self.as_timer0().cc[0].write(|w| unsafe { w.bits(cycles.into()) });
// Clear the counter value.
self.as_timer0().tasks_clear.write(|w| unsafe { w.bits(1) });
// Start the timer.
self.as_timer0().tasks_start.write(|w| unsafe { w.bits(1) });
}
/// Resets event for CC\[0\] register.
fn timer_reset_event(&self) {
self.as_timer0().events_compare[0].reset();
}
/// Cancels timer by setting it to stop mode and resetting the events.
fn timer_cancel(&self) {
self.as_timer0().tasks_stop.write(|w| unsafe { w.bits(1) });
self.timer_reset_event();
}
/// Checks if the timer is still running which means no event is yet generated for CC\[0\].
fn timer_running(&self) -> bool {
self.as_timer0().events_compare[0].read().bits() == 0
}
fn read_counter(&self) -> u32 {
self.as_timer0().tasks_capture[1].write(|w| unsafe { w.bits(1) });
self.as_timer0().cc[1].read().bits()
}
/// Disables interrupt for event COMPARE\[0\].
fn disable_interrupt(&self) {
self.as_timer0()
.intenclr
.modify(|_, w| w.compare0().clear());
}
/// Enables interrupt for event COMPARE\[0\].
fn enable_interrupt(&self) {
self.as_timer0().intenset.modify(|_, w| w.compare0().set());
}
/// Sets timer into periodic mode.
fn set_shorts_periodic(&self) {
self.as_timer0()
.shorts
.write(|w| w.compare0_clear().enabled().compare0_stop().disabled());
}
/// Sets timer into oneshot mode.
fn set_shorts_oneshot(&self) {
self.as_timer0()
.shorts
.write(|w| w.compare0_clear().enabled().compare0_stop().enabled());
}
/// Sets up timer for 1 MHz prescaled periods with 32 bits accuracy.
///
/// This is only safe to call when the timer is stopped.
fn set_periodic(&self) {
self.set_shorts_periodic();
self.as_timer0().prescaler.write(
|w| unsafe { w.prescaler().bits(4) }, // 1 MHz
);
self.as_timer0().bitmode.write(|w| w.bitmode()._32bit());
}
/// Sets up timer for a 1 MHz prescaled oneshot with 32 bits accuracy.
///
/// This is only safe to call when the timer is stopped.
fn set_oneshot(&self) {
self.set_shorts_oneshot();
self.as_timer0().prescaler.write(
|w| unsafe { w.prescaler().bits(4) }, // 1 MHz
);
self.as_timer0().bitmode.write(|w| w.bitmode()._32bit());
}
}
impl Instance for TIMER0 {
const INTERRUPT: Interrupt = Interrupt::TIMER0;
#[inline(always)]
fn as_timer0(&self) -> &RegBlock0 {
self
}
}
impl Instance for TIMER1 {
const INTERRUPT: Interrupt = Interrupt::TIMER1;
#[inline(always)]
fn as_timer0(&self) -> &RegBlock0 {
self
}
}
impl Instance for TIMER2 {
const INTERRUPT: Interrupt = Interrupt::TIMER2;
#[inline(always)]
fn as_timer0(&self) -> &RegBlock0 {
self
}
}
#[cfg(any(feature = "52832", feature = "52833", feature = "52840"))]
impl Instance for TIMER3 {
const INTERRUPT: Interrupt = Interrupt::TIMER3;
#[inline(always)]
fn as_timer0(&self) -> &RegBlock0 {
let rb: &RegBlock3 = self;
let rb_ptr: *const RegBlock3 = rb;
// SAFETY: TIMER0 and TIMER3 register layouts are identical, except
// that TIMER3 has 6 CC registers, while TIMER0 has 4. There is
// appropriate padding to allow other operations to work correctly
unsafe { &*rb_ptr.cast() }
}
}
#[cfg(any(feature = "52832", feature = "52833", feature = "52840"))]
impl Instance for TIMER4 {
const INTERRUPT: Interrupt = Interrupt::TIMER4;
#[inline(always)]
fn as_timer0(&self) -> &RegBlock0 {
let rb: &RegBlock3 = self;
let rb_ptr: *const RegBlock3 = rb;
// SAFETY: TIMER0 and TIMER3 register layouts are identical, except
// that TIMER3 has 6 CC registers, while TIMER0 has 4. There is
// appropriate padding to allow other operations to work correctly
unsafe { &*rb_ptr.cast() }
}
}
/// Adds task- and event PPI endpoint getters for CC\[4\] and CC\[5\] on supported instances.
#[cfg(any(feature = "52832", feature = "52833", feature = "52840"))]
pub trait ExtendedCCTimer {
fn task_capture_cc4(&self) -> &TasksCapture3;
fn task_capture_cc5(&self) -> &TasksCapture3;
fn event_compare_cc4(&self) -> &EventsCompare3;
fn event_compare_cc5(&self) -> &EventsCompare3;
}
#[cfg(any(feature = "52832", feature = "52833", feature = "52840"))]
impl ExtendedCCTimer for Timer<TIMER3> {
/// Returns reference to the CC\[4\] `CAPTURE` task endpoint for PPI.
#[inline(always)]
fn task_capture_cc4(&self) -> &TasksCapture3 {
&self.0.tasks_capture[4]
}
/// Returns reference to the CC\[5\] `CAPTURE` task endpoint for PPI.
#[inline(always)]
fn task_capture_cc5(&self) -> &TasksCapture3 {
&self.0.tasks_capture[5]
}
/// Returns reference to the CC\[4\] `COMPARE` event endpoint for PPI.
#[inline(always)]
fn event_compare_cc4(&self) -> &EventsCompare3 {
&self.0.events_compare[4]
}
/// Returns reference to the CC\[5\] `COMPARE` event endpoint for PPI.
#[inline(always)]
fn event_compare_cc5(&self) -> &EventsCompare3 {
&self.0.events_compare[5]
}
}
#[cfg(any(feature = "52832", feature = "52833", feature = "52840"))]
impl ExtendedCCTimer for Timer<TIMER4> {
/// Returns reference to the CC\[4\] `CAPTURE` task endpoint for PPI.
#[inline(always)]
fn task_capture_cc4(&self) -> &TasksCapture3 {
&self.0.tasks_capture[4]
}
/// Returns reference to the CC\[5\] `CAPTURE` task endpoint for PPI.
#[inline(always)]
fn task_capture_cc5(&self) -> &TasksCapture3 {
&self.0.tasks_capture[5]
}
/// Returns reference to the CC\[4\] `COMPARE` event endpoint for PPI.
#[inline(always)]
fn event_compare_cc4(&self) -> &EventsCompare3 {
&self.0.events_compare[4]
}
/// Returns reference to the CC\[5\] `COMPARE` event endpoint for PPI.
#[inline(always)]
fn event_compare_cc5(&self) -> &EventsCompare3 {
&self.0.events_compare[5]
}
}
mod sealed {
pub trait Sealed {}
impl Sealed for super::TIMER0 {}
impl Sealed for super::TIMER1 {}
impl Sealed for super::TIMER2 {}
#[cfg(any(feature = "52832", feature = "52833", feature = "52840"))]
impl Sealed for super::TIMER3 {}
#[cfg(any(feature = "52832", feature = "52833", feature = "52840"))]
impl Sealed for super::TIMER4 {}
}