求一个使用定时器4驱动舵机的stmf103c8t6程序。
希望引脚能选择PB8或者PB9。
寻找已经很久了但没有找到合适的。
以下是一个使用定时器4驱动舵机的STM32F103C8T6程序,可以选择PB8或者PB9引脚来输出PWM信号:
#include "stm32f10x.h"
#define SERVO_PWM_PIN GPIO_Pin_8 // 定义舵机PWM输出引脚(这里为PB8)
//#define SERVO_PWM_PIN GPIO_Pin_9 // 如果需要使用PB9引脚,则注释掉上一行并取消该行注释即可
void TIM4_PWM_Init(uint16_t arr, uint16_t psc);
void set_servo_pwm_duty(float duty_cycle);
int main(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); // 使能GPIOB时钟
GPIO_InitStructure.GPIO_Pin = SERVO_PWM_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; // 复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
TIM4_PWM_Init(1999, 71); // 初始化TIM4定时器,设置PWM频率为50Hz,占空比精度为2000
while (1)
{
// 将舵机转到0度位置,即最左边
set_servo_pwm_duty(5.0 / 200.0); // 占空比设置为5%
// 等待舵机运动到指定角度
for (int i = 0; i < 1000000; i++);
// 将舵机转到90度位置,即中间位置
set_servo_pwm_duty(12.5 / 200.0); // 占空比设置为12.5%
// 等待舵机运动到指定角度
for (int i = 0; i < 1000000; i++);
// 将舵机转到180度位置,即最右边
set_servo_pwm_duty(20.0 / 200.0); // 占空比设置为20%
// 等待舵机运动到指定角度
for (int i = 0; i < 1000000; i++);
}
}
void TIM4_PWM_Init(uint16_t arr, uint16_t psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); // 使能TIM4时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); // 使能GPIOB时钟
GPIO_InitStructure.GPIO_Pin = SERVO_PWM_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; // 复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period = arr; // 设置自动重装载寄存器周期的值
TIM_TimeBaseStructure.TIM_Prescaler = psc; // 设置时钟频率分频系数
TIM_TimeBaseStructure.TIM_ClockDivision = 0; // 设置时钟分割
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // 向上计数模式
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure); // 初始化TIM4
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; // 配置PWM模式1
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; // OC0输出使能
TIM_OCInitStructure.TIM_Pulse = 0; // 设置初始占空比为0
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; // OC0极性为高电平
TIM_OC1Init(TIM4, &TIM_OCInitStructure); // 初始化TIM4的OC1通道
TIM_Cmd(TIM4, ENABLE); // 使能TIM4
}
void set_servo_pwm_duty(float duty_cycle)
{
uint16_t CCR = (uint16_t)(duty_cycle * 2000.0);
TIM4->CCR1 = CCR;
}
在上述程序中,我们使用了TIM4_PWM_Init()函数来初始化定时器4,该函数会将TIM4配置成PWM输出模式,并设置频率为50Hz,占空比精度为2000。我们可以通过修改set_servo_pwm_duty()函数中的参数来改变舵机的角度。例如,将参数设置为5.0 / 200.0则代表将占空比设置为5%(对应0度位置),将参数设置为12.5 / 200.0则代表将占空比设置为12.5%(对应90度位置),将参数设置为20.0 / 200.0则代表将占空比设置为20%(对应180度位置)。
注意:在使用该程序时,请务必将相关的舵机接线正确。同时,需要注意电路中的舵机和STM32的电源是否稳定,以免对硬件造成损害。