@@ -8,6 +8,7 @@ use crate::timer::pins::TimerPin;
8
8
use crate :: timer:: * ;
9
9
10
10
pub struct Pwm < TIM > {
11
+ clk : Hertz ,
11
12
tim : PhantomData < TIM > ,
12
13
}
13
14
@@ -47,24 +48,33 @@ macro_rules! pwm {
47
48
}
48
49
}
49
50
50
- fn $timX<T >( tim: $TIMX, freq: T , rcc: & mut Rcc ) -> Pwm <$TIMX>
51
- where
52
- T : Into <Hertz >,
53
- {
51
+ fn $timX<F : Into <Hertz >>( _tim: $TIMX, freq: F , rcc: & mut Rcc ) -> Pwm <$TIMX> {
54
52
$TIMX:: enable( rcc) ;
55
53
$TIMX:: reset( rcc) ;
56
54
57
- let ratio = rcc. clocks. apb_tim_clk / freq. into( ) ;
58
- let psc = ( ratio - 1 ) / 0xffff ;
59
- let arr = ratio / ( psc + 1 ) - 1 ;
60
- tim. psc. write( |w| unsafe { w. psc( ) . bits( psc as u16 ) } ) ;
61
- tim. arr. write( |w| unsafe { w. $arr( ) . bits( arr as u16 ) } ) ;
62
- $(
63
- tim. arr. modify( |_, w| unsafe { w. $arr_h( ) . bits( ( arr >> 16 ) as u16 ) } ) ;
64
- ) *
65
- tim. cr1. write( |w| w. cen( ) . set_bit( ) ) ;
66
- Pwm {
67
- tim: PhantomData
55
+ let mut pwm = Pwm :: <$TIMX> {
56
+ clk: rcc. clocks. apb_tim_clk,
57
+ tim: PhantomData ,
58
+ } ;
59
+ pwm. set_freq( freq) ;
60
+ pwm
61
+ }
62
+
63
+ impl Pwm <$TIMX> {
64
+ pub fn set_freq<F : Into <Hertz >>( & mut self , freq: F ) {
65
+ let ratio = self . clk / freq. into( ) ;
66
+ let psc = ( ratio - 1 ) / 0xffff ;
67
+ let arr = ratio / ( psc + 1 ) - 1 ;
68
+
69
+ unsafe {
70
+ let tim = & * $TIMX:: ptr( ) ;
71
+ tim. psc. write( |w| w. psc( ) . bits( psc as u16 ) ) ;
72
+ tim. arr. write( |w| w. $arr( ) . bits( arr as u16 ) ) ;
73
+ $(
74
+ tim. arr. modify( |_, w| w. $arr_h( ) . bits( ( arr >> 16 ) as u16 ) ) ;
75
+ ) *
76
+ tim. cr1. write( |w| w. cen( ) . set_bit( ) )
77
+ }
68
78
}
69
79
}
70
80
) +
0 commit comments