基于stm32的红外避障模块和舵机sg90代码
时间: 2023-10-09 20:15:56 浏览: 31
以下是基于STM32的红外避障模块和舵机SG90代码,其中红外避障模块使用的是TCRT5000,舵机使用的是TIM3通道1输出PWM信号控制。
```
#include "stm32f10x.h"
#include "delay.h"
#define IR_PORT GPIOA
#define IR_PIN GPIO_Pin_0
#define SERVO_PORT GPIOA
#define SERVO_PIN GPIO_Pin_6
void IR_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = IR_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(IR_PORT, &GPIO_InitStructure);
}
void Servo_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_OCInitTypeDef TIM_OCInitStruct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = SERVO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(SERVO_PORT, &GPIO_InitStructure);
TIM_TimeBaseInitStruct.TIM_Period = 20000 - 1;
TIM_TimeBaseInitStruct.TIM_Prescaler = 72 - 1;
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_Pulse = 1500;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStruct);
TIM_Cmd(TIM3, ENABLE);
}
void Servo_SetAngle(int angle)
{
uint16_t pulse = (uint16_t)(angle * 10.0 + 500);
TIM_SetCompare1(TIM3, pulse);
}
int main(void)
{
IR_Init();
Servo_Init();
while(1)
{
if(GPIO_ReadInputDataBit(IR_PORT, IR_PIN) == 0)
{
Servo_SetAngle(0);
Delay_ms(1000);
Servo_SetAngle(90);
Delay_ms(1000);
Servo_SetAngle(180);
Delay_ms(1000);
}
}
}
```