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
//! Delays

use cast::u32;
use nrf51::TIMER0;

use hal::blocking::delay::{DelayMs, DelayUs};

/// System timer `TIMER0` as a delay provider
pub struct Delay {
    timer: TIMER0,
}

impl Delay {
    /// Configures the TIMER0 as a delay provider
    pub fn new(timer: TIMER0) -> Self {
        timer.tasks_stop.write(|w| unsafe { w.bits(1) });

        // Set counter to 24bit mode
        timer.bitmode.write(|w| unsafe { w.bits(2) });

        // Set prescaler to 4 == 1MHz timer
        timer.prescaler.write(|w| unsafe { w.bits(4) });

        Delay { timer }
    }

    pub fn free(self) -> TIMER0 {
        self.timer
    }
}

impl DelayMs<u32> for Delay {
    fn delay_ms(&mut self, ms: u32) {
        self.delay_us(ms * 1_000);
    }
}

impl DelayMs<u16> for Delay {
    fn delay_ms(&mut self, ms: u16) {
        self.delay_ms(u32(ms));
    }
}

impl DelayMs<u8> for Delay {
    fn delay_ms(&mut self, ms: u8) {
        self.delay_ms(u32(ms));
    }
}

impl DelayUs<u32> for Delay {
    fn delay_us(&mut self, us: u32) {
        /* Clear event in case it was used before */
        self.timer.events_compare[0].write(|w| unsafe { w.bits(0) });

        /* Program counter compare register with value */
        self.timer.cc[0].write(|w| unsafe { w.bits(us) });

        /* Clear current counter value */
        self.timer.tasks_clear.write(|w| unsafe { w.bits(1) });

        /* Start counting */
        self.timer.tasks_start.write(|w| unsafe { w.bits(1) });

        /* Busy wait for event to happen */
        while self.timer.events_compare[0].read().bits() == 0 {}

        /* Stop counting */
        self.timer.tasks_stop.write(|w| unsafe { w.bits(1) });
    }
}

impl DelayUs<u16> for Delay {
    fn delay_us(&mut self, us: u16) {
        self.delay_us(u32(us))
    }
}

impl DelayUs<u8> for Delay {
    fn delay_us(&mut self, us: u8) {
        self.delay_us(u32(us))
    }
}