电子达人2011

STM32输出精确个PWM波形

0
阅读(1725)

最近涉及到一个超声波测距的项目,测距开始时需要触发指定个数的方波。此为背景。
在网上搜集了相关资料,有以下几个思路供参考:
1、最直观的

  1. while(pulsecnt--)

  2. {

  3.     for(;;);//delay up to the frequency

  4.     Pin_ON();

  5.     for(;;);

  6.     Pin_OFF();

  7. }

复制代码


2、如果你的timer有RCR,那就好办了。看ST参考手册的解释:

If the repetition counter is used, the update event (UEV) is generated after upcounting is repeated for the number of times programmed in the repetition counter register (TIMx_RCR). Else the update event is generated at each counter overflow.


用此方法需要考虑到RCR只有8位,以及PWM的edge-aligned and center-aligned模式:

Each time the REP_CNT related downcounter reaches zero, an update event is generated
and it restarts counting from REP value. As REP_CNT is reloaded with REP value only at the
repetition update event U_RC, any write to the TIMx_RCR register is not taken in account until
the next repetition update event.
It means in PWM mode (REP+1) corresponds to:
– the number of PWM periods in edge-aligned mode
– the number of half PWM period in center-aligned mode.


3、DMA方式送数。
    将DMA与Tim的CCR绑定,通过控制DMA的数据数量,输出同等数量的波形,该方式有以下优缺点:
    优点:PWM的脉冲宽度控制较为灵活,可事先将脉冲宽度写入DMA的传输Buffer中;
    缺点:PWM的周期控制可能会不那么准确,因为DMA传输的触发到传输完成需要一定时间;

4、利用Timer之间的同步:

Configure Timer 1 in master mode so that it outputs a periodic trigger signal on each
update event UEV. If you write MMS=010 in the TIM1_CR2 register, a rising edge is
output on TRGO1 each time an update event is generated.
• To connect the TRGO1 output of Timer 1 to Timer 2, Timer 2 must be configured in
slave mode using ITR1 as internal trigger. You select this through the TS bits in the
TIM2_SMCR register (writing TS=000).
• Then the Timer2's slave mode controller should be configured in external clock mode 1
(write SMS=111 in the TIM2_SMCR register). This causes Timer 2 to be clocked by the
rising edge of the periodic Timer 1 trigger signal (which correspond to the timer 1
counter overflow).
• Finally both timers must be enabled by setting their respective CEN bits within their
respective TIMx_CR1 registers. Make sure to enable Timer2 before enabling Timer1.


  Tim1负责PWM输出,Tim2控制脉冲数。Tim1、Tim2设置好后,给Tim2的ARR设置为 PulseCnt-1 以及为Tim2的Update事件设置中断,在中断服务程序中关闭Tim以完成PulseCnt脉冲的发送。        
      Note:  1、Tim1设置为PWM mode 2,避免在结束输出时Tim1多输出一个脉冲;
                2、代码着重说明Tim的配置,若用此方法需要结合应用增添相应代码。
代码:

  1. TIM1->CR2 |= TIM_CR2_MMS_1;

  2. TIM2->SMCR |= TIM_SMCR_SMS_2 | TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0;

  3. TIM1->PSC = 47999;

  4. TIM1->ARR = 999;

  5. TIM2->ARR = PulseCnt-1;

  6. TIM1->CR1 |= TIM_CR1_CEN;

  7. TIM2->CR1 |= TIM_CR1_CEN;

复制代码


以上是个人通过学习相关资料所做的总结,如有不当之处,欢迎拍砖。

PS. 几个链接:
http://bbs.eeworld.com.cn/thread-252318-1-1.htmlhttp://www.amobbs.com/thread-5509627-1-1.html
http://www.stmcu.org/module/forum/thread-559739-1-1.html
PPS.几次想上传图片,以便更好说明问题,为什么总是失败,是我公司网络问题,还是Server的问题?PPPS.在这个位置贴的链接也会丢失,不知道是什么问题。了解更多