Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
Measuring distances is a common requirement in various projects, from robotics to home automation. In the Arduino environment, one of the most popular methods for measuring distance is using ultrasonic sensors. These sensors are affordable, easy to use, and provide reasonably accurate measurements. This article will guide you through the process of setting up an ultrasonic sensor with an Arduino to measure distances.
An ultrasonic sensor works by emitting a high-frequency sound wave and measuring the time it takes for the echo to return. The most commonly used sensor for this purpose is the HC-SR04. It has four pins: VCC, Trig, Echo, and GND.
Here is a simple Arduino sketch to measure distance using the HC-SR04 sensor:
const int trigPin = 9;
const int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration;
int distance;
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = duration * 0.034 / 2;
// Print the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500);
}
distance = duration * 0.034 / 2
, where 0.034 cm/µs is the speed of sound in air.Using an ultrasonic sensor with Arduino is a straightforward and effective way to measure distances. This setup can be used in a variety of projects, including obstacle avoidance in robots, level measurement in tanks, and more.