Hey guys, added more on to the robot. I got a
HC-SR04 ultrasonic sensor today so I decided to try and make an automated mode for my robot. So far, my basic automated mode works but with one problem. I would like to be able to press a button to go to and from automatic mode. This would allow the user to control the robot, or let the robot navigate by it's self, with a single button push. However, my code (shown below) currently does the following:
At start, I am able to use the remote to control the robot just fine.
I press '0' on my remote (the button that activates automation) and the robot starts doing it's own thing.
The robot now no longer responds to any button commands.
I'm sure there is something I'm just doing completely wrong so if you guys can give me any suggestions, or point out a blunder in my code I'd appreciate it!
#include <Servo.h>
#include <IRremote.h>
Servo servoLeft;
Servo servoRight;
const unsigned int RECV_PIN = 11;
const unsigned int US_OUT_PIN = 13;
const unsigned int US_IN_PIN = 12;
IRrecv irrecv(RECV_PIN);
decode_results result;
long distanceFront = 0;
int startAvoidDistance = 20;
void setup()
{
servoLeft.attach(9);
servoRight.attach(8);
irrecv.enableIRIn();
pinMode(US_OUT_PIN, OUTPUT);
}
void loop()
{
if(irrecv.decode(&result))
{
if(result.value == 800)
autoMode();
else
controlMode();
}
}
void forward()
{
servoLeft.write(180);
servoRight.write(0);
}
void reverse()
{
servoLeft.write(0);
servoRight.write(180);
}
void spinLeft()
{
servoLeft.write(0);
servoRight.write(0);
}
void spinRight()
{
servoLeft.write(180);
servoRight.write(180);
}
void stopRobot()
{
servoLeft.write(91);
servoRight.write(91);
}
unsigned long measure_distance()
{
pinMode(US_OUT_PIN, OUTPUT);
digitalWrite(US_OUT_PIN, LOW);
delayMicroseconds(2);
digitalWrite(US_OUT_PIN, HIGH);
delayMicroseconds(5);
digitalWrite(US_OUT_PIN, LOW);
pinMode(US_IN_PIN, INPUT);
duration = pulseIn(US_IN_PIN, HIGH);
return msToCentimeters(duration);
}
long msToInches(long microseconds)
{
return microseconds/74/2;
}
long msToCentimeters(long microseconds)
{
return microseconds/29/2;
}
boolean checkFront()
{
distanceFront = measure_distance();
return distanceFront > startAvoidDistance;
}
void autoMode()
{
do
{
if(checkFront() == true)
{
forward();
delay(2500);
stopRobot();
delay(1000);
checkFront();
delay(500);
irrecv.resume();
delay(25);
}
else
{
stopRobot();
delay(500);
spinLeft();
delay(500);
stopRobot();
delay(500);
checkFront();
delay(500);
irrecv.resume();
delay(25);
}
}
while(result.value == 800);
}
void controlMode()
{
switch(result.value)
{
case 802:
forward();
break;
case 808:
reverse();
break;
case 804:
spinLeft();
break;
case 806:
spinRight();
break;
case 805:
stopRobot();
break;
}
irrecv.resume();
delay(25);
}