Skip to content
This repository was archived by the owner on May 15, 2021. It is now read-only.

Commit 3fb5068

Browse files
committed
Add non-blocking timer module
1 parent 2c66dbc commit 3fb5068

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#![feature(const_fn)]
66
#![allow(non_camel_case_types)]
77
#![feature(never_type)]
8+
#![feature(duration_extras)]
89

910
extern crate bare_metal;
1011
extern crate cast;
@@ -19,3 +20,4 @@ pub mod i2c;
1920
pub mod prelude;
2021
pub mod serial;
2122
pub mod rng;
23+
pub mod timer;

src/timer.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
use core::time::Duration;
2+
use core::u32;
3+
4+
use nb::{Result, Error};
5+
use hal::timer::{CountDown, Periodic};
6+
use nrf51::TIMER0;
7+
8+
pub struct Timer(TIMER0);
9+
10+
impl Timer {
11+
pub fn new(timer: TIMER0) -> Timer {
12+
// 32bits @ 1MHz == max delay of ~1 hour 11 minutes
13+
timer.bitmode.write(|w| w.bitmode()._32bit());
14+
timer.prescaler.write(|w| unsafe { w.prescaler().bits(4) });
15+
timer.intenset.write(|w| w.compare0().set());
16+
timer.shorts.write(|w| w.compare0_clear().enabled());
17+
18+
Timer(timer)
19+
}
20+
}
21+
22+
impl CountDown for Timer {
23+
type Time = Duration;
24+
25+
fn start<T>(&mut self, count: T) where T: Into<Self::Time> {
26+
let duration = count.into();
27+
debug_assert!(duration.as_secs() < ((u32::MAX as u64 - duration.subsec_micros) / 1_000_000));
28+
29+
let us = (duration.as_secs() as u32) * 1_000_000 + duration.subsec_micros();
30+
self.0.cc[0].write(|w| unsafe { w.bits(us) });
31+
32+
self.0.events_compare[0].reset();
33+
self.0.tasks_clear.write(|w| unsafe { w.bits(1) });
34+
self.0.tasks_start.write(|w| unsafe { w.bits(1) });
35+
}
36+
37+
fn wait(&mut self) -> Result<(), !> {
38+
if self.0.events_compare[0].read().bits() == 1 {
39+
self.0.events_compare[0].reset();
40+
Ok(())
41+
} else {
42+
Err(Error::WouldBlock)
43+
}
44+
}
45+
}
46+
47+
impl Periodic for Timer {
48+
}

0 commit comments

Comments
 (0)