STM32定时器单脉冲输出

来源:互联网 发布:网络交友的好处和弊端: 编辑:程序博客网 时间:2024/06/13 20:18

使用stm32cubemx配置外设,代码使用HAL stm32f1 v1.3.1库。

用的是stm32l152c开发板,时钟频率32MHZ。





这里,没有配置中断。



上图的意思是,TI2收到1给正脉冲,触发TIM1开始计数,经过 tDelay后,OC1输出低,经过一个tPulse后,OC1又恢复为高。


The OPM waveform is defined by writing the compare registers (taking into account the clock frequency and the counter prescaler).
• The tDELAY is defined by the value written in the TIMx_CCR1 register.
• The tPULSEis defined by the difference between the auto-reload value and the compare value (TIMx_ARR - TIMx_CCR + 1).

Let’s say you want to build a waveform with a transition from ‘0 to ‘1 when a compare match occurs and a transition from ‘1 to ‘0 when the counter reaches the auto-reload value. 

To do this you enable PWM mode 2 by writing OC1M=111 in the TIMx_CCMR1 register. You can optionally enable the preload registers by writing OC1PE=1 in the 
TIMx_CCMR1 register and ARPE in the TIMx_CR1 register. In thiscase you have to write the compare value in the TIMx_CCR1 register, the auto-reload value in the 
TIMx_ARR register, generate an update by setting the UG bit and wait for external trigger event on TI2. CC1P is written to ‘0 in this example.

向比较寄存器写入数值(考虑时钟频率和计数分频来计算)来定义OPM波形。

1)tDelay值是TIMx_CCR1寄存器值

2)tPulse的值是 自动重装值减掉比较值: (TIMx_ARR - TIMx_CCR + 1)


假如,当比较相符发生时,你希望得到从0到1的波形,而当计数器达到自动重装值时,波形又从1变到0.

这种情况,使用PWM模式2,TIMx_CCMR1 寄存器的OC1M要为111。可选:使能重装寄存器。 在此例子中,你需要把比较值写到TIMx_CCR1 寄存器,自动重装值写到TIMx_ARR寄存器,设置UG位产生一个更新事件,并且等待TI2的外部触发事件。CC1P被写为 0.


看了手册上面的描述,就明白了:

我按下按钮,延时2秒,点亮绿灯,停1秒,绿灯灭。


如果是控制可控硅,就是:

检测到零点,延时x微秒,触发可控硅,停1毫秒,关掉可控硅。 生成触发脉冲。

可以让硬件自己处理,不用中断。


开发板实现描述1.


  while (1)  {  /* USER CODE END WHILE */  /* USER CODE BEGIN 3 */    if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == GPIO_PIN_SET) {      HAL_Delay(100);            if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == GPIO_PIN_SET) {        __HAL_TIM_ENABLE(&htim4);        HAL_TIM_OnePulse_Start(&htim4, TIM_CHANNEL_2);      }    }      }  /* USER CODE END 3 */}

HAL_TIM_OnePulse_Start函数有问题,它总是使能1、2两个通道,而且它不启用定时器的计数。

因此,在它之前要使用宏 __HAL_TIM_ENABLE,置位 TIMx_CR1的CEN。


需要注意到,单脉冲功能,只能在1、2通道上做。

1 0