Skip to content

Commit 730d74f

Browse files
authored
Added a Delay implementation based on cortex_m::asm::delay (#178)
Fmt Made DelayCM Clone/Copy Fixed error in calculation Made milliseconds more accurate Simplification
1 parent f16db92 commit 730d74f

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

src/delay.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
//! Delays
22
33
use cast::u32;
4+
use cortex_m::asm;
45
use cortex_m::peripheral::syst::SystClkSource;
56
use cortex_m::peripheral::SYST;
67

78
use crate::hal::blocking::delay::{DelayMs, DelayUs};
89
use crate::rcc::Clocks;
10+
use crate::time::Hertz;
911

1012
/// System timer (SysTick) as a delay provider
1113
pub struct Delay {
@@ -85,3 +87,57 @@ impl DelayUs<u8> for Delay {
8587
self.delay_us(u32(us))
8688
}
8789
}
90+
91+
/// Cortex-M `asm::delay` as provider
92+
#[derive(Clone, Copy)]
93+
pub struct DelayCM {
94+
sysclk: Hertz,
95+
}
96+
97+
impl DelayCM {
98+
/// Create a new delay
99+
pub fn new(clocks: Clocks) -> Self {
100+
DelayCM {
101+
sysclk: clocks.sysclk(),
102+
}
103+
}
104+
}
105+
106+
impl DelayMs<u32> for DelayCM {
107+
fn delay_ms(&mut self, ms: u32) {
108+
self.delay_us(ms * 1_000);
109+
}
110+
}
111+
112+
impl DelayMs<u16> for DelayCM {
113+
fn delay_ms(&mut self, ms: u16) {
114+
self.delay_ms(u32(ms));
115+
}
116+
}
117+
118+
impl DelayMs<u8> for DelayCM {
119+
fn delay_ms(&mut self, ms: u8) {
120+
self.delay_ms(u32(ms));
121+
}
122+
}
123+
124+
impl DelayUs<u32> for DelayCM {
125+
fn delay_us(&mut self, us: u32) {
126+
// Max delay is 53_687_091 us at 80 MHz
127+
let ticks = self.sysclk.0 / 1_000_000;
128+
129+
asm::delay(ticks * us);
130+
}
131+
}
132+
133+
impl DelayUs<u16> for DelayCM {
134+
fn delay_us(&mut self, us: u16) {
135+
self.delay_us(u32(us))
136+
}
137+
}
138+
139+
impl DelayUs<u8> for DelayCM {
140+
fn delay_us(&mut self, us: u8) {
141+
self.delay_us(u32(us))
142+
}
143+
}

0 commit comments

Comments
 (0)