i am stuck once again i can't seem to figure out why my motors will activate when the ping reads closer than danger threshold, however it will not execute/motors won't activate in the next part of code when the sensor or ping reads farther than danger threshold. what i am attempting to build is an obstacle avoidance rover. if you have any ideas it would greatly appreciated..... XD
here is my code:
int pingPin = 11; //pin for ultrasound sensor
long duration; //time it takes to recieve PING signal
int dangerThresh = 10; //threshold for obstacles (in cm)
int E1 = 5; //E1: PWM control for Motor1
int M1 = 4; //M1: Direction for Motor1 pin 4
int E2 = 6; //E2: PWM control for Motor2
int M2 = 7; //M2: Direction for Motor2 pin 7
void setup()
{
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);
}
void loop()
{
int distanceFwd = ping();
if (distanceFwd<dangerThresh) //if path is blocked
{
digitalWrite(M1,HIGH);
digitalWrite(M2, LOW);
analogWrite(E1, 80); //PWM Speed Control
analogWrite(E2,100); //PWM Speed Control
}
else if (distanceFwd>dangerThresh)//if path is clear
{
digitalWrite(M1,HIGH);
digitalWrite(M2, HIGH);
analogWrite(E1, 150); //PWM Speed Control
analogWrite(E2, 150); //PWM Speed Control
}
}
long ping()
{
// Send out PING))) signal pulse
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
//Get duration it takes to receive echo
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
//Convert duration into distance
//return duration / 74 / 2; //inches
return duration / 29 / 2; // centimeters
}