So I can get my code to run a motor at greater than 20 cm and not run at less than 20 cm the problem is that if the sensor can't read a distance because it is to far away it returns 0 as the distance. I am trying to get the motor to run then at 0 and at greater than 20 but with no luck. Here is my latest try which ended up still turning the motor off at 0 which I think is because the first if statement just cancels out the left else if statement. Is there a way to set it to turn off for an interval of distance?
#include <NewPing.h>
#define TRIGGER_PIN 11
#define ECHO_PIN 12
#define MAX_DISTANCE 50 //max distance to ping for
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
const int rightMotor1 = 6;
const int rightMotor2 = 7;
const int enablePin = 9;
void setup()
{
Serial.begin(9600);
pinMode(rightMotor1, OUTPUT);
pinMode(rightMotor2,OUTPUT);
pinMode(enablePin, OUTPUT);
digitalWrite(enablePin, LOW);
}
void loop()
{
delay(50);
unsigned int uS = sonar.ping();
int distance = sonar.ping_cm();
Serial.print("Ping: ");
Serial.print(uS / US_ROUNDTRIP_CM);
Serial.println("cm");
if(distance < 20)
{
digitalWrite(enablePin, LOW);
}
else if(distance > 20)
{
digitalWrite(enablePin, HIGH);
digitalWrite(rightMotor1, HIGH);
digitalWrite(rightMotor2, LOW);
}
else if(distance == 0)
{
digitalWrite(enablePin, HIGH);
digitalWrite(rightMotor1, HIGH);
digitalWrite(rightMotor2, LOW);
}
}