ch32v307 PWM驱动SG90舵机代码
时间: 2024-04-26 16:24:23 浏览: 134
嵌入式初学者STM32控制SG90舵机相关代码
5星 · 资源好评率100%
以下是一个使用ch32v307的PWM模块来驱动SG90舵机的示例代码:
```c
#include "ch32v30x.h"
#define PWM_PERIOD 20000 // PWM周期,单位为us
#define SERVO_MIN_PULSE 500 // 舵机最小脉宽,单位为us
#define SERVO_MAX_PULSE 2500 // 舵机最大脉宽,单位为us
void PWM_Init(void)
{
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource8, GPIO_AF_2);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1; // 分频系数
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = PWM_PERIOD - 1; // PWM周期
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Disable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Reset;
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_Cmd(TIM1, ENABLE);
}
void Servo_SetAngle(uint8_t angle)
{
uint16_t pulseWidth = SERVO_MIN_PULSE + (SERVO_MAX_PULSE - SERVO_MIN_PULSE) * angle / 180;
uint16_t pulseCnt = pulseWidth * 72 / 1000; // 将脉宽转换为计数器的值
TIM1->CCR1 = pulseCnt;
}
int main(void)
{
PWM_Init();
while (1) {
Servo_SetAngle(0); // 0度
Delay_ms(1000);
Servo_SetAngle(90); // 90度
Delay_ms(1000);
Servo_SetAngle(180); // 180度
Delay_ms(1000);
}
}
```
这个示例代码中,我们使用了ch32v307的TIM1模块来生成PWM信号,然后使用PWM信号来驱动SG90舵机。在main函数中,我们通过Servo_SetAngle函数来设置舵机的角度,该函数将角度转换为对应的脉宽值,然后将脉宽值转换为计数器的值,最后将计数器的值赋值给TIM1的CCR1寄存器,从而改变PWM信号的占空比,驱动舵机转动到对应的角度。
阅读全文