Im doing a school project, where we make a robot that is supposed to be able to find its way around a room. We have run into a wall that we have been trying to climb for days with this sensor.
#include <Servo.h>
#include<AFMotor.h>
// Declare classes for Servo connectors of the MotorShield.
Servo servo_1;
Servo servo_2;
const int Trig = 8;
const int Echo = 10;
const int PWR = 6;
const int Close= 5;
int distance;
AF_DCMotor MotorL(1);
AF_DCMotor MotorR(4);
void setup() {
//start motors
MotorL.setSpeed(200);
MotorL.run(RELEASE);
MotorR.setSpeed(200);
MotorL.run(RELEASE);
pinMode(Trig, OUTPUT);
pinMode(Echo, INPUT);
pinMode(0, OUTPUT);
Serial.begin(9600);
}
void loop() {
delay(1000);
digitalWrite(PWR, HIGH);
Think();
}
void Think(){
int turn;
int D = Get_Distance();
if (D >= Close){
turn = random(1,2);
if (turn == 1){
MotorL.run(RELEASE);
MotorL.run(FORWARD);
MotorR.run(RELEASE);
MotorR.run(BACKWARD);
//motor right backward
}
else if(turn == 2){
MotorL.run(RELEASE);
MotorL.run(BACKWARD);
MotorR.run(RELEASE);
MotorR.run(FORWARD);
//motor left forward
}
}
else if (D <= Close|| D == 0){
MotorL.run(RELEASE);
MotorL.run(FORWARD);
MotorR.run(RELEASE);
MotorR.run(FORWARD);
//motor left forward
//motor left backward
}
}
int Get_Distance(){
long duration;
digitalWrite(Trig, LOW);
delayMicroseconds(2);
digitalWrite(Trig, HIGH);
delayMicroseconds(10);
digitalWrite(Trig, LOW);
duration = pulseIn(Echo, HIGH);
delayMicroseconds(10);
distance = duration*0.034/2;
Serial.begin(9600);
Serial.print(distance);
Serial.print("\n");
return(distance);
}
the serial monitor is only out putting either 0 or 59, but mostly 59
I'm not sure why you have any code to use distance when you are having problems getting distance.
I don't see any differences between the code that was outputting somewhat reasonable data and the code that is outputting all 0's. That suggests that you have a hardware problem.
Why does the Get_Distance() function return the value in a global variable?
Why does it return anything, when you don't care what the returned value is?