Hello World,
Is there any brave programmer who can help me with following case?
I am coding very simple robot with:
- 2 x servo 360
- one distance sensor HC SR04
I want the robot to move forward by default and when it approaches a wall it has to make backward rotation (approximately 90 degrees in random way either leftwards or rightwards), then go forward again etc. Here's the code which is almost working (robot goes forward and when it approaches a barrier he goes backward to the right):
#include <Servo.h>
const int RForward = 1350;
const int RBackward = 1650;
const int LForward = RBackward;
const int LBackward = RForward;
const int RNeutral = 1500;
const int LNeutral = 1500;
const int RSlowForward = 1450;
const int RSlowBackward = 1550;
const int LSlowForward = RSlowBackward;
const int LSlowBackward = RSlowForward;
const int dangerThresh = 80;
Servo leftMotor;
Servo rightMotor;
void setup(){
Serial.begin(9600);
rightMotor.attach(9);
leftMotor.attach(10);
}
void loop(){
int distanceFront = frontSensor();
if (distanceFront > dangerThresh || distanceFront < 0){ //sometimes the HCSR04 shows minus values...
moveForward();
}
else if (distanceFront < dangerThresh){
moveBackward();
}
}
long frontSensor()
{
pinMode (trigFront, OUTPUT);
pinMode (echoFront, INPUT);
//Front HC-SR04
int timeFront, distFront;
long duration, cm;
digitalWrite (trigFront, HIGH);
delayMicroseconds (200);
digitalWrite (trigFront, LOW);
delayMicroseconds (200);
timeFront = pulseIn (echoFront, HIGH);
distFront = (timeFront/2)/29.1;
Serial.println(distFront);
Serial.println("FRONT");
return distFront;
}
void moveForward(){
leftMotor.writeMicroseconds(LForward);
rightMotor.writeMicroseconds(RForward);
}
void moveBackward(){
** int randBack;**
** randBack = random(2);**
** Serial.print("randBack");**
** Serial.println(randBack);**
if (randBack = 0){
** leftMotor.writeMicroseconds(LBackward);**
** rightMotor.writeMicroseconds(RSlowBackward);**
}
if (randBack = 1){
** leftMotor.writeMicroseconds(LSlowBackward);**
** rightMotor.writeMicroseconds(RBackward);**
}
}
I have troubles with the highlighted section (basically the robot moves backward only in one way, disregarding the if statements and random issues...)
Anyone willing to help me?
Cheers,
Chris
P.S. You can see the robot in the shrimp_02.png file below