尽管获得了正确的值,但IR障碍传感器仍未执行代码

时间:2017-11-30 14:46:11

标签: c++ arduino-uno

我们正在学校做一个项目,我们应该制造一个自动机器人,在游乐场上搜寻另一个机器人并尝试将其推离棋盘。电路板周围有一个黑色圆圈,其他部分是白色的。 搜索功能正常工作,并将对象从板上推开。 然而,IR传感器发现它已达到黑色边缘的事实,但是当它执行时应该运行的代码不会执行。我已经尝试了不同的层次结构,在if语句中哪个控件首先出现但似乎没有任何效果。

#include <NewPing.h>
#define TRIGGER_PIN  14
#define ECHO_PIN     15
#define MAX_DISTANCE 70

NewPing DistanceSensor(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;
// IR-sensor
int obstaclePin = 4;  
int hasObstacle = HIGH; // HIGH MEANS NO OBSTACLE

void setup()
{
  // set IR-sensor pin to input
  pinMode(obstaclePin, INPUT);
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
  Serial.begin(9600);
}
void driveFwd() {
  // turn on motor A
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  // turn on motor B
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 255);
  analogWrite(enB, 255);
}

void driveBwd() {
  // now change motor directions
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);  
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW); 
  analogWrite(enA, 255);
  analogWrite(enB, 255);
}

void driveStop() {
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}

void driveTurn() {
  //Motor A, forward
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  //Motor B, backward
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  //Turn on full speed
  analogWrite(enA, 255);
  analogWrite(enB, 255);
}

void loop()
{
  unsigned int cm = DistanceSensor.ping_cm();

 //Main code for the behaviors depending on information from the IR- and distance sensor

 if (cm == 0) {
   driveTurn();
 }
 else if (cm > 0) {
   driveFwd();      
 }
 else if (hasObstacle == HIGH) {
   driveStop();
   while (hasObstacle == HIGH) {
     driveBwd();
   }
 }   
}

0 个答案:

没有答案