Tuesday, 3 April 2018

Ultrasonic Left and Right Detection

Task

Use ultrasonic sensors to detect objects closing in from the left and right side of an entity. If objects are within certain distance then  the buzzer will be turned on.
The components are Arduino Uno, buzzer and two ultrasonic sensor HC-SR04


The  Arduino code to detect left and right object which are near the main entity that is being protected.

#include <NewPing.h>
#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 50  // max distance can be changed accaording to application
#define TRIGGER_PIN2  4  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN2     3  // Arduino pin tied to echo pin on the ultrasonic sensor.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE);

int buzzer=9;
int leftObject;
int rightObject;

void setup() {
  // put your setup code here, to run once:
pinMode(buzzer,OUTPUT);
Serial.begin(9600);
}

void loop() {

delay(50); // Wait 50ms between pings
leftObject=sonar.ping_cm();
rightObject=sonar2.ping_cm();
// Serial print to check values from ultrasonic
Serial.print("Object at Left: ");
Serial.print(leftObject);
Serial.println("cm");
Serial.print("Object at Right: ");
Serial.print(rightObject); 
Serial.println("cm");

// left object less than 10 cm from main entity. Turn on buzzer
if(leftObject < 10 && leftObject!=0  )
{
// buzzer is active-low type (It turns on when the driven low)
digitalWrite(buzzer,LOW); 
}

// Turn off buzzer
if(leftObject > 11 ||leftObject == 0) //
{
  digitalWrite(buzzer, HIGH);
  } 


// right object less than 10 cm from main entity
//Turn on buzzer
if(rightObject < 10 && rightObject!=0 )
{
digitalWrite(buzzer, LOW);
}
//Turn off buzzer
if(rightObject==0 || rightObject > 11 )
{
  digitalWrite(buzzer, HIGH);
  }


}

No comments:

Post a Comment