基于51单片机的红外避障+超声波避障程序
作者:互联网
最近在学习关于51单片机控制智能小车的程序,学习了很多大佬优秀的代码和思路
受到了一些启发,决定按自己的逻辑尝试一下关于红外避障+超声波避障的程序
经过实际测试,当PWM在50%左右,效果还行,但当全速前进时效果不是很理想
代码还有待改进,有些地方逻辑比较混乱,单纯只是为了能跑通,有待优化
先记录一下,毕竟也花了不少时间来写和调试
#include<reg52.H> #include "test2.h" #include <stdlib.h> sbit P22 = P2^2; sbit P23 = P2^3; sbit P24 = P2^4; sbit TRIG = P2^1; sbit ECHO = P2^0; sbit left_zhangai = P3^4; sbit right_zhangai = P3^5; unsigned char flag = 0; unsigned char i; unsigned int out_TH0, out_TL0, distance; void left_bizhang() { for (i = 0; i < 30; i++) //90 = 90 { car_left_backward(); } } void right_bizhang() { for (i = 0; i < 30; i++) //90 = 90 { car_right_backward(); } } void all_bizhang() { for (i = 0; i < 30; i++) //90 = 90 { car_right_backward(); } } void back_bizhang() { for (i = 0; i < 10; i++) car_straight_backward(); for (i = 0; i < 10; i++) car_left_backward(); } void init_time() { TMOD = 0x11; //启动0 1两个定时器 TH0 = 0; TL0 = 0; TR0 = 0; TR1 = 0; TH1 = 238; TL1 = 0; TF0 = 0; //中断溢出标志位 TF1 = 1; ET0 = 1; ET1 = 1; EA = 1; } void run() { P22 = 1; P24 = 1; left_zhangai = 1; right_zhangai = 1; TRIG = 0; // 先给控制端初始化为0 car_straight_forward_per50(); distance = 100; while(1) { ///////////////////////////// label: if (left_zhangai == 1&&right_zhangai == 1) { car_straight_forward_per50(); } else { if (left_zhangai == 0&&right_zhangai == 0) { all_bizhang(); } if (right_zhangai == 0&&left_zhangai == 1) { right_bizhang(); } if (left_zhangai == 0&&right_zhangai == 1) { left_bizhang(); } } init_time(); //初始化定时器 flag = 0; //置溢出标志位为0 //控制口发一个10US 以上的高电平 TRIG = 1; TR1 = 1; //启动定时器1 delay_10um(2); TRIG = 0; //等待接收端出现高电平 while(!ECHO) { if (TH1 == 0) { distance = 200; goto label; } }; TR0 = 1; //启动计时器 开始计时 while(ECHO) { if (TH1 == 0) { distance = 200; goto label; } }; //等待高电平结束 TR0 = 0; //关闭低电平 out_TH0 = TH0; //取定时器的值 out_TL0 = TL0; distance = (TH0*256 + TL0)*1.7/100; if (flag == 1) { flag = 0; } else if (distance >= 200) { car_straight_forward_per50(); } else if (distance <= 10) { back_bizhang(); } else if (distance <= 20) { all_bizhang(); } ///////////////////////////////////////// } } void timer0() interrupt 1 //中断函数 { flag=1; //溢出标志位置1 }
标签:避障,car,51,单片机,right,bizhang,sbit,zhangai,left 来源: https://www.cnblogs.com/s1eepDumling/p/14720220.html