How to make ultrasonic distance dependent alarm

Posted by moudud 12/05/2019 0 Comment(s)

 

 

How to make ultrasonic distance dependent alarm

 


Circuit Diagram :


 

 

Connections
 PinArduino
BuzzerVCCD2
GNDGND
HC-SR04 Ultrasonic SensorVCC5V
GNDGND
TrigD12
EchoD11
Oled Display ModuleVCC5V
GNDGND
SDAA4
SCLA5


 

 

 

 


Code

 

 

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

const int output =  2; 

#define CommonSenseMetricSystem
//#define Imperial Nonsense System

#define trigPin 12
#define echoPin 11

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(output, OUTPUT);
  pinMode(echoPin, INPUT);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();

}

void loop() {
  long duration, distance;
  
  digitalWrite(trigPin, LOW);  //PULSE ___|---|___
  delayMicroseconds(2); 
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); 
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);
  
  #ifdef CommonSenseMetricSystem
  distance = (duration/2) / 29.1;
  #endif
  #ifdef ImperialNonsenseSystem
  distance = (duration/2) / 73.914;
  #endif

  display.setCursor(22,10);
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.println(distance);
  display.setCursor(85,10);
  display.setTextSize(2);
  
  #ifdef CommonSenseMetricSystem
  display.println("cm");
  #endif
  #ifdef ImperialNonsenseSystem
  display.println("in");
  #endif
  
  display.display();

  delay(500);
  display.clearDisplay();
 
  Serial.println(distance);//debug


  if (distance <= 15) //set the trig point 
  {
    //output(D2) is high
    digitalWrite(output, HIGH);
  } else {
    //output(D2) is low
    digitalWrite(output, LOW);
  }
  
 

}

 


 

 


 

 


 

 

Write a Comment