Hi all,
I'm building an obstacle avoiding robot. It's pretty big as ultimately it will be a vacuuming robot like Roomba. When one of the ultrasonic sensors hears an obstacle, the backing up sequence starts.
As the robot is quite wide, the dc motors are running for not enough amount of time for it to fall back to a safe distance. I tried for loop, millis() and delays but all this for nothing. I need to make those motors run for a bit longer than they are now but only when the sensors are hearing an obstacle. May I ask for your suggestions?
I'm pasting my current code bellow:
//------------------Libraries------------------
#include "NewPing.h"
#include <Servo.h>
//Variables:
//------------------SONARS------------------
//bottom sonar
#define TRIGGER_PIN 2
#define ECHO_PIN 3
//head sonar
#define TRIGGER_PIN2 4
#define ECHO_PIN2 5
//shared data
#define MAX_DIST 200
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DIST);
NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DIST);
float duration, bottom, duration2, head;
int ledPin = 7;
//------------------MOTORS------------------
// speed
int l_speed = 8; //Left Motor
int r_speed = 9; //Right Motor
// Motor Control Pins
int M1P1 = 10;
int M1P2 = 11;
int M2P1 = 12;
int M2P2 = 13;
//------------------SERVO------------------
Servo Servo1;
int servoPin = 6;
int pos = 0;
//------------------TIMER------------------
int lastmillis1, lastmillis2, lastmillis3, lastmillis4;
int actual;
int T1 = 2000;
void setup() {
pinMode(M1P1,OUTPUT);
pinMode(M2P1,OUTPUT);
pinMode(M1P2,OUTPUT);
pinMode(M2P2,OUTPUT);
pinMode(l_speed,OUTPUT);
pinMode(r_speed,OUTPUT);
Servo1.attach(servoPin);
Serial.begin (9600);
}
void HeadBanging() {
//Head Moving
for (pos = 45; pos <= 135; pos += 1) {
Servo1.write(pos);
delay(20);
}
for (pos = 135; pos >= 45; pos -= 1) {
Servo1.write(pos);
delay(20);
}
}
void loop() {
analogWrite(l_speed,255);
analogWrite(r_speed,255);
HeadBanging();
//Sensors blaazing!
duration = sonar.ping();
bottom=(duration / 2)* 0.0343;
duration2 = sonar2.ping();
head=(duration2 / 2)* 0.0343;
//in case of finding a obstacle
if (head<=7||bottom>=5) {
Serial.print("oH noOO!! aN oBSTacLE!!! rUUUN! ");
Serial.print(head);
Serial.println(" cm. alERT! ALerT! We ALL GonNA DiE!");
aktualny = millis();
if((actual - lastmillis1) <= T1)
{
lastmillis1 = millis();
digitalWrite(M1P1,LOW); //stop
digitalWrite(M2P1,LOW);
digitalWrite(M1P2,LOW);
digitalWrite(M2P2,LOW);
delay(1000);}
if((actual - lastmillis2) <= T1)
{
lastmillis2 = millis();
digitalWrite(M1P1,LOW); //move back a bit
digitalWrite(M2P1,LOW);
digitalWrite(M1P2,HIGH);
digitalWrite(M2P2,HIGH);
delay(1000);}
if((actual - lastmillis3) <= T1)
{
lastmillis3 = millis();
digitalWrite(M1P1,HIGH); //turn left
digitalWrite(M2P1,LOW);
digitalWrite(M1P2,LOW);
digitalWrite(M2P2,HIGH);
delay(1000);}}
else {
Serial.println("Dobie, dobie doo, I'm a happy robot moving forward!");
digitalWrite(M1P1,HIGH);
digitalWrite(M2P1,HIGH);
digitalWrite(M1P2,LOW);
digitalWrite(M2P2,LOW);}
}```