基于keil编写stm32f103互补输出PWM的代码,使用TIM1,部分映射管脚
时间: 2024-01-24 11:02:28 浏览: 107
以下是基于Keil编写的STM32F103互补输出PWM的代码,使用TIM1,其中PA8和PA9被映射到TIM1的通道1和通道2上:
```c
#include "stm32f10x.h"
int main(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
// 使能GPIOA和TIM1的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_TIM1, ENABLE);
// 配置PA8和PA9为复用推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置TIM1的时基
TIM_TimeBaseStructure.TIM_Period = 999; // 1kHz的PWM频率
TIM_TimeBaseStructure.TIM_Prescaler = 71; // 72MHz时钟,分频为72,计数器时钟为1MHz
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
// 配置TIM1的通道1
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0; // 初始占空比为0
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
// 配置TIM1的通道2
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0; // 初始占空比为0
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC2Init(TIM1, &TIM_OCInitStructure);
// 启动TIM1
TIM_Cmd(TIM1, ENABLE);
// 设置TIM1的互补输出模式
TIM_BDTRInitTypeDef TIM_BDTRInitStructure;
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 = 50; // 50ns的死区时间
TIM_BDTRInitStructure.TIM_Break = TIM_Break_Disable;
TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_Low;
TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Enable;
TIM_BDTRConfig(TIM1, &TIM_BDTRInitStructure);
// 设置TIM1的互补输出使能
TIM_CCPreloadControl(TIM1, ENABLE);
TIM_CtrlPWMOutputs(TIM1, ENABLE);
while (1) {
// 修改TIM1通道1的占空比,使LED灯逐渐亮起
for (int i = 0; i <= 1000; i += 10) {
TIM_SetCompare1(TIM1, i);
TIM_SetCompare2(TIM1, 1000 - i);
for (int j = 0; j < 100000; j++); // 延时一段时间
}
}
}
```
这个代码先配置了GPIOA的PA8和PA9为复用推挽输出,然后配置了TIM1的时基和两个通道的PWM输出模式。接着设置了TIM1的互补输出模式并使能互补输出,最后在主循环中修改TIM1通道1和通道2的占空比,使得互补输出的PWM信号逐渐改变。
阅读全文