Hey, Iv'e been working on a robot, I've been trying to get it to find its way through a maze with a Ping sensor. Now I only have one mounted on the front so I want to go forward check if its less than 4 cm. If it is I want it to turn right and check again. If it reads less than 4 cm again do a 180 and go strait and repeat. Heres the code I came up with:
const int leftMotor = 10;
const int rightMotor = 5;
const int pingPin = 7;
const int ledPin = 12;
void setup() {
pinMode(rightMotor, OUTPUT);
pinMode(leftMotor, OUTPUT);
}
void loop()
{
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
if(cm<4) {
digitalWrite(ledPin, HIGH);
digitalWrite(leftMotor, HIGH);
digitalWrite(rightMotor, LOW);
delay(575);
digitalWrite(leftMotor, LOW);
digitalWrite(rightMotor, LOW);
} else {
digitalWrite(ledPin, LOW);
digitalWrite(leftMotor, HIGH);
digitalWrite(rightMotor, HIGH);
}
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
if(cm<4) {
digitalWrite(leftMotor, HIGH);
digitalWrite(rightMotor, LOW);
delay(1150);
digitalWrite(leftMotor, HIGH);
digitalWrite(rightMotor, HIGH);
} else {
digitalWrite(leftMotor, HIGH);
digitalWrite(rightMotor, HIGH);
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
Now I keep getting errors like; redeclaration of 'long int duration' and a function definition is not allowed before '{' token. I would like some help striating out my program, oh but please don't just fix my problems tell me why you did what you did so I can learn.
Thanks
oh by the way delay(575); is the time it takes my robot to do a 90 degree turn