|
3 | 3 | // TODO: on the h7x3 at least, only TIM2, TIM3, TIM4, TIM5 can support 32 bits.
|
4 | 4 | // TIM1 is 16 bit.
|
5 | 5 |
|
| 6 | +use core::convert::TryFrom; |
6 | 7 | use core::marker::PhantomData;
|
7 | 8 |
|
8 | 9 | use crate::hal::timer::{CountDown, Periodic};
|
@@ -227,6 +228,43 @@ macro_rules! hal {
|
227 | 228 | let frequency = self.timeout.0;
|
228 | 229 | let ticks = clk / frequency;
|
229 | 230 |
|
| 231 | + self.set_timeout_ticks(ticks); |
| 232 | + } |
| 233 | + |
| 234 | + /// Sets the timer period from a time duration |
| 235 | + /// |
| 236 | + /// ``` |
| 237 | + /// // Set timeout to 100ms |
| 238 | + /// timer.set_timeout(100.ms()); |
| 239 | + /// ``` |
| 240 | + /// |
| 241 | + /// Alternatively, the duration can be set using the |
| 242 | + /// core::time::Duration type |
| 243 | + /// |
| 244 | + /// ``` |
| 245 | + /// let duration = core::time::Duration::from_nanos(2_500); |
| 246 | + /// |
| 247 | + /// // Set timeout to 2.5µs |
| 248 | + /// timer.set_timeout(duration); |
| 249 | + /// ``` |
| 250 | + pub fn set_timeout<T>(&mut self, timeout: T) |
| 251 | + where |
| 252 | + T: Into<core::time::Duration> |
| 253 | + { |
| 254 | + const NANOS_PER_SECOND: u64 = 1_000_000_000; |
| 255 | + let timeout = timeout.into(); |
| 256 | + |
| 257 | + let clk = self.clk as u64; |
| 258 | + let ticks = u32::try_from( |
| 259 | + clk * timeout.as_secs() + |
| 260 | + clk * u64::from(timeout.subsec_nanos()) / NANOS_PER_SECOND, |
| 261 | + ) |
| 262 | + .unwrap_or(u32::max_value()); |
| 263 | + |
| 264 | + self.set_timeout_ticks(ticks.max(1)); |
| 265 | + } |
| 266 | + |
| 267 | + fn set_timeout_ticks(&mut self, ticks: u32) { |
230 | 268 | let psc = u16((ticks - 1) / (1 << 16)).unwrap();
|
231 | 269 | self.tim.psc.write(|w| { w.psc().bits(psc) });
|
232 | 270 |
|
|
0 commit comments