#include #include #include #include #include struct buzzer buzzers[] = { { TIM2, TIM_OC1 }, }; size_t nbuzzers = count_of(buzzers); void buzzer_init(struct buzzer *buzzer) { rcc_periph_reset_pulse(buzzer->timer); timer_set_mode(buzzer->timer, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); timer_set_prescaler(buzzer->timer, 72); timer_set_repetition_counter(buzzer->timer, 0); timer_enable_preload(buzzer->timer); timer_enable_break_main_output(buzzer->timer); timer_continuous_mode(buzzer->timer); timer_disable_oc_output(buzzer->timer, buzzer->channel); timer_set_oc_mode(buzzer->timer, buzzer->channel, TIM_OCM_PWM1); timer_set_oc_value(buzzer->timer, buzzer->channel, 0); timer_enable_oc_output(buzzer->timer, buzzer->channel); } void buzzer_enable(struct buzzer *buzzer) { timer_enable_counter(buzzer->timer); } void buzzer_disable(struct buzzer *buzzer) { timer_disable_counter(buzzer->timer); } void buzzer_set_freq(struct buzzer *buzzer, uint32_t freq) { uint32_t period = 1000000 / freq; timer_set_period(buzzer->timer, period); timer_set_oc_value(buzzer->timer, buzzer->channel, period / 2); }