Hello. I am still new to programming. Have successfully programmed this bot. The idea is to move forward till too close to something.(standard) then backs up, turns whole body right, scan, turn left, scan, then decide what to do. He always seems to only decide to go left. being the last command. I feel it is the syntax or the way things are placed in the code. I will copy code to this post cause I dislike downloading more code from others. Using the NewPing.h library. Goal is to only use one sensor, and preferably no servo keeping robot low to the ground.Thank you in advance. peace.
boards arduino uno seed studio motor board and small breadboard and one HC-SR04
// code.
//obstacle avoidance, look in three direction and deciding which is the clearest way to go.
#include <NewPing.h>
#define trigPin 5
#define echoPin 6
#define MAX_DISTANCE 100
int motorPin = 12; //right motor forward
int motorPin2 = 8; //left motor forward
int motorPin3 = 13; //right motor backward
int motorPin4 = 11; //left motor backward
NewPing sonar(trigPin, echoPin, MAX_DISTANCE);
unsigned int time;
int distance;
int triggerDistance = 30;
int fDistance;
int lDistance;
int rDistance;
//
void setup()
{
Serial.begin (9600);
pinMode(motorPin, OUTPUT); //motor outputs.
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);
}
//
void loop()
{
scan();
fDistance = distance;
if(fDistance < triggerDistance){
backward();
delay(1000);
turnRight();
delay(500);
moveStop();
scan();
rDistance = distance;
turnLeft();
delay(1000);
moveStop();
scan();
lDistance = distance;
if(lDistance < rDistance){
turnRight();
delay(200);
Forward();
}
else{
Forward();
}
}
else{
Forward();
}
}
//function
void scan(){
time = sonar.ping();
distance = time / US_ROUNDTRIP_CM;
if(distance == 0){
distance = 100;
}
delay(10);
}
void Forward()
{
digitalWrite(motorPin, HIGH);
digitalWrite(motorPin2, HIGH);
analogWrite(10, 190);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
analogWrite(9, 180);
}
void backward()
{
digitalWrite(motorPin, LOW);
digitalWrite(motorPin2, LOW);
analogWrite(10, 190);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, HIGH);
analogWrite(9, 180);
}
void turnLeft()
{
digitalWrite(motorPin, HIGH);
digitalWrite(motorPin2, LOW);
analogWrite(10, 150);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
analogWrite(9, 150);
}
void turnRight()
{
digitalWrite(motorPin, LOW);
digitalWrite(motorPin2, HIGH);
analogWrite(10, 150);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
analogWrite(9, 160);
}
void moveStop()
{
digitalWrite(motorPin, LOW);
digitalWrite(motorPin2, LOW);
analogWrite(10, 190);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
analogWrite(9, 190);
}