#include <Servo.h>
#include <NewPing.h>
#define TRIGGER_PIN 12
#define ECHO_PIN 11
#define MAX_DISTANCE 200
#define MAX_SPEED 150 // set the speed of the dc motors
int distance= 100;
Servo flameservo;
Servo Sonarservo;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
// L298 pins
const int ENa = 9;
const int ENb = 10;
const int IN1 = 2;
const int IN2 = 7;
const int IN3 = 4;
const int IN4 = 6;
// flame sensor pins
const int Dflame = 6;
const int Aflame = A0;
//flame extinguisher
const int fan =A5;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(ENa, OUTPUT);
pinMode(ENb, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
//set the pwm duty cycle for the Enable pin
// analogWrite(ENa ,MAX_SPEED);
// analogWrite(ENb , MAX_SPEED);
flameservo.attach(5); // attach flame servo to pin 5
Sonarservo.attach(3); // attach sonar servo to pin 3
Sonarservo.write(100); // set sonar servo to 100 degree
delay(2000); // wait for 2 secs
// check the distance
distance = readPing();
delay(100);
distance = readPing();
delay(100);
}
void loop() {
// put your main code here, to run repeatedly:
analogWrite(ENa ,MAX_SPEED);
analogWrite(ENb , MAX_SPEED);
int distanceR = 0;
int distanceL = 0;
delay(40);
if(distance <=15){
move_stop();
delay(100);
move_backward();
delay(300);
move_stop();
delay(200);
distanceR = look_right();
delay(300);
distanceL = look_left();
delay(300);
if (distanceR >= distanceL){
turn_right();
move_stop();
}
else {
turn_left();
move_stop();
}
}
else {
move_forward();
}
distance = readPing();
}
void move_forward(){
digitalWrite(IN1 , HIGH);
digitalWrite(IN2 , LOW);
digitalWrite(IN3 , HIGH);
digitalWrite(IN4 , LOW);
}
void move_backward(){
digitalWrite(IN1 , LOW);
digitalWrite(IN2 , HIGH);
digitalWrite(IN3 , LOW);
digitalWrite(IN4 , HIGH);
}
void move_stop(){
digitalWrite(IN1 , HIGH);
digitalWrite(IN2 , HIGH);
digitalWrite(IN3 , HIGH);
digitalWrite(IN4 , HIGH);
}
void turn_left(){
digitalWrite(IN1 , HIGH);
digitalWrite(IN2 , HIGH);
digitalWrite(IN3 , HIGH);
digitalWrite(IN4 , LOW);
delay(10);
}
void turn_right(){
digitalWrite(IN1 , HIGH);
digitalWrite(IN2 , LOW);
digitalWrite(IN3 , HIGH);
digitalWrite(IN4 , HIGH);
delay(10);
}
// calculate distance of the ultrasonic sensor
int readPing(){
delay(70);
int cm = sonar.ping_cm();
if(cm==0){
cm = 250;
}
return cm;
}
//make the servo the ultrasonic sensor is mounted on look left and
//return the distance of obstacle away from it
int look_left() {
Sonarservo.write(170);
int distance =readPing();
delay(2000);
Sonarservo.write(100);
return distance;
delay(100);
}
//make the servo the ultrasonic sensor is mounted on look left and
//return the distance of obstacle away from it
int look_right(){
Sonarservo.write(20);
int distance =readPing();
delay(2000);
Sonarservo.write(100);
return distance;
delay(100);
}