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

Reset timer CNT register when PWM period is changed #555

Merged
merged 3 commits into from
Dec 7, 2022

Conversation

scd31
Copy link

@scd31 scd31 commented Dec 6, 2022

When changing the period of a PWM timer repeatedly, it will sporadically stop working. This is because the CNT register isn't being reset.

Minimum reproducible example:

#![no_main]
#![no_std]

// use panic_halt as _;
use panic_semihosting as _;

use cortex_m_rt::entry;
use stm32f4xx_hal as hal;

use crate::hal::{pac, prelude::*, timer::Channel};

#[entry]
fn main() -> ! {
    let dp = pac::Peripherals::take().unwrap();

    let buzzer = dp.GPIOA.split().pa0.into_alternate();

    // Set up the system clock. We want to run at 48MHz for this one.
    let rcc = dp.RCC.constrain();
    let clocks = rcc.cfgr.use_hse(25.MHz()).sysclk(48.MHz()).freeze();

    let mut pwm = dp.TIM5.pwm_hz(buzzer, 1000.Hz(), &clocks);
    pwm.set_duty(Channel::C1, pwm.get_max_duty() / 2);
    pwm.enable(Channel::C1);

    let mut delay = dp.TIM1.delay_us(&clocks);

    loop {
        pwm.set_period(1000.Hz());
        pwm.set_duty(Channel::C1, pwm.get_max_duty() / 2);
        pwm.configure(&clocks);

        delay.delay_ms(1000_u32);

        pwm.set_period(2000.Hz());
        pwm.set_duty(Channel::C1, pwm.get_max_duty() / 2);
        pwm.configure(&clocks);

        delay.delay(1.secs());
    }
}

Before this PR, this would work for a few cycles before the signal disappears. It would occasionally reappear every few minutes. After this PR, the code is consistently outputting a signal that alternates between 1 and 2 KHz.

@burrbull
Copy link
Contributor

burrbull commented Dec 6, 2022

Should we also clear interrupt flags there?

Add this to Pwm::set_period also and update changelog

@scd31
Copy link
Author

scd31 commented Dec 6, 2022

@burrbull I am not sure if we want to clear the interrupt flags. I would imagine we'd want to keep them (if an interrupt is raised right before set_period is called we probably still want to handle that interrupt)

@burrbull
Copy link
Contributor

burrbull commented Dec 7, 2022

bors r+

@bors bors bot merged commit 9d21215 into stm32-rs:master Dec 7, 2022
@scd31 scd31 deleted the reset_timer_on_pwm_period_change branch December 7, 2022 12:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants