When i run a test code in Newping library for ultrasonic sensor SR04 then in works properly but when i run the actual code for obstacle avoiding robot then it shows 0 cm everytime. This means that wiring is correct but there is something wrong in my code below
#include <NewPing.h>
#include <AFMotor.h> //import your motor shield library
#define TRIGGER_PIN 12
#define ECHO_PIN 11
#define MAX_DISTANCE 200
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
AF_DCMotor motor1(1, MOTOR12_64KHZ); // set up motors.
AF_DCMotor motor2(2, MOTOR12_8KHZ);
int distance;
void setup() {
Serial.begin(115200);
}
void loop() {
delay(50);
distance = sonar.ping_cm(); // start the scan
delay(20);
if (distance < 2) {
Serial.println("Close Obstacle detected!" );
Serial.println("Obstacle Details:");
Serial.print("Distance From Robot is " );
Serial.print(distance);
Serial.print( " CM!");// print out the distance in centimeters.
delay(10);
Serial.println (" The obstacle is declared a threat due to close distance. ");
Serial.println (" Turning !");
motor1.run(FORWARD); // Turn as long as there's an obstacle ahead.
motor2.run(BACKWARD);
}
else {
Serial.println("No obstacle detected. going forward");
delay(15);
motor1.run(FORWARD); //if there's no obstacle ahead, Go Forward!
motor2.run(FORWARD);
}
}
Test code for sensor which worked:-
#include <NewPing.h>
#define TRIGGER_PIN 12
#define ECHO_PIN 11
#define MAX_DISTANCE 200
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(115200);
}
void loop() {
delay(50);
Serial.print("Ping: ");
Serial.print(sonar.ping_cm());
Serial.println("cm");
}
Tell me whats wrong here
Motor Shield used below Wiring of sensor is connected to Arduino below the shield
if-else
loop withSerial.print(distance);
.... what does it print now?