STM32F103C8T6设置定时器1和定时器2输出PWM标准库代码
时间: 2023-12-18 19:37:37 浏览: 217
STM32定时器2PWM输出
以下是使用标准库代码在STM32F103C8T6上设置定时器1和定时器2输出PWM的示例代码:
```c
#include "stm32f10x.h"
void TIM1_Config(void);
void TIM2_Config(void);
int main(void)
{
// 初始化定时器1和定时器2
TIM1_Config();
TIM2_Config();
// 启动定时器1和定时器2
TIM_Cmd(TIM1, ENABLE);
TIM_Cmd(TIM2, ENABLE);
while (1)
{
// 主循环
}
}
void TIM1_Config(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
// 使能定时器1和GPIOA的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1 | RCC_APB2Periph_GPIOA, ENABLE);
// 配置GPIOA的引脚为复用推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 设置定时器1的预分频值为72,计数频率为1MHz
TIM_TimeBaseStructure.TIM_Period = 1000 - 1;
TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
// 配置定时器1通道1的输出比较模式为PWM模式1
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
// 设置定时器1通道1的占空比为50%
TIM_SetCompare1(TIM1, 500);
// 使能定时器1
TIM_Cmd(TIM1, ENABLE);
}
void TIM2_Config(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
// 使能定时器2和GPIOA的时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
// 配置GPIOA的引脚为复用推挽输出
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);
// 设置定时器2的预分频值为72,计数频率为1MHz
TIM_TimeBaseStructure.TIM_Period = 1000 - 1;
TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 配置定时器2通道1的输出比较模式为PWM模式1
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
// 设置定时器2通道1的占空比为50%
TIM_SetCompare1(TIM2, 500);
// 使能定时器2
TIM_Cmd(TIM2, ENABLE);
}
```
这段代码使用定时器1和定时器2输出PWM信号,使用了GPIOA的引脚8和引脚0作为输出引脚。你可以根据实际需求修改引脚和参数的设置。
阅读全文