机械臂共有六个舵机, 舵机通过PWM输出波形控制,波形的高电平持续时间对应旋转的角度, 实现0~180°的旋转角度,疑问:能否实现舵机旋转角度的平滑输出?
由于控制的舵机较多,所以用了TIM2、TIM3两个定时器输出六路PWM,注意调用GPIO_PinRemapConfig函数,用来开启GPIO管脚部分映射功能.配置1~4输出通道
。
硬件连接: 舵机用外置直流电源供电,注意直流电源和开发板GND要相连
TIM1的初始化配置
void Tim1_PWM_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStruct;
TIM_OCInitTypeDef TIM_OCInitStructure;
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3,ENABLE);
//定时器初始化
TIM_TimeBaseStruct.TIM_Period=20000;//初值
TIM_TimeBaseStruct.TIM_Prescaler=72;//预分频
TIM_TimeBaseStruct.TIM_ClockDivision=0;
TIM_TimeBaseStruct.TIM_CounterMode=TIM_CounterMode_Up;//向上
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStruct);
//pwm 初始化
TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_Low;
TIM_OC1Init(TIM3,&TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM3,TIM_OCPreload_Enable);
TIM_OC2Init(TIM3,&TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable);
TIM_OC3Init(TIM3,&TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM3,TIM_OCPreload_Enable);
TIM_OC4Init(TIM3,&TIM_OCInitStructure);
TIM_OC4PreloadConfig(TIM3,TIM_OCPreload_Enable);
TIM_Cmd(TIM3,ENABLE);
TIM_SetCompare1(TIM3,djsd);
TIM_SetCompare2(TIM3,djsd);
TIM_SetCompare3(TIM3,djsd);
TIM_SetCompare4(TIM3,djsd);
}
PWM输出管脚初始化
void DJ_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_4;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_Init(PWM_GPIO_Port,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_Init(PWM_GPIO_Port,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_Init(PWM_GPIO_Port,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_Init(PWM_GPIO_Port,&GPIO_InitStructure);
}
通过键盘控制舵机旋转
void DJ4_KZ_Key(void)
{
if(GPIO_ReadInputDataBit(KEY4_PORT,KEY4_PIN)==Bit_RESET)
{
djsd=1500;
TIM_SetCompare4(TIM3,djsd); //1.5ms 0 度
printf_bz=1;
while(!GPIO_ReadInputDataBit(KEY1_PORT,KEY1_PIN));
}
if(GPIO_ReadInputDataBit(KEY2_PORT,KEY2_PIN)==Bit_RESET) //右 熄灭
{
if(djfx==0) //左 反转
{
djsd=500;
djfx=1;
TIM_SetCompare4(TIM3,djsd); //0.5ms -90 度
printf_bz=1;
}
else //右 正转
{
djsd=2500;
djfx=0;
TIM_SetCompare4(TIM3,djsd); //2.5ms 90 度
printf_bz=1;
}
while(!GPIO_ReadInputDataBit(KEY2_PORT,KEY2_PIN));
}
//上 加速
if(GPIO_ReadInputDataBit(KEY3_PORT,KEY3_PIN)==Bit_RESET) //上 增加
{
if(djsd>500) djsd=djsd-500;
TIM_SetCompare4(TIM3,djsd);
printf_bz=1;
while(!GPIO_ReadInputDataBit(KEY3_PORT,KEY3_PIN));
}
//下 减速
if(GPIO_ReadInputDataBit(KEY4_PORT,KEY4_PIN)==Bit_RESET) //下 减少
{
if(djsd<2500) djsd=djsd+500;
TIM_SetCompare4(TIM3,djsd);
printf_bz=1;
while(!GPIO_ReadInputDataBit(KEY4_PORT,KEY4_PIN));
}
}
通过PAJ7620手势识别控制舵机旋转
未完待续...