stm32f103对定时器2通道34输出的pwn波记高电平次数标准库代码
时间: 2024-01-05 22:03:18 浏览: 129
以下是使用STM32F103标准库的定时器2通道3和4输出PWM波的代码,其中计算高电平次数的部分已经添加:
```
#include "stm32f10x.h"
#define PWM_FREQ 10000 // PWM波频率为10kHz
#define PWM_MAX_DUTY_CYCLE 100 // PWM波最大占空比为100%
void GPIO_Configuration(void);
void TIM2_Configuration(void);
void PWM_Output_Configuration(void);
uint32_t high_count = 0; // 高电平次数计数器
int main(void)
{
GPIO_Configuration();
TIM2_Configuration();
PWM_Output_Configuration();
while (1)
{
// 计算高电平次数
high_count = TIM_GetCapture2(TIM2);
}
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
// 打开GPIOA和AFIO时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
// 配置PA2和PA3为复用功能推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void TIM2_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
// 打开TIM2时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
// 配置TIM2基本参数
TIM_TimeBaseStructure.TIM_Period = SystemCoreClock / PWM_FREQ - 1; // PWM波周期
TIM_TimeBaseStructure.TIM_Prescaler = 0; // 不分频
TIM_TimeBaseStructure.TIM_ClockDivision = 0; // 不分频
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // 向上计数
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 配置TIM2通道3和4为PWM输出模式
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = (SystemCoreClock / PWM_FREQ) * PWM_MAX_DUTY_CYCLE / 100 - 1; // PWM波占空比
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC3Init(TIM2, &TIM_OCInitStructure);
TIM_OC4Init(TIM2, &TIM_OCInitStructure);
// 启动TIM2
TIM_Cmd(TIM2, ENABLE);
}
void PWM_Output_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_BDTRInitTypeDef TIM_BDTRInitStructure;
// 打开GPIOB时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
// 配置PB10和PB11为复用功能推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 配置TIM2的BDTR寄存器
TIM_BDTRInitStructure.TIM_OSSRState = TIM_OSSRState_Enable; // 开启输出比较快速重载
TIM_BDTRInitStructure.TIM_OSSIState = TIM_OSSIState_Enable; // 开启输出比较快速关闭
TIM_BDTRInitStructure.TIM_LOCKLevel = TIM_LOCKLevel_OFF; // 关闭锁定配置
TIM_BDTRInitStructure.TIM_DeadTime = 0; // 死区时间为0
TIM_BDTRInitStructure.TIM_Break = TIM_Break_Disable; // 禁用定时器2的断路器
TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_Low;
TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Enable; // 开启自动输出使能
TIM_BDTRConfig(TIM2, &TIM_BDTRInitStructure);
}
```
阅读全文