stm32f103对输出的pwn波记高电平次数代码
时间: 2024-01-05 09:02:15 浏览: 74
以下是基于STM32F103的PWM输出代码,可记录高电平次数:
```c
#include "stm32f10x.h"
#include "stm32f10x_tim.h"
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
uint32_t highCount = 0; // 记录高电平次数
int main(void)
{
// 启用时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE); // GPIOA和复用功能时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); // 定时器2时钟
// 配置GPIO
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; // 复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置定时器
TIM_TimeBaseStructure.TIM_Period = 1000; // 计数器最大值
TIM_TimeBaseStructure.TIM_Prescaler = 71; // 分频系数
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 配置PWM输出通道
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 500; // 占空比为50%
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC2Init(TIM2, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable);
// 启动定时器
TIM_Cmd(TIM2, ENABLE);
while(1)
{
if(TIM_GetFlagStatus(TIM2, TIM_FLAG_Update) != RESET) // 定时器溢出
{
TIM_ClearFlag(TIM2, TIM_FLAG_Update);
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == GPIO_Pin_Set) // 输入为高电平
{
highCount++; // 记录高电平次数
}
}
}
}
```
上述代码中,占空比为50%的PWM输出被设置在定时器2的通道2上。在每次定时器溢出时,通过读取GPIOA的输入引脚状态来判断是否为高电平,并计数高电平次数。最后,可以根据高电平次数来确定PWM波的频率或其他相关参数。
阅读全文