this is the whole code
#include <AFMotor.h>
AF_DCMotor motor1(1, MOTOR12_64KHZ);
AF_DCMotor motor2(2, MOTOR12_64KHZ);
AF_DCMotor motor3(3, MOTOR12_1KHZ);
AF_DCMotor motor4(4, MOTOR12_1KHZ);
#define trigPin 8
#define echoPin 9
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
motor1.setSpeed(200); // Set the speed for the motors (255 is the maximum)
motor2.setSpeed(200);
motor3.setSpeed(200);
motor4.setSpeed(200);
}
void forward(){ // This function moves the wheels forward
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
}
void backward() { // This function moves the wheels backward
motor1.run(BACKWARD);
motor2.run(BACKWARD);
motor3.run(BACKWARD);
motor4.run(BACKWARD);
}
void haltMotors() // This function stops each motor (It is better to stop the motors before changing direction.)
{
motor1.run(RELEASE);
motor2.run(RELEASE);
motor3.run(RELEASE);
motor4.run(RELEASE);
}
void turnRight(){ // This function turns the robot right.
motor1.run(FORWARD);
motor2.run(BACKWARD);
motor3.run(BACKWARD);
motor4.run(FORWARD);
}
void turnLeft(){
motor1.run(BACKWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(BACKWARD);
}
float ping() {
int duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
return distance;
}
void loop(){
long time, distance;
distance=ping();
Serial.print(distance);
Serial.print("cm");
Serial.println();
if (distance >=10){
turnRight();
}
if (distance <10){
forward();}
}