stm32f103c8t6用定时器2同时用中断和通道3输出舵机pwm
时间: 2023-12-18 12:05:25 浏览: 101
用STM32F103C8t6输出多路PWM信号控制多路舵机(标准库)
首先,你需要配置定时器2来产生PWM信号,配置方法如下:
1. 开启定时器2时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
2. 设置定时器2的基本参数
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 20000-1; //设置自动重装载寄存器的值,20000为PWM周期,单位为us
TIM_TimeBaseStructure.TIM_Prescaler = 72-1;//设置时钟频率分频系数,72为APB1的时钟频率,单位为MHz
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //设置计数器计数模式为向上计数
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); //初始化TIM2
3. 配置通道3输出PWM信号
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //设置PWM模式
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //使能输出
TIM_OCInitStructure.TIM_Pulse = 1000; //设置占空比,1000为初始占空比,单位为us
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //设置极性为高电平
TIM_OC3Init(TIM2, &TIM_OCInitStructure); //初始化TIM2的通道3
4. 配置定时器2中断
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn; //选择TIM2中断通道
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //设置抢占优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //设置子优先级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //使能中断
NVIC_Init(&NVIC_InitStructure); //初始化NVIC
5. 启动定时器2
TIM_Cmd(TIM2, ENABLE); //启动定时器2
6. 在中断处理函数中修改占空比
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET) //检查更新中断是否发生
{
TIM_SetCompare3(TIM2, 1500); //修改占空比为1500us
TIM_ClearITPendingBit(TIM2, TIM_IT_Update); //清除更新中断标志位
}
}
这样就可以同时使用定时器2中断和通道3输出PWM信号了。注意,这里的占空比是以us为单位的,需要根据你的舵机规格来调整占空比的值。
阅读全文