Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

timer Instance, rtic monotonic #388

Merged
merged 1 commit into from
Jan 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

### Added

- `Instance` for Timer's, rtic-monotonic fugit impl
- Serial can now be reconfigured, allowing to change e.g. the baud rate after initialisation.

## [v0.8.0] - 2021-12-29
Expand Down
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ bxcan = "0.6"
cast = { default-features = false, version = "0.3.0" }
void = { default-features = false, version = "1.0.2" }
embedded-hal = { features = ["unproven"], version = "0.2.6" }
fugit = "0.3.0"
rtic-monotonic = { version = "1.0", optional = true }

[dependencies.stm32-usbd]
version = "0.6.0"
Expand Down Expand Up @@ -62,6 +64,8 @@ connectivity = ["medium", "has-can"]
# Devices with CAN interface
has-can = []

rtic = ["rt", "rtic-monotonic"]

[profile.dev]
incremental = false
codegen-units = 1
Expand Down
2 changes: 1 addition & 1 deletion examples/blinky_timer_irq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ fn main() -> ! {
cortex_m::interrupt::free(|cs| *G_LED.borrow(cs).borrow_mut() = Some(led));

// Set up a timer expiring after 1s
let mut timer = Timer::tim2(dp.TIM2, &clocks).start_count_down(1.hz());
let mut timer = Timer::new(dp.TIM2, &clocks).start_count_down(1.hz());

// Generate an interrupt when the timer expires
timer.listen(Event::Update);
Expand Down
2 changes: 1 addition & 1 deletion examples/pwm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ fn main() -> ! {
// let c4 = gpiob.pb9.into_alternate_push_pull(&mut gpiob.crh);

let mut pwm =
Timer::tim2(p.TIM2, &clocks).pwm::<Tim2NoRemap, _, _, _>(pins, &mut afio.mapr, 1.khz());
Timer::new(p.TIM2, &clocks).pwm::<Tim2NoRemap, _, _, _>(pins, &mut afio.mapr, 1.khz());

// Enable clock on each of the channels
pwm.enable(Channel::C1);
Expand Down
2 changes: 1 addition & 1 deletion examples/pwm_custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ fn main() -> ! {
let p0 = pb4.into_alternate_push_pull(&mut gpiob.crl);
let p1 = gpiob.pb5.into_alternate_push_pull(&mut gpiob.crl);

let pwm = Timer::tim3(p.TIM3, &clocks).pwm((p0, p1), &mut afio.mapr, 1.khz());
let pwm = Timer::new(p.TIM3, &clocks).pwm((p0, p1), &mut afio.mapr, 1.khz());

let max = pwm.get_max_duty();

Expand Down
2 changes: 1 addition & 1 deletion examples/pwm_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn main() -> ! {
let (_pa15, _pb3, pb4) = afio.mapr.disable_jtag(gpioa.pa15, gpiob.pb3, gpiob.pb4);
let pb5 = gpiob.pb5;

let pwm_input = Timer::tim3(p.TIM3, &clocks).pwm_input(
let pwm_input = Timer::new(p.TIM3, &clocks).pwm_input(
(pb4, pb5),
&mut afio.mapr,
&mut dbg,
Expand Down
2 changes: 1 addition & 1 deletion examples/qei.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ fn main() -> ! {
let c1 = gpiob.pb6;
let c2 = gpiob.pb7;

let qei = Timer::tim4(dp.TIM4, &clocks).qei((c1, c2), &mut afio.mapr, QeiOptions::default());
let qei = Timer::new(dp.TIM4, &clocks).qei((c1, c2), &mut afio.mapr, QeiOptions::default());
let mut delay = Delay::new(cp.SYST, clocks);

loop {
Expand Down
2 changes: 1 addition & 1 deletion examples/timer-interrupt-rtic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ mod app {
.pc13
.into_push_pull_output_with_state(&mut gpioc.crh, PinState::High);
// Configure the syst timer to trigger an update every second and enables interrupt
let mut timer = Timer::tim1(cx.device.TIM1, &clocks).start_count_down(1.hz());
let mut timer = Timer::new(cx.device.TIM1, &clocks).start_count_down(1.hz());
timer.listen(Event::Update);

// Init the static resources to use them later through RTIC
Expand Down
61 changes: 42 additions & 19 deletions src/timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,17 @@ use crate::pac::{DBGMCU as DBG, TIM2, TIM3};
#[cfg(feature = "stm32f100")]
use crate::pac::{TIM15, TIM16, TIM17};

use crate::rcc::{Clocks, Enable, GetBusFreq, RccBus, Reset};
use crate::rcc::{self, Clocks};
use cast::{u16, u32, u64};
use cortex_m::peripheral::syst::SystClkSource;
use cortex_m::peripheral::SYST;
use void::Void;

use crate::time::Hertz;

#[cfg(feature = "rtic")]
mod monotonic;

/// Interrupt events
pub enum Event {
/// Timer timed out / count down ended
Expand Down Expand Up @@ -275,18 +278,50 @@ impl Cancel for CountDownTimer<SYST> {

impl Periodic for CountDownTimer<SYST> {}

pub trait Instance: crate::Sealed + rcc::Enable + rcc::Reset + rcc::GetBusFreq {}

impl<TIM> Timer<TIM>
where
TIM: Instance,
{
/// Initialize timer
pub fn new(tim: TIM, clocks: &Clocks) -> Self {
unsafe {
//NOTE(unsafe) this reference will only be used for atomic writes with no side effects
let rcc = &(*RCC::ptr());
// Enable and reset the timer peripheral
TIM::enable(rcc);
TIM::reset(rcc);
}

Self {
clk: TIM::get_timer_frequency(&clocks),
tim,
}
}

/// Resets timer peripheral
#[inline(always)]
pub fn clocking_reset(&mut self) {
let rcc = unsafe { &(*RCC::ptr()) };
TIM::reset(rcc);
}

/// Releases the TIM Peripheral
pub fn release(self) -> TIM {
self.tim
}
}

macro_rules! hal {
($($TIMX:ident: ($timX:ident, $APBx:ident, $dbg_timX_stop:ident$(,$master_timbase:ident)*),)+) => {
$(
impl Instance for $TIMX { }

impl Timer<$TIMX> {
/// Initialize timer
pub fn $timX(tim: $TIMX, clocks: &Clocks) -> Self {
// enable and reset peripheral to a clean slate state
let rcc = unsafe { &(*RCC::ptr()) };
$TIMX::enable(rcc);
$TIMX::reset(rcc);

Self { tim, clk: <$TIMX as RccBus>::Bus::get_timer_frequency(&clocks) }
Self::new(tim, clocks)
}

/// Starts timer in count down mode at a given frequency
Expand Down Expand Up @@ -323,23 +358,11 @@ macro_rules! hal {
timer
}

/// Resets timer peripheral
#[inline(always)]
pub fn clocking_reset(&mut self) {
let rcc = unsafe { &(*RCC::ptr()) };
$TIMX::reset(rcc);
}

/// Stopping timer in debug mode can cause troubles when sampling the signal
#[inline(always)]
pub fn stop_in_debug(&mut self, dbg: &mut DBG, state: bool) {
dbg.cr.modify(|_, w| w.$dbg_timX_stop().bit(state));
}

/// Releases the TIM Peripheral
pub fn release(self) -> $TIMX {
self.tim
}
}

impl CountDownTimer<$TIMX> {
Expand Down
123 changes: 123 additions & 0 deletions src/timer/monotonic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
//! RTIC Monotonic implementation

use core::convert::TryInto;

use crate::{rcc::Clocks, timer::Timer};
pub use fugit::{self, ExtU32};
use rtic_monotonic::Monotonic;

pub struct MonoTimer<T, const FREQ: u32> {
tim: T,
ovf: u32,
}

macro_rules! mono {
($($TIM:ty,)+) => {
$(
impl Timer<$TIM> {
pub fn monotonic<const FREQ: u32>(self) -> MonoTimer<$TIM, FREQ> {
MonoTimer::<$TIM, FREQ>::_new(self)
}
}

impl<const FREQ: u32> MonoTimer<$TIM, FREQ> {
pub fn new(timer: $TIM, clocks: &Clocks) -> Self {
Timer::<$TIM>::new(timer, clocks).monotonic()
}

fn _new(timer: Timer<$TIM>) -> Self {
let Timer { tim, clk } = timer;
// Configure timer. If the u16 conversion panics, try increasing FREQ.
let psc: u16 = (clk.0 / FREQ - 1).try_into().unwrap();
tim.psc.write(|w| w.psc().bits(psc)); // Set prescaler.
tim.arr.write(|w| w.arr().bits(u16::MAX)); // Set auto-reload value.
tim.egr.write(|w| w.ug().set_bit()); // Generate interrupt on overflow.

// Start timer.
tim.sr.modify(|_, w| w.uif().clear_bit()); // Clear interrupt flag.
tim.cr1.modify(|_, w| {
w.cen()
.set_bit() // Enable counter.
.udis()
.clear_bit() // Overflow should trigger update event.
.urs()
.set_bit() // Only overflow triggers interrupt.
});

Self { tim, ovf: 0 }
}
}

impl<const FREQ: u32> Monotonic for MonoTimer<$TIM, FREQ> {
type Instant = fugit::TimerInstantU32<FREQ>;
type Duration = fugit::TimerDurationU32<FREQ>;

unsafe fn reset(&mut self) {
self.tim.dier.modify(|_, w| w.cc1ie().set_bit());
}

#[inline(always)]
fn now(&mut self) -> Self::Instant {
let cnt = self.tim.cnt.read().cnt().bits() as u32;

// If the overflow bit is set, we add this to the timer value. It means the `on_interrupt`
// has not yet happened, and we need to compensate here.
let ovf = if self.tim.sr.read().uif().bit_is_set() {
0x10000
} else {
0
};

Self::Instant::from_ticks(cnt.wrapping_add(ovf).wrapping_add(self.ovf))
}

fn set_compare(&mut self, instant: Self::Instant) {
let now = self.now();
let cnt = self.tim.cnt.read().cnt().bits();

// Since the timer may or may not overflow based on the requested compare val, we check
// how many ticks are left.
let val = match instant.checked_duration_since(now) {
None => cnt.wrapping_add(0xffff), // In the past, RTIC will handle this
Some(x) if x.ticks() <= 0xffff => instant.duration_since_epoch().ticks() as u16, // Will not overflow
Some(_) => cnt.wrapping_add(0xffff), // Will overflow, run for as long as possible
};

self.tim.ccr1.write(|w| w.ccr().bits(val));
}

fn clear_compare_flag(&mut self) {
self.tim.sr.modify(|_, w| w.cc1if().clear_bit());
}

fn on_interrupt(&mut self) {
// If there was an overflow, increment the overflow counter.
if self.tim.sr.read().uif().bit_is_set() {
self.tim.sr.modify(|_, w| w.uif().clear_bit());

self.ovf += 0x10000;
}
}

#[inline(always)]
fn zero() -> Self::Instant {
Self::Instant::from_ticks(0)
}
}
)+
}
}

mono!(crate::pac::TIM2, crate::pac::TIM3,);

#[cfg(any(feature = "stm32f100", feature = "stm32f103", feature = "connectivity",))]
mono!(crate::pac::TIM1,);

#[cfg(feature = "medium")]
mono!(crate::pac::TIM4,);

#[cfg(any(feature = "high", feature = "connectivity"))]
mono!(crate::pac::TIM5,);

#[cfg(all(feature = "stm32f103", feature = "high",))]
mono!(crate::pac::TIM8,);