Lesson Five – Ultrasonic Sensor Alarm

Lesson Five: Ultrasonic Sensor Alarm

The ultrasonic sensor is a kind of sensor developed by using the characteristics of the ultrasonic waves. It is widely used in industry, biomedicine, robot collision prevention, and anti-theft alarm and other fields. The circuit in this lesson will be a simple alarm device based on ultrasonic distance sensor.

What way it may look like if you build this circuit with an Arduino kit: 

Try to build this circuit in Tinkercad Circuits:

STEP 1: Build an Independent Loop with the LED

Connect the shorter leg of LED to ground through a 220 Ohm resistor; connect the longer leg of the LED with pin 6 of the Arduino board

STEP 2: Build an Independent Loop with the Buzzer

Connect the Buzzer’s positive terminal with pin 8 of Arduino and negative terminal to GND

STEP 3: Build a Separate Loop with the Ultrasonic Sensor

Use Female-to-male Dupont Wire to connect the VCC to the “+” bus, GND to the “-” bus. Connect the Trigger pin to pin 12 and Echo pin to pin 13 of Arduino.

STEP 4: Write & Test the Code

Here is the code, look closely to see how the code works

/* This simple project describes how to make an ultrasonic alarm system using 
LED, Ultasonic Sensor(HC-SR04) and a buzzer.*/ 

//Firstly the connections of ultrasonic Sensor.Connect +5v and GND normally and trigger pin to 12 & echo pin to 13. 

#define trigPin 12
#define echoPin 13
int Buzzer = 8; // Connect buzzer pin to 8
int ledPin= 6;  //Connect LEd pin to 6
int duration, distance; //to measure the distance and time taken 

void setup() {
        Serial.begin (9600); 
        //Define the output and input objects(devices)
        pinMode(trigPin, OUTPUT); 
        pinMode(echoPin, INPUT);
        pinMode(Buzzer, OUTPUT);
        pinMode(ledPin, OUTPUT);
}

void loop() {

    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    //when distance is greater than or equal to 30 OR less than or equal to 0,the buzzer and LED are off
  if (distance >= 30 || distance <= 0) 
        {
        Serial.println("no object detected");
        noTone(Buzzer);
        digitalWrite(ledPin,LOW);
        }
  else {
        Serial.println("object detected \n");
        Serial.print("distance= ");              
        Serial.print(distance);        //prints the distance if it is between the range 0 to 200
        tone(Buzzer,400);              // play tone of 400Hz for 500 ms
        digitalWrite(ledPin,HIGH);
  }
}

After we run the code, if something comes within 30 cm of the Ultrasonic Sensor, the buzzer should ring, and the LED should light up!

Take me back to Makerhub