/* 存在问题随机行走时,红外无法避障
-----------------------------------------*/
int hzuo = 12; //左方红外传感器
int hyou = 13; //右方红外传感器
int left, right; //定义两个变量存储传感器返回值
int AIN1 = 14; //Direction
int AIN2 = 15; //Direction
int BIN1 = 16; //Direction
int BIN2 = 17; //Direction
long randNumber;//定义长整型随机数
void setup()
{
Serial.begin(9600);
pinMode(AIN1, OUTPUT);
pinMode(AIN2, OUTPUT);
pinMode(BIN1, OUTPUT);
pinMode(BIN2, OUTPUT);
pinMode(hzuo, INPUT);
pinMode(hyou, INPUT);
randomSeed(analogRead(0)); //随机引脚0
}
void loop() {
/* 红外避障功能----------------------------------------------------------------------------------- */
left = digitalRead(hzuo);
right = digitalRead(hyou);
/* 当右传感器检测到障碍物时 */
if (left == HIGH && right == LOW) //左边高电位
{
szuo(); //左转
}
/* 当左传感器检测到障碍物时 */
else if (left == LOW && right == HIGH) //右边高电位
{
syou(); //右转
}
/* 当都没有 */
else if (left == HIGH && right == HIGH) //右边高电位
{
sqian(); //前进
}
/* 当都测到障碍物时 */
else if (left == LOW && right == LOW) //都处于低电位
{
shoutui(); //后退
}
/* 随机行走算法----------------------------------------------------------------------------------- */
Serial.print("random1=");//取一个随机数300个
randNumber = random(301);//总数301个,因为从0计算
Serial.println(randNumber); // print a random number from 0 to 300
if ( randNumber <= 80) //左转
{
zuo();
delay(800);
}