舵机mg995和mg90s
时间: 2023-10-24 07:08:49 浏览: 216
以下是使用STM32控制MG995和MG90S舵机的示例代码:
```
#include "stm32f10x.h"
#include "delay.h"
void TIM3_PWM_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); //使能定时器3时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); //使能GPIOB时钟
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1; //TIM3_CH3、TIM3_CH4
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 = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //选择定时器模式:TIM脉冲宽度调制模式1
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;//比较输出使能
TIM_OCInitStructure.TIM_Pulse = 0; //设置待装入捕获比较寄存器的脉冲值
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性:TIM输出比较极性高
TIM_OC3Init(TIM3, &TIM_OCInitStructure); //根据T指定的参数初始化外设TIM3 OC3
TIM_OC4Init(TIM3, &TIM_OCInitStructure); //根据T指定的参数初始化外设TIM3 OC4
TIM_Cmd(TIM3, ENABLE); //使能定时器3
TIM_SetCompare3(TIM3,1500); //MG995中位
TIM_SetCompare4(TIM3,1500); //MG90S中位
}
void MG995_SetAngle(u16 angle)
{
u16 value = (u16)(angle*(2000.0/180.0) + 500); //根据角度计算占空比
TIM_SetCompare3(TIM3,value);
}
void MG90S_SetAngle(u16 angle)
{
u16 value = (u16)(angle*(1000.0/180.0) + 500); //根据角度计算占空比
TIM_SetCompare4(TIM3,value);
}
int main(void)
{
u16 i;
delay_init(); //延时初始化
TIM3_PWM_Init(20000,71); //PWM频率为50Hz
while(1)
{
for(i=0;i<=180;i++) //MG995舵机旋转0~180度
{
MG995_SetAngle(i);
delay_ms(20);
}
delay_ms(1000);
for(i=0;i<=180;i++) //MG90S舵机旋转0~180度
{
MG90S_SetAngle(i);
delay_ms(20);
}
delay_ms(1000);
}
}
```
在代码中,TIM3_PWM_Init()函数用于初始化定时器3和GPIO口,其中arr和psc参数用于设置PWM的频率,MG995_SetAngle()和MG90S_SetAngle()函数用于设置舵机的转动角度,delay_ms()函数用于延时。在main()函数中,通过调用MG995_SetAngle()和MG90S_SetAngle()函数,可以控制舵机旋转到指定的角度。
注意:以上代码仅供参考,具体实现可能需要根据舵机和控制器的型号进行调整。
阅读全文