stm32的sg90舵机代码
时间: 2023-05-30 12:01:44 浏览: 396
STM32控制sg90舵机代码.rar
以下是使用STM32控制SG90舵机的示例代码:
```
#include "stm32f10x.h"
#define PWM_GPIO_PIN GPIO_Pin_0
#define PWM_GPIO_PORT GPIOA
#define PWM_TIM TIM2
void PWM_Configuration(void);
int main(void)
{
uint16_t pulse_width = 0;
uint8_t direction = 0;
PWM_Configuration();
while(1)
{
if(direction == 0)
{
pulse_width += 10;
if(pulse_width >= 180)
{
direction = 1;
}
}
else
{
pulse_width -= 10;
if(pulse_width <= 0)
{
direction = 0;
}
}
TIM_SetCompare1(PWM_TIM, pulse_width);
for(int i=0; i<1000000; i++); //简单的延时
}
}
void PWM_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
GPIO_InitStructure.GPIO_Pin = PWM_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(PWM_GPIO_PORT, &GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period = 20000 - 1; //20ms的周期,对应50Hz的频率
TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1; //72MHz的系统时钟,预分频器设置为72,计数器时钟为1MHz
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(PWM_TIM, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_Pulse = 0; //初始占空比为0
TIM_OC1Init(PWM_TIM, &TIM_OCInitStructure);
TIM_Cmd(PWM_TIM, ENABLE);
TIM_CtrlPWMOutputs(PWM_TIM, ENABLE);
}
```
在这个示例中,我们使用了TIM2通道1来控制SG90舵机。我们设置了一个20ms的周期,对应50Hz的频率,这是SG90舵机的标准频率。然后我们按照占空比的变化来控制舵机的角度。占空比为0时,舵机转到最左边;占空比为180时,舵机转到最右边。在这个示例中,我们每次增加或减少10个计数器单位,然后等待一段简单的延时,以便我们可以看到舵机的运动。
阅读全文