stm32f103对输出的两路pwn波记高电平次数代码
时间: 2024-01-05 09:02:15 浏览: 129
以下是STM32F103对输出的两路PWM波计高电平次数的代码:
```c
#include "stm32f10x.h"
#define PWM_FREQ 1000 // PWM频率
#define PWM_PERIOD (SystemCoreClock / PWM_FREQ - 1) // PWM周期
uint16_t PWM1_Duty = 500; // PWM1占空比
uint16_t PWM2_Duty = 250; // PWM2占空比
uint32_t PWM1_HighCount = 0; // PWM1高电平计数
uint32_t PWM2_HighCount = 0; // PWM2高电平计数
int main(void)
{
// 使能GPIOB和TIM3时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
// 配置GPIOB.0和GPIOB.1为复用推挽输出
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 配置TIM3为PWM模式
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = PWM_PERIOD;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
// 配置TIM3的通道1和通道2为PWM输出模式
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = PWM1_Duty;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStructure);
TIM_OCInitStructure.TIM_Pulse = PWM2_Duty;
TIM_OC2Init(TIM3, &TIM_OCInitStructure);
// 启动TIM3
TIM_Cmd(TIM3, ENABLE);
while (1)
{
// 计算PWM1和PWM2的高电平次数
PWM1_HighCount = TIM_GetCounter(TIM3) * PWM1_Duty / PWM_PERIOD;
PWM2_HighCount = TIM_GetCounter(TIM3) * PWM2_Duty / PWM_PERIOD;
}
}
```
在上面的代码中,我们首先定义了PWM的频率和占空比。然后定义了两个变量`PWM1_HighCount`和`PWM2_HighCount`,分别用来记录PWM1和PWM2的高电平次数。
在`main`函数中,我们先使能GPIOB和TIM3的时钟。然后配置GPIOB.0和GPIOB.1为复用推挽输出。接着,我们配置TIM3为PWM模式,并将通道1和通道2配置为PWM输出模式。最后启动TIM3的计数器。
在`while`循环中,我们通过计算当前TIM3计数器的值,以及PWM1和PWM2的占空比,来计算PWM1和PWM2的高电平次数。这样就可以实现对输出的两路PWM波高电平次数的计数了。
阅读全文