STM32单片机 PWM控制 MG90S舵机
MG90S舵机图片
接线图
输出PWM波要求
输入舵机的周期为 20ms ,因此PWM频率要设置为50Hz。
PWM占空比 | 舵机状态 |
0% | 停止 |
2.5% | 顺时钟快转 |
5% | 顺时钟慢转 |
7.5% | 停止 |
10% | 逆时针慢转 |
12.5% | 逆时针快转 |
100% | 停止 |
PWM参数计算公式
代码示例
PWM.h
#include "stm32f10x.h" // Device header#ifndef __PWM_H
#define __PWM_Hvoid PWM_Init(void);
void PWM_SetCompare1(uint16_t Compare);#endif
PWM.c
#include "stm32f10x.h" // Device headervoid PWM_Init(void){RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);GPIO_InitTypeDef GPIO_InitStructure;GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOA,&GPIO_InitStructure);TIM_InternalClockConfig(TIM2);TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;TIM_TimeBaseInitStruct.TIM_Period = 20000-1; //自动重装器,ARRTIM_TimeBaseInitStruct.TIM_Prescaler = 72-1; //预分频器,PSCTIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStruct);TIM_OCInitTypeDef TIM_OCInitStruct;TIM_OCStructInit(&TIM_OCInitStruct);TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;TIM_OCInitStruct.TIM_Pulse = 0; //CCRTIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;TIM_OC1Init(TIM2,&TIM_OCInitStruct);TIM_Cmd(TIM2,ENABLE);}void PWM_SetCompare1(uint16_t Compare){TIM_SetCompare1(TIM2,Compare);}
Key.h
#include "stm32f10x.h" // Device header#ifndef __LED_H
#define __LED_Hvoid LED_Switch(uint8_t Temp);
void LED_Init(void);#endif
Key.c
#include "stm32f10x.h" // Device header
#include "Delay.h"
uint16_t KeyState = 0;
void Key_Init(void){RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);GPIO_InitTypeDef GPIO_InitStructure;GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; //上拉输入GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOB,&GPIO_InitStructure);
}uint8_t Key_GetState(void){if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1) == 1){Delay_ms(20);//消抖while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1) == 1);Delay_ms(20);KeyState += 1;}if(KeyState > 40){KeyState = 0;}return KeyState;}
main.c
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "Key.h"
#include "LED.h"
#include "Encoder.h"
#include "PWM.h"int main(void){PWM_Init();Key_Init();OLED_Init();uint16_t Key_State;while(1){Key_State = Key_GetState();PWM_SetCompare1(Key_State * 500);OLED_Printf(0,0,OLED_8X16,"%d",Key_State);OLED_Update();}
}
代码现象
按键按一下,屏幕上显示1,设置CCR为500,占空比为2.5% ,舵机顺时针快转
按键按第二下,屏幕显示2,设置CCR为1000,占空比为5%,舵机顺时针慢转