STM32F407 study notes-MG90S steering gear module (basic control)
1. Basic principle:
By changing the PWM duty cycle, the steering gear can be rotated at different angles. The relationship between the rotation angle and the pulse time and the corresponding duty cycle is given below (time base pulse = 20ms).
Rotation angle | Pulse time | Compare register | Duty cycle |
---|---|---|---|
0° | 0.5ms | 195 | 2.5% |
45° | 1ms | 190 | 5% |
90° | 1.5ms | 185 | 7.5% |
135° | 2ms | 180 | 10% |
180° | 2.5ms | 175 | 12.5% |
Duty cycle calculation formula: pulse time/20ms
comparison register: 200-200*duty cycle
The code given at the end of the article only needs to change the comparison register to control the rotation angle of the steering gear.
2. Code function:
change the comparison register to control the rotation angle of the steering gear.
3. Wiring:
PA0——PWM signal wire (yellow wire), +5v——+5v (red wire), GND——GND (brown wire)
4. Code part:
SG90.h
#ifndef __SG90_H
#define __SG90_H
#include <stm32f4xx.h>
#include <delay.h>
#include "math.h"
void TIM2_PWM_Init(u32 arr,u32 psc);
#endif //__SG90_H
SG90.h
#include "sys.h"
#include "SG90.h"
void TIM2_PWM_Init(u32 arr,u32 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_PinAFConfig(GPIOA,GPIO_PinSource0,GPIO_AF_TIM2);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA,&GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Prescaler=psc;
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period=arr;
TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM2,ENABLE);
TIM_Cmd(TIM2, ENABLE);
}
main.c
#include "sys.h"
#include "HC-SR04.h"
#include "SG90.h"
#include "delay.h"
int main()
{
delay_init(168);
TIM2_PWM_Init(200-1,8400-1);
while(1)
{
delay_ms(1000);
TIM_SetCompare1(TIM2,175);
delay_ms(1000);
TIM_SetCompare1(TIM2,180);
delay_ms(1000);
TIM_SetCompare1(TIM2,185);
delay_ms(1000);
TIM_SetCompare1(TIM2,190);
delay_ms(1000);
TIM_SetCompare1(TIM2,195);
}
}
PS: This module and code can be used with gyroscope module and ultrasonic module.
Reference for this article: The principle and code of STM32 control steering gear
Only for beginners to learn and use