The HC-SR04 ultrasonic sensor is a popular and low-cost sensor used for measuring distances. It works by sending out a sound wave and measuring the time it takes for the wave to bounce back. This information can then be used to calculate the distance to the object.
The HC-SR04 sensor is a great choice for a variety of applications, including robotics, automation, and home security. It is easy to use and can be interfaced with a variety of microcontrollers.
In this article, we will take a look at the HC-SR04 sensor and how to use it with an Arduino. We will also provide some example code that you can use to get started.
Materials
To get started, you will need the following materials:
Wiring
The HC-SR04 sensor has four pins: VCC, GND, Trig, and Echo. VCC should be connected to 5V, GND to ground, Trig to digital pin 12, and Echo to digital pin 13.
Code
The following code will read the distance from the HC-SR04 sensor and print it to the serial monitor:
#include <Arduino.h>
// Define the pins that the HC-SR04 sensor is connected to.
#define TrigPin 12
#define EchoPin 13
// Define the speed of sound in cm/us.
#define SoundSpeed 340
void setup() {
// Initialize the serial monitor.
Serial.begin(9600);
// Set the Trig pin as an output.
pinMode(TrigPin, OUTPUT);
// Set the Echo pin as an input.
pinMode(EchoPin, INPUT);
}
void loop() {
// Send a 10us pulse to the Trig pin.
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
// Wait for the Echo pin to go high.
long startTime = micros();
while (digitalRead(EchoPin) == LOW);
long endTime = micros();
// Calculate the distance to the object.
float distance = (endTime - startTime) * SoundSpeed / 2;
// Print the distance to the serial monitor.
Serial.println(distance);
// Wait for 1 second before taking another measurement.
delay(1000);
}
The HC-SR04 ultrasonic sensor is a versatile and easy-to-use sensor that can be used for a variety of applications. It is a great choice for beginners who are just getting started with robotics or automation.
Call to Action
If you are looking for a low-cost and easy-to-use ultrasonic sensor, then the HC-SR04 is a great option. Order yours today and start experimenting!