stm32对定时器2通道34输出的pwn波记高电平次数代码
时间: 2024-01-05 20:03:18 浏览: 145
STM32定时器捕获高电平时间程序
5星 · 资源好评率100%
以下是使用STM32的定时器2通道3和4输出PWM波,并记录高电平次数的代码示例:
```c
#include "stm32f4xx.h"
int main(void)
{
// 初始化GPIO
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_TIM2);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_TIM2);
// 初始化定时器
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_TimeBaseInitStruct.TIM_Period = 9999; // PWM频率为10kHz
TIM_TimeBaseInitStruct.TIM_Prescaler = 83; // 定时器时钟为84MHz/84=1MHz
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
TIM_OCInitTypeDef TIM_OCInitStruct;
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_Pulse = 4999; // 占空比50%
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC3Init(TIM2, &TIM_OCInitStruct);
TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_OC4Init(TIM2, &TIM_OCInitStruct);
TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_Cmd(TIM2, ENABLE);
// 记录高电平次数
uint32_t cnt = 0;
while (1)
{
if (TIM2->CCR3 > 4999 / 2) // 通道3输出高电平
{
cnt++;
}
}
}
```
该代码使用的是STM32F4xx系列微控制器,使用定时器2的通道3和4分别输出PWM波,并通过TIM2->CCR3寄存器检测通道3输出的PWM波是否为高电平,从而记录高电平次数。
阅读全文