硬件准备:stm32,两个舵机
舵机pwm波形输出,使用TIM2中的两个通道进行输出。
pwm.c
#include "stm32f10x.h" // Device header
void PWM_Init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1|GPIO_Pin_0;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM_InternalClockConfig(TIM2);
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_Period = 20000 - 1; //ARR
TIM_TimeBaseInitStructure.TIM_Prescaler = 72 - 1; //PSC
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure);
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCStructInit(&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0; //CCR
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
TIM_OC2Init(TIM2, &TIM_OCInitStructure);
TIM_Cmd(TIM2, ENABLE);
}
void PWM_SetCompare2(uint16_t Compare)
{
TIM_SetCompare2(TIM2, Compare);
}
void PWM_SetCompare1(uint16_t Compare)
{
TIM_SetCompare1(TIM2, Compare);
}
pwm,h
#ifndef __PWM_H
#define __PWM_H
void PWM_Init(void);
void PWM_SetCompare1(uint16_t Compare);
void PWM_SetCompare2(uint16_t Compare);
#endif
为了更加直观的使用,用Servo函数对pwm输出占空比与舵机旋转角度进行封装。
Servo,c
#include "stm32f10x.h" // Device header
#include "PWM.h"
void Servo_Init(void)
{
PWM_Init();
}
void Servo_SetAngle2(float Angle2)
{
PWM_SetCompare2(Angle2 / 180 * 2000 + 500);
}
void Servo_SetAngle1(float Angle1)
{
PWM_SetCompare1(Angle1 / 180 * 2000 + 500);
}
Servo,h
#ifndef __SERVO_H
#define __SERVO_H
void Servo_Init(void);
void Servo_SetAngle1(float Angle1);
void Servo_SetAngle2(float Angle2);
#endif
主函数
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "PWM.h"
#include "Key.h"
#include "Servo.h"
uint8_t KeyNum;
float Angle1,Angle2;
int main(void)
{
Servo_Init();
Key_Init();
Serial_Init();
while (1)
{
if( KeyNum == 1 )
{
Angle1+=30;
if(Angle1>180)
{
Angle1 = 0;
Delay_ms(50);
}
Servo_SetAngle1(Angle1);
break;
}
if(KeyNum == 2 )
{
Angle2+=30;
if(Angle2>180)
{
Angle2 = 0;
Delay_ms(50);
}
Servo_SetAngle2(Angle2);
break;
}
}
}
同时分享一位大佬的视频,我也是跟着他学习,一步一步总结的。文章来源:https://www.toymoban.com/news/detail-635806.html
https://www.bilibili.com/video/BV1th411z7sn/?spm_id_from=333.1007.top_right_bar_window_custom_collection.content.click文章来源地址https://www.toymoban.com/news/detail-635806.html
到了这里,关于stm32同时控制两个舵机的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!