Alright, I apologise again, not really experienced with how the questions and threads work, so here is the additional info:
I am using Deek-Robot Motor Shield L298P
Arduino is powered from a 9V rechargable battery, it is connected directly to the Motor Shield.
Motors are connected to the Motor Shield as well, more precisely through the A+/A- and B+/B- pins specified for the motors, so nothing is directly connected to Arduino.
The code is very simple:
#include <NewPing.h>
const int DirMotorA = 12;
const int SpeedMotorA = 3;
const int BrakeMotorA = 9;
const int DirMotorB = 13;
const int SpeedMotorB = 11;
const int BrakeMotorB = 8;
const int Clockwise = HIGH;
const int CClockwise = LOW;
#define trig_pin A1
#define echo_pin A2
#define maximum_distance 200
int distance = 100;
NewPing sonar(trig_pin, echo_pin, maximum_distance);
void setup() {
pinMode(DirMotorA, OUTPUT);
pinMode(SpeedMotorA, OUTPUT);
pinMode(BrakeMotorA, OUTPUT);
pinMode(DirMotorB, OUTPUT);
pinMode(SpeedMotorB, OUTPUT);
pinMode(BrakeMotorB, OUTPUT);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
Serial.begin(9600);
}
void loop() {
delay(50);
if (distance <= 10)
{
Serial.println("Sensor has detected a distance less than 10cm.");
stopMove();
delay(500);
moveBackward();
delay(1700);
stopMove();
delay(2000);
turnRight();
delay(1200);
stopMove();
}
else
{
moveForward();
}
distance = readPing();
}
int readPing() {
delay(70);
int cm = sonar.ping_cm();
if (cm == 0) {
cm = 250;
}
return cm;
}
void stopMove() {
digitalWrite(DirMotorA, LOW);
analogWrite(SpeedMotorA, 0);
digitalWrite(BrakeMotorA, HIGH);
digitalWrite(DirMotorB, LOW);
analogWrite(SpeedMotorB, 0);
digitalWrite(BrakeMotorB, HIGH);
}
void moveForward() {
digitalWrite(DirMotorA, Clockwise);
analogWrite(SpeedMotorA, 100);
digitalWrite(BrakeMotorA, LOW);
digitalWrite(DirMotorB, CClockwise);
analogWrite(SpeedMotorB, 100);
digitalWrite(BrakeMotorB, LOW);
}
void moveBackward() {
digitalWrite(DirMotorA, CClockwise);
analogWrite(SpeedMotorA, 100);
digitalWrite(BrakeMotorA, LOW);
digitalWrite(DirMotorB, Clockwise);
analogWrite(SpeedMotorB, 100);
digitalWrite(BrakeMotorB, LOW);
}
void turnRight() {
digitalWrite(DirMotorA, CClockwise);
analogWrite(SpeedMotorA, 70);
digitalWrite(BrakeMotorA, LOW);
digitalWrite(DirMotorB, CClockwise);
analogWrite(SpeedMotorB, 70);
digitalWrite(BrakeMotorB, LOW);
}
void turnLeft() {
digitalWrite(DirMotorA, Clockwise);
analogWrite(SpeedMotorA, 70);
digitalWrite(BrakeMotorA, LOW);
digitalWrite(DirMotorB, Clockwise);
analogWrite(SpeedMotorB, 70);
digitalWrite(BrakeMotorB, LOW);
}
Here is the picture of the circuit, the sensor part is very poorly done, but that works as it should be anyway.
Hope I did everything correctly.
By the way no errors were encountered while compiling.
Thank you in advance for a response and for taking time to help, I appreciate it.