I must have bought the crappy ones because when it reads out of range it stops working, when it reads in range for too long it stops working, and when cycling the power with a relay the problem still persists. My code is below, and this is my second project after the line following robot, so don't expect anything fancy in the code. (D8 is the relay)
#include <Servo.h>
#include <NewPing.h>
#define TRIGGER_PIN 12
#define ECHO_PIN 11
#define MAX_DISTANCE 400
Servo left;
Servo right;
Servo head;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
int leftDistance = 0;
int frontDistance = 0;
int rightDistance = 0;
int val = 0;
void setup() {
// put your setup code here, to run once:
head.attach(6);
left.attach(10);
right.attach(9);
Serial.begin(115200);
left.write(90);
right.write(90);
head.write(90);
pinMode(8,OUTPUT);
scan();
}
void loop() {
head.write(90);
delay(10);
logic();
}
void scan() {
digitalWrite(8, LOW);
delay(100);
left.write(90);
right.write(90);
head.write(90);
digitalWrite(8,HIGH);
delay(2000);
val = sonar.ping();
if(val > 1){
frontDistance = val;
}
else {
digitalWrite(8, LOW);
frontDistance = 20000;
delay(100);
}
delay(100);
head.write(180);
digitalWrite(8,HIGH);
delay(2000);
val = sonar.ping();
if(val > 1){
rightDistance = val;
}
else {
rightDistance = 20000;
digitalWrite(8, LOW);
delay(100);
}
delay(100);
head.write(0);
digitalWrite(8,HIGH);
delay(2000);
val = sonar.ping();
if(val > 1){
leftDistance = val;
}
else {
leftDistance = 20000;
digitalWrite(8, LOW);
delay(100);
}
digitalWrite(8,HIGH);
}
void turnRight() {
left.write(180);
right.write(180);
delay(1500);
left.write(90);
right.write(90);
}
void turnLeft() {
left.write(0);
right.write(0);
delay(1500);
left.write(90);
right.write(90);
}
void goForward() {
left.write(180);
right.write(0);
delay(1000);
}
void logic(){
digitalWrite(8, LOW);
delay(1000);
digitalWrite(8,HIGH);
delay(1000);
frontDistance = sonar.ping();
if(frontDistance < 500) {
goForward();
}
else {
scan();
if(rightDistance >= leftDistance){
turnRight();
}
else {
turnLeft();
}
}
}