c51红外循迹避障小车代码
时间: 2023-11-19 17:07:18 浏览: 226
以下是c51红外循迹避障小车的代码:
```c
//头文件
#include <reg52.h>
#include <intrins.h>
#include "delay.h"
#include "lcd1602.h"
#include "ir.h"
#include "motor.h"
#include "ultrasonic.h"
//宏定义
#define uchar unsigned char
#define uint unsigned int
//函数声明
void init();
void display();
//全局变量
uchar mode = 0; //模式选择
uchar speed = 50; //小车速度
uchar distance = 0; //超声波距离
//主函数
void main()
{
init(); //初始化
while(1)
{
display(); //显示信息
switch(mode)
{
case 0: //循迹模式
if(ir() == 0x1c) //左1右1
left_forward(speed);
else if(ir() == 0x18) //左0右1
left_forward(speed/2), right_stop();
else if(ir() == 0x1e) //左1右0
left_stop(), right_forward(speed/2);
else if(ir() == 0x0c) //左0右0
left_backward(speed/2), right_forward(speed/2);
else if(ir() == 0x1d) //左1右2
left_forward(speed/2), right_backward(speed);
else if(ir() == 0x19) //左2右1
left_backward(speed), right_forward(speed/2);
else if(ir() == 0x1f) //左2右2
left_stop(), right_stop();
break;
case 1: //避障模式
if(ultrasonic() < 30) //前方有障碍物
left_backward(speed), right_forward(speed), delay_ms(500);
else //前方无障碍物
left_forward(speed), right_forward(speed);
break;
}
}
}
//初始化函数
void init()
{
lcd_init(); //LCD1602初始化
ir_init(); //红外循迹初始化
motor_init(); //电机初始化
ultrasonic_init(); //超声波初始化
}
//显示函数
void display()
{
lcd_write_string(0, 0, "Mode: ");
lcd_write_string(6, 0, mode == 0 ? "Track" : "Avoid");
lcd_write_string(0, 1, "Speed: ");
lcd_write_data(speed/10 + '0');
lcd_write_data(speed%10 + '0');
lcd_write_string(6, 1, "Dist: ");
distance = ultrasonic();
lcd_write_data(distance/10 + '0');
lcd_write_data(distance%10 + '0');
}
--相关问题--:
阅读全文