1.硬件
- STM32单片机最小系统
- SG90舵机模块
2.软件
- sg90驱动文件添加
- main.c程序
#include "sys.h"
#include "delay.h"
#include "led.h"
#include "sg90.h"int main(void)
{HAL_Init(); /* 初始化HAL库 */stm32_clock_init(RCC_PLL_MUL9); /* 设置时钟, 72Mhz */led_init(); /* 初始化LED灯 */sg90_init();// uint16_t i = 0;while(1){ sg90_angle_set(0);delay_ms(1000);sg90_angle_set(20);delay_ms(1000);sg90_angle_set(40);delay_ms(1000);sg90_angle_set(90);delay_ms(1000);sg90_angle_set(180);delay_ms(1000);
// for(i = 5; i <= 25; i++)//数1个数的时间是100us即0.1ms,0.5ms对应0°即数5个数
// {
// tim3_compare_set(i);
// delay_ms(100);
// }
//
// for(i = 5; i <= 25; i++)
// {
// tim3_compare_set(30 - i);
// delay_ms(100);
// }
// led1_on();
// led2_off();
// delay_ms(500);
// led1_off();
// led2_on();
// delay_ms(500);}
}
- sg90.c程序
#include "sg90.h"TIM_HandleTypeDef tim3_handle = {0};
// init函数
void tim3_init(void)
{TIM_OC_InitTypeDef pwm_config = {0};tim3_handle.Instance = TIM3;tim3_handle.Init.Prescaler = 7200 - 1;//psc (20ms)tim3_handle.Init.Period = 200 - 1;//arrtim3_handle.Init.CounterMode = TIM_COUNTERMODE_UP;HAL_TIM_PWM_Init(&tim3_handle);pwm_config.OCMode = TIM_OCMODE_PWM1;//PWM模式1pwm_config.Pulse = 100;//arr/2pwm_config.OCPolarity = TIM_OCPOLARITY_HIGH;//高电平极性HAL_TIM_PWM_ConfigChannel(&tim3_handle, &pwm_config, TIM_CHANNEL_1);//PWM接PA6,定时器3通道1HAL_TIM_PWM_Start(&tim3_handle, TIM_CHANNEL_1);
}//msp函数
void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim)
{if(htim->Instance == TIM3){GPIO_InitTypeDef gpio_initstruct;//打开时钟__HAL_RCC_GPIOA_CLK_ENABLE(); // 使能GPIOA时钟__HAL_RCC_TIM3_CLK_ENABLE();//调用GPIO初始化函数gpio_initstruct.Pin = GPIO_PIN_6; // PA6gpio_initstruct.Mode = GPIO_MODE_AF_PP; // 推挽输出gpio_initstruct.Pull = GPIO_PULLUP; // 上拉gpio_initstruct.Speed = GPIO_SPEED_FREQ_HIGH; // 高速HAL_GPIO_Init(GPIOA, &gpio_initstruct);}
}//修改CCR值的函数
void tim3_compare_set(uint16_t val)//生成PWM波
{__HAL_TIM_SET_COMPARE(&tim3_handle, TIM_CHANNEL_1, val);
}void sg90_init(void)
{tim3_init();
}void sg90_angle_set(uint16_t angle)
{uint16_t CCRx = (1.0 / 9.0) * angle + 5.0;tim3_compare_set(CCRx);
}
- sg90.h程序
#ifndef __SG90_H__
#define __SG90_H__#include "sys.h"void sg90_init(void);
void sg90_angle_set(uint16_t angle);#endif
3.实物效果
- 硬件模块接线
SG90 | STM32 |
---|---|
PWM | PA6 |
VCC | 5V |
GND | GND |
ST-Link下载方式
- 实验现象