问题遇到的现象和发生背景
HAL库制作STM32红外避障小车见到障碍物反而变快了?
问题相关代码,请勿粘贴截图
函数的定义
//红外避障
/*
右避障 VOID_R_PIN PC7
左避障 VOID_L_PIN PG2
*/
#define VOID_R_PIN GPIO_PIN_7
#define VOID_R_GPIO GPIOC
#define VOID_R_IO HAL_GPIO_ReadPin(VOID_R_GPIO, VOID_R_PIN)
#define VOID_L_PIN GPIO_PIN_2
#define VOID_L_GPIO GPIOG
#define VOID_L_IO HAL_GPIO_ReadPin(VOID_L_GPIO, VOID_L_PIN)
#define BARRIER_Y 0 //有障碍物
#define BARRIER_N 1 //无障碍物
//指令定义
#define COMM_STOP 'I'//停止
#define COMM_UP 'A'//前进
#define COMM_DOWN 'B'//后退
#define COMM_LEFT 'C'//左转
#define COMM_RIGHT 'D'//右转
GetVoidStatus函数
extern char ctrl_comm;
//获取红外避障模块状态
char GetVoidStatus(void)
{
char left=0,right=0;
char count;
if(VOID_L_IO == BARRIER_Y)
{
count = 2;
while(--count)//10ms 采集2次均要采集到前面障碍物信息,滤波
{
if(VOID_L_IO == BARRIER_N)
break;
HAL_Delay(1000);
}
if(count == 0)
{
left = 1;
ctrl_comm = COMM_RIGHT;CarBack(); HAL_Delay(500); CarLeft(); DelayCheck(500);
}
}
if(VOID_R_IO == BARRIER_Y)
{
count = 2;
while(--count)//10ms 采集2次均要采集到前面障碍物信息,滤波
{
if(VOID_R_IO == BARRIER_N)
break;
HAL_Delay(1000);
}
if(count == 0) right = 2;
}
return left + right;
}
VoidRun函数
//延时的同时检测红外,一旦发生障碍物,就停止并跳出延时
void DelayCheck(int ms)
{
while(ms--)
{
HAL_Delay(1);
if(VOID_NONE != GetVoidStatus())
{
CarStop();
return;
}
}
}
//红外避障处理
//处理方式:左边检测到 后退500ms 右转500ms
// 右边检测到 后退500ms 左转500ms
// 两边检测到 后退700ms 右转500ms
// 没检测到 直行
void VoidRun(void)
{
char status;
status = GetVoidStatus();
switch(status)
{
case VOID_LEFT:
ctrl_comm = COMM_RIGHT;CarBack(); HAL_Delay(500); CarLeft(); DelayCheck(500);
break;
case VOID_RIGHT:
ctrl_comm = COMM_LEFT;CarBack(); HAL_Delay(500); CarRight(); DelayCheck(500);
break;
case VOID_BOTH:
ctrl_comm = COMM_RIGHT;CarBack(); HAL_Delay(700); CarRight(); DelayCheck(500);
break;
case VOID_NONE:
ctrl_comm = COMM_UP;CarGo();
break;
default: break;
}
}
main.c里的函数
while (1)
{
/* USER CODE END WHILE */
if(tick_5ms >= 5)
{
tick_5ms = 0;
tick_200ms++;
if(tick_200ms >= 40)
{
tick_200ms = 0;
HAL_GPIO_TogglePin(LED_GPIO,LED_PIN);
}
VoidRun();
}
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
运行结果及报错内容
遇到障碍物反而加快速度了
我的解答思路和尝试过的方法
我想要达到的结果