pwm.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. /*!
  2. # Pulse width modulation
  3. The general purpose timers (`TIM2`, `TIM3`, and `TIM4`) can be used to output
  4. pulse width modulated signals on some pins. The timers support up to 4
  5. simultaneous pwm outputs in separate `Channels`
  6. ## Usage for pre-defined channel combinations
  7. This crate only defines basic channel combinations for default AFIO remappings,
  8. where all the channels are enabled. Start by setting all the pins for the
  9. timer you want to use to alternate push pull pins:
  10. ```rust
  11. let gpioa = ..; // Set up and split GPIOA
  12. // Select the pins you want to use
  13. let pins = (
  14. gpioa.pa0.into_alternate_push_pull(&mut gpioa.crl),
  15. gpioa.pa1.into_alternate_push_pull(&mut gpioa.crl),
  16. gpioa.pa2.into_alternate_push_pull(&mut gpioa.crl),
  17. gpioa.pa3.into_alternate_push_pull(&mut gpioa.crl),
  18. );
  19. // Set up the timer as a PWM output. If selected pins may correspond to different remap options,
  20. // then you must specify the remap generic parameter. Otherwise, if there is no such ambiguity,
  21. // the remap generic parameter can be omitted without complains from the compiler.
  22. let (c1, c2, c3, c4) = Timer::tim2(p.TIM2, &clocks, &mut rcc.apb1)
  23. .pwm::<Tim2NoRemap, _, _, _>(pins, &mut afio.mapr, 1.khz())
  24. .3;
  25. // Start using the channels
  26. c1.set_duty(c1.get_max_duty());
  27. // ...
  28. ```
  29. Then call the `pwm` function on the corresponding timer.
  30. NOTE: In some cases you need to specify remap you need, especially for TIM2
  31. (see [Alternate function remapping](super::timer)):
  32. ```
  33. let device: pac::Peripherals = ..;
  34. // Put the timer in PWM mode using the specified pins
  35. // with a frequency of 100 hz.
  36. let (c0, c1, c2, c3) = Timer::tim2(device.TIM2, &clocks, &mut rcc.apb1)
  37. .pwm::<Tim2NoRemap, _, _, _>(pins, &mut afio.mapr, 100.hz());
  38. // Set the duty cycle of channel 0 to 50%
  39. c0.set_duty(c0.get_max_duty() / 2);
  40. // PWM outputs are disabled by default
  41. c0.enable()
  42. ```
  43. */
  44. use core::marker::Copy;
  45. use core::marker::PhantomData;
  46. use core::mem;
  47. use crate::hal;
  48. #[cfg(any(feature = "stm32f100", feature = "stm32f103", feature = "connectivity",))]
  49. use crate::pac::TIM1;
  50. #[cfg(feature = "medium")]
  51. use crate::pac::TIM4;
  52. use crate::pac::{TIM2, TIM3};
  53. use cast::{u16, u32};
  54. use crate::afio::MAPR;
  55. use crate::bb;
  56. use crate::gpio::{self, Alternate, PushPull};
  57. use crate::time::Hertz;
  58. use crate::time::U32Ext;
  59. use crate::timer::Timer;
  60. pub trait Pins<REMAP, P> {
  61. const C1: bool = false;
  62. const C2: bool = false;
  63. const C3: bool = false;
  64. const C4: bool = false;
  65. type Channels;
  66. fn check_used(c: Channel) -> Channel {
  67. if (c == Channel::C1 && Self::C1)
  68. || (c == Channel::C2 && Self::C2)
  69. || (c == Channel::C3 && Self::C3)
  70. || (c == Channel::C4 && Self::C4)
  71. {
  72. c
  73. } else {
  74. panic!("Unused channel")
  75. }
  76. }
  77. }
  78. #[derive(Clone, Copy, PartialEq)]
  79. pub enum Channel {
  80. C1,
  81. C2,
  82. C3,
  83. C4,
  84. }
  85. use crate::timer::sealed::{Ch1, Ch2, Ch3, Ch4, Remap};
  86. macro_rules! pins_impl {
  87. ( $( ( $($PINX:ident),+ ), ( $($TRAIT:ident),+ ), ( $($ENCHX:ident),* ); )+ ) => {
  88. $(
  89. #[allow(unused_parens)]
  90. impl<TIM, REMAP, $($PINX,)+> Pins<REMAP, ($($ENCHX),+)> for ($($PINX),+)
  91. where
  92. REMAP: Remap<Periph = TIM>,
  93. $($PINX: $TRAIT<REMAP> + gpio::Mode<Alternate<PushPull>>,)+
  94. {
  95. $(const $ENCHX: bool = true;)+
  96. type Channels = ($(PwmChannel<TIM, $ENCHX>),+);
  97. }
  98. )+
  99. };
  100. }
  101. pins_impl!(
  102. (P1, P2, P3, P4), (Ch1, Ch2, Ch3, Ch4), (C1, C2, C3, C4);
  103. (P2, P3, P4), (Ch2, Ch3, Ch4), (C2, C3, C4);
  104. (P1, P3, P4), (Ch1, Ch3, Ch4), (C1, C3, C4);
  105. (P1, P2, P4), (Ch1, Ch2, Ch4), (C1, C2, C4);
  106. (P1, P2, P3), (Ch1, Ch2, Ch3), (C1, C2, C3);
  107. (P3, P4), (Ch3, Ch4), (C3, C4);
  108. (P2, P4), (Ch2, Ch4), (C2, C4);
  109. (P2, P3), (Ch2, Ch3), (C2, C3);
  110. (P1, P4), (Ch1, Ch4), (C1, C4);
  111. (P1, P3), (Ch1, Ch3), (C1, C3);
  112. (P1, P2), (Ch1, Ch2), (C1, C2);
  113. (P1), (Ch1), (C1);
  114. (P2), (Ch2), (C2);
  115. (P3), (Ch3), (C3);
  116. (P4), (Ch4), (C4);
  117. );
  118. #[cfg(any(feature = "stm32f100", feature = "stm32f103", feature = "connectivity",))]
  119. impl Timer<TIM1> {
  120. pub fn pwm<REMAP, P, PINS, T>(
  121. self,
  122. _pins: PINS,
  123. mapr: &mut MAPR,
  124. freq: T,
  125. ) -> Pwm<TIM1, REMAP, P, PINS>
  126. where
  127. REMAP: Remap<Periph = TIM1>,
  128. PINS: Pins<REMAP, P>,
  129. T: Into<Hertz>,
  130. {
  131. mapr.modify_mapr(|_, w| unsafe { w.tim1_remap().bits(REMAP::REMAP) });
  132. // TIM1 has a break function that deactivates the outputs, this bit automatically activates
  133. // the output when no break input is present
  134. self.tim.bdtr.modify(|_, w| w.aoe().set_bit());
  135. let Self { tim, clk } = self;
  136. tim1(tim, _pins, freq.into(), clk)
  137. }
  138. }
  139. impl Timer<TIM2> {
  140. pub fn pwm<REMAP, P, PINS, T>(
  141. self,
  142. _pins: PINS,
  143. mapr: &mut MAPR,
  144. freq: T,
  145. ) -> Pwm<TIM2, REMAP, P, PINS>
  146. where
  147. REMAP: Remap<Periph = TIM2>,
  148. PINS: Pins<REMAP, P>,
  149. T: Into<Hertz>,
  150. {
  151. mapr.modify_mapr(|_, w| unsafe { w.tim2_remap().bits(REMAP::REMAP) });
  152. let Self { tim, clk } = self;
  153. tim2(tim, _pins, freq.into(), clk)
  154. }
  155. }
  156. impl Timer<TIM3> {
  157. pub fn pwm<REMAP, P, PINS, T>(
  158. self,
  159. _pins: PINS,
  160. mapr: &mut MAPR,
  161. freq: T,
  162. ) -> Pwm<TIM3, REMAP, P, PINS>
  163. where
  164. REMAP: Remap<Periph = TIM3>,
  165. PINS: Pins<REMAP, P>,
  166. T: Into<Hertz>,
  167. {
  168. mapr.modify_mapr(|_, w| unsafe { w.tim3_remap().bits(REMAP::REMAP) });
  169. let Self { tim, clk } = self;
  170. tim3(tim, _pins, freq.into(), clk)
  171. }
  172. }
  173. #[cfg(feature = "medium")]
  174. impl Timer<TIM4> {
  175. pub fn pwm<REMAP, P, PINS, T>(
  176. self,
  177. _pins: PINS,
  178. mapr: &mut MAPR,
  179. freq: T,
  180. ) -> Pwm<TIM4, REMAP, P, PINS>
  181. where
  182. REMAP: Remap<Periph = TIM4>,
  183. PINS: Pins<REMAP, P>,
  184. T: Into<Hertz>,
  185. {
  186. mapr.modify_mapr(|_, w| w.tim4_remap().bit(REMAP::REMAP == 1));
  187. let Self { tim, clk } = self;
  188. tim4(tim, _pins, freq.into(), clk)
  189. }
  190. }
  191. pub struct Pwm<TIM, REMAP, P, PINS>
  192. where
  193. REMAP: Remap<Periph = TIM>,
  194. PINS: Pins<REMAP, P>,
  195. {
  196. clk: Hertz,
  197. _pins: PhantomData<(TIM, REMAP, P, PINS)>,
  198. }
  199. impl<TIM, REMAP, P, PINS> Pwm<TIM, REMAP, P, PINS>
  200. where
  201. REMAP: Remap<Periph = TIM>,
  202. PINS: Pins<REMAP, P>,
  203. {
  204. pub fn split(self) -> PINS::Channels {
  205. unsafe { mem::MaybeUninit::uninit().assume_init() }
  206. }
  207. }
  208. pub struct PwmChannel<TIM, CHANNEL> {
  209. _channel: PhantomData<CHANNEL>,
  210. _tim: PhantomData<TIM>,
  211. }
  212. pub struct C1;
  213. pub struct C2;
  214. pub struct C3;
  215. pub struct C4;
  216. macro_rules! hal {
  217. ($($TIMX:ident: ($timX:ident),)+) => {
  218. $(
  219. fn $timX<REMAP, P, PINS>(
  220. tim: $TIMX,
  221. _pins: PINS,
  222. freq: Hertz,
  223. clk: Hertz,
  224. ) -> Pwm<$TIMX, REMAP, P, PINS>
  225. where
  226. REMAP: Remap<Periph = $TIMX>,
  227. PINS: Pins<REMAP, P>,
  228. {
  229. if PINS::C1 {
  230. tim.ccmr1_output()
  231. .modify(|_, w| w.oc1pe().set_bit().oc1m().pwm_mode1() );
  232. }
  233. if PINS::C2 {
  234. tim.ccmr1_output()
  235. .modify(|_, w| w.oc2pe().set_bit().oc2m().pwm_mode1() );
  236. }
  237. if PINS::C3 {
  238. tim.ccmr2_output()
  239. .modify(|_, w| w.oc3pe().set_bit().oc3m().pwm_mode1() );
  240. }
  241. if PINS::C4 {
  242. tim.ccmr2_output()
  243. .modify(|_, w| w.oc4pe().set_bit().oc4m().pwm_mode1() );
  244. }
  245. let ticks = clk.0 / freq.0;
  246. let psc = u16(ticks / (1 << 16)).unwrap();
  247. tim.psc.write(|w| w.psc().bits(psc) );
  248. let arr = u16(ticks / u32(psc + 1)).unwrap();
  249. tim.arr.write(|w| w.arr().bits(arr));
  250. // The psc register is buffered, so we trigger an update event to update it
  251. // Sets the URS bit to prevent an interrupt from being triggered by the UG bit
  252. tim.cr1.modify(|_, w| w.urs().set_bit());
  253. tim.egr.write(|w| w.ug().set_bit());
  254. tim.cr1.modify(|_, w| w.urs().clear_bit());
  255. tim.cr1.write(|w|
  256. w.cms()
  257. .bits(0b00)
  258. .dir()
  259. .clear_bit()
  260. .opm()
  261. .clear_bit()
  262. .cen()
  263. .set_bit()
  264. );
  265. Pwm {
  266. clk: clk,
  267. _pins: PhantomData
  268. }
  269. }
  270. /*
  271. The following implemention of the embedded_hal::Pwm uses Hertz as a time type. This was choosen
  272. because of the timescales of operations being on the order of nanoseconds and not being able to
  273. efficently represent a float on the hardware. It might be possible to change the time type to
  274. a different time based using such as the nanosecond. The issue with doing so is that the max
  275. delay would then be at just a little over 2 seconds because of the 32 bit depth of the number.
  276. Using milliseconds is also an option, however, using this as a base unit means that only there
  277. could be resolution issues when trying to get a specific value, because of the integer nature.
  278. To find a middle ground, the Hertz type is used as a base here and the Into trait has been
  279. defined for several base time units. This will allow for calling the set_period method with
  280. something that is natural to both the MCU and the end user.
  281. */
  282. impl<REMAP, P, PINS> hal::Pwm for Pwm<$TIMX, REMAP, P, PINS> where
  283. REMAP: Remap<Periph = $TIMX>,
  284. PINS: Pins<REMAP, P>,
  285. {
  286. type Channel = Channel;
  287. type Duty = u16;
  288. type Time = Hertz;
  289. fn enable(&mut self, channel: Self::Channel) {
  290. match PINS::check_used(channel) {
  291. Channel::C1 => unsafe { bb::set(&(*$TIMX::ptr()).ccer, 0) },
  292. Channel::C2 => unsafe { bb::set(&(*$TIMX::ptr()).ccer, 4) },
  293. Channel::C3 => unsafe { bb::set(&(*$TIMX::ptr()).ccer, 8) },
  294. Channel::C4 => unsafe { bb::set(&(*$TIMX::ptr()).ccer, 12) }
  295. }
  296. }
  297. fn disable(&mut self, channel: Self::Channel) {
  298. match PINS::check_used(channel) {
  299. Channel::C1 => unsafe { bb::clear(&(*$TIMX::ptr()).ccer, 0) },
  300. Channel::C2 => unsafe { bb::clear(&(*$TIMX::ptr()).ccer, 4) },
  301. Channel::C3 => unsafe { bb::clear(&(*$TIMX::ptr()).ccer, 8) },
  302. Channel::C4 => unsafe { bb::clear(&(*$TIMX::ptr()).ccer, 12) },
  303. }
  304. }
  305. fn get_duty(&self, channel: Self::Channel) -> Self::Duty {
  306. match PINS::check_used(channel) {
  307. Channel::C1 => unsafe { (*$TIMX::ptr()).ccr1.read().ccr().bits() },
  308. Channel::C2 => unsafe { (*$TIMX::ptr()).ccr2.read().ccr().bits() },
  309. Channel::C3 => unsafe { (*$TIMX::ptr()).ccr3.read().ccr().bits() },
  310. Channel::C4 => unsafe { (*$TIMX::ptr()).ccr4.read().ccr().bits() },
  311. }
  312. }
  313. fn set_duty(&mut self, channel: Self::Channel, duty: Self::Duty) {
  314. match PINS::check_used(channel) {
  315. Channel::C1 => unsafe { (*$TIMX::ptr()).ccr1.write(|w| w.ccr().bits(duty)) },
  316. Channel::C2 => unsafe { (*$TIMX::ptr()).ccr2.write(|w| w.ccr().bits(duty)) },
  317. Channel::C3 => unsafe { (*$TIMX::ptr()).ccr3.write(|w| w.ccr().bits(duty)) },
  318. Channel::C4 => unsafe { (*$TIMX::ptr()).ccr4.write(|w| w.ccr().bits(duty)) },
  319. }
  320. }
  321. fn get_max_duty(&self) -> Self::Duty {
  322. unsafe { (*$TIMX::ptr()).arr.read().arr().bits() }
  323. }
  324. fn get_period(&self) -> Self::Time {
  325. let clk = self.clk;
  326. let psc: u16 = unsafe{(*$TIMX::ptr()).psc.read().psc().bits()};
  327. let arr: u16 = unsafe{(*$TIMX::ptr()).arr.read().arr().bits()};
  328. // Length in ms of an internal clock pulse
  329. (clk.0 / u32(psc * arr)).hz()
  330. }
  331. fn set_period<T>(&mut self, period: T) where
  332. T: Into<Self::Time> {
  333. let clk = self.clk;
  334. let ticks = clk.0 / period.into().0;
  335. let psc = u16(ticks / (1 << 16)).unwrap();
  336. let arr = u16(ticks / u32(psc + 1)).unwrap();
  337. unsafe {
  338. (*$TIMX::ptr()).psc.write(|w| w.psc().bits(psc));
  339. (*$TIMX::ptr()).arr.write(|w| w.arr().bits(arr));
  340. }
  341. }
  342. }
  343. impl hal::PwmPin for PwmChannel<$TIMX, C1> {
  344. type Duty = u16;
  345. fn disable(&mut self) {
  346. unsafe { bb::clear(&(*$TIMX::ptr()).ccer, 0) }
  347. }
  348. fn enable(&mut self) {
  349. unsafe { bb::set(&(*$TIMX::ptr()).ccer, 0) }
  350. }
  351. fn get_duty(&self) -> u16 {
  352. unsafe { (*$TIMX::ptr()).ccr1.read().ccr().bits() }
  353. }
  354. fn get_max_duty(&self) -> u16 {
  355. unsafe { (*$TIMX::ptr()).arr.read().arr().bits() }
  356. }
  357. fn set_duty(&mut self, duty: u16) {
  358. unsafe { (*$TIMX::ptr()).ccr1.write(|w| w.ccr().bits(duty)) }
  359. }
  360. }
  361. impl hal::PwmPin for PwmChannel<$TIMX, C2> {
  362. type Duty = u16;
  363. fn disable(&mut self) {
  364. unsafe { bb::clear(&(*$TIMX::ptr()).ccer, 4) }
  365. }
  366. fn enable(&mut self) {
  367. unsafe { bb::set(&(*$TIMX::ptr()).ccer, 4) }
  368. }
  369. fn get_duty(&self) -> u16 {
  370. unsafe { (*$TIMX::ptr()).ccr2.read().ccr().bits() }
  371. }
  372. fn get_max_duty(&self) -> u16 {
  373. unsafe { (*$TIMX::ptr()).arr.read().arr().bits() }
  374. }
  375. fn set_duty(&mut self, duty: u16) {
  376. unsafe { (*$TIMX::ptr()).ccr2.write(|w| w.ccr().bits(duty)) }
  377. }
  378. }
  379. impl hal::PwmPin for PwmChannel<$TIMX, C3> {
  380. type Duty = u16;
  381. fn disable(&mut self) {
  382. unsafe { bb::clear(&(*$TIMX::ptr()).ccer, 8) }
  383. }
  384. fn enable(&mut self) {
  385. unsafe { bb::set(&(*$TIMX::ptr()).ccer, 8) }
  386. }
  387. fn get_duty(&self) -> u16 {
  388. unsafe { (*$TIMX::ptr()).ccr3.read().ccr().bits() }
  389. }
  390. fn get_max_duty(&self) -> u16 {
  391. unsafe { (*$TIMX::ptr()).arr.read().arr().bits() }
  392. }
  393. fn set_duty(&mut self, duty: u16) {
  394. unsafe { (*$TIMX::ptr()).ccr3.write(|w| w.ccr().bits(duty)) }
  395. }
  396. }
  397. impl hal::PwmPin for PwmChannel<$TIMX, C4> {
  398. type Duty = u16;
  399. fn disable(&mut self) {
  400. unsafe { bb::clear(&(*$TIMX::ptr()).ccer, 12) }
  401. }
  402. fn enable(&mut self) {
  403. unsafe { bb::set(&(*$TIMX::ptr()).ccer, 12) }
  404. }
  405. fn get_duty(&self) -> u16 {
  406. unsafe { (*$TIMX::ptr()).ccr4.read().ccr().bits() }
  407. }
  408. fn get_max_duty(&self) -> u16 {
  409. unsafe { (*$TIMX::ptr()).arr.read().arr().bits() }
  410. }
  411. fn set_duty(&mut self, duty: u16) {
  412. unsafe { (*$TIMX::ptr()).ccr4.write(|w| w.ccr().bits(duty)) }
  413. }
  414. }
  415. )+
  416. }
  417. }
  418. #[cfg(any(feature = "stm32f100", feature = "stm32f103", feature = "connectivity",))]
  419. hal! {
  420. TIM1: (tim1),
  421. }
  422. hal! {
  423. TIM2: (tim2),
  424. TIM3: (tim3),
  425. }
  426. #[cfg(feature = "medium")]
  427. hal! {
  428. TIM4: (tim4),
  429. }