Last Updated on March 24, 2024
Simple Interface ultrasonic sensor (HC-SR 04) with Arduino, The HC-SR 04 is famous ultrasonic range sensor, and its very easy to use with many microcontrollers. This article will give you idea about to interface ultrasonic sensor with Arduino board.
Here the circuit constructed for to identify the range limit with warning beep sound. This circuit have minimum components such as Arduino development board, ultrasonic sensor HC-SR 04 and a buzzer.
Connection diagram
Circuit Diagram
This circuit can used for security alarm, invisible fence with alarm or distance measurement (Cm) etc…
The HC-SR04 sensor module works under the principle of ultrasonic wave transmission and ultrasonic wave reflection (echo). The time difference between transmitter wave to echo wave is calculated for to find the distance between sensor module and objects.
Arduino code
HC-SR04 Ping distance sensor
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 9 Trig to Arduino pin 8
Buzzer +ve to Arduino pin 13 and GND to GND
Original code sourced from theorycircuit.com
Some code and wiring inspired by arduino.cc
#define trigPin 8 #define echoPin 9 #define Buzzer 13 void setup() { Serial.begin (9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(Buzzer, OUTPUT); } void loop() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); int duration = pulseIn(echoPin, HIGH); int distance = (duration/2) / 29.1; if (distance < 30) { digitalWrite(Buzzer,HIGH); //less than 30cm then buzzer will produce beep sound } else { digitalWrite(Buzzer,LOW); } if (distance >= 200 || distance <= 0) { Serial.print("Out of range"); } else { Serial.print(distance); Serial.print("cm"); } delay(500); }
Components List
S.No | Name | Quantity |
1. | Arduino UNO board | 1 |
2. | Buzzer 6V | 1 |
3. | Connecting Wires | as required |
Prototype
It works IF I add this at the start
unsigned long duration;
unsigned long distance;
Hi Newtoon
Thank you for trying theorycircuit.com
Doesn’t work
‘Duration was not declared in this scope’ is the error message