stm32f103使用TIM1输出PWM代码
时间: 2024-01-14 22:04:04 浏览: 65
以下是使用STM32F103的TIM1输出PWM的示例代码:
#include "stm32f10x.h"
void TIM1_PWM_Init(uint16_t period, uint16_t duty_cycle){
//使能TIM1时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
//配置TIM1的基本参数
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Prescaler = 0; //不分频
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
TIM_TimeBaseStructure.TIM_Period = period - 1; //PWM周期
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //时钟分频
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
//配置TIM1的PWM参数
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //PWM模式1
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //使能输出
TIM_OCInitStructure.TIM_Pulse = duty_cycle; //占空比
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //高电平有效
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
//启动TIM1
TIM_Cmd(TIM1, ENABLE);
}
int main(void){
//初始化GPIO引脚
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出模式
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStruct);
//初始化PWM
TIM1_PWM_Init(100, 50); //PWM周期为100,占空比为50%
while(1){
//循环执行其他任务
}
}
阅读全文