What is wrong with the below code? It is suppose to see if there is an object infront of it using a HC-SR04, if there is turn 90degrees. If not, drive forward. yet it just spins in circles...
/*
This program is adapted from the example Ping code from Arduino.
*/
//pin which triggers ultrasonic sound
const int pingPin = 8;
//pin which delivers time to receive echo using pulseIn()
int inPin = 7;
//range in cm which is considered safe to enter, anything
//coming within less than 5 cm triggers m2f, m1b in order to turn 90degrees.
int safeZone = 5;
//LED pin numbers
//int greenLed = 3, redLed = 2;
void setup() {
// initialize serial communication
Serial.begin(9600);
pinMode(5, OUTPUT);
pinMode(3, OUTPUT);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
#define m1f 9
#define m2f 6
#define m1b 3
#define m2b 5
}
void loop()
{
//raw duration in milliseconds, cm is the
//converted amount into a distance
long duration, cm;
//setting up the input pin, and receiving the duration in
//microseconds for the sound to bounce off the object infront
pinMode(inPin, INPUT);
duration = pulseIn(inPin, HIGH);
// convert the time into a distance
cm = microsecondsToCentimeters(duration);
//printing the current readings to ther serial display
Serial.print(cm);
Serial.print("cm");
Serial.println();
//checking if anything is within the safezone, if not, keep
//going forwards if safezone violated, turn 90degrees
if (cm > safeZone)
{
digitalWrite(m1f, HIGH);
digitalWrite(m2f, HIGH);
}
else
{
digitalWrite(m1b, HIGH);
digitalWrite(m2f, HIGH);
delay(200);
digitalWrite(m1b, LOW);
digitalWrite(m2f, LOW);
}
delay(100);
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}