Bird
0
0
Arduinoprogramming~30 mins

Ultrasonic distance sensor (HC-SR04) in Arduino - Mini Project: Build & Apply

Choose your learning style9 modes available
Ultrasonic distance sensor (HC-SR04)
📖 Scenario: You want to measure the distance to an object using an ultrasonic sensor (HC-SR04) connected to an Arduino board. This sensor sends out sound waves and listens for the echo to calculate how far the object is.
🎯 Goal: Build a simple Arduino program that reads the distance from the HC-SR04 sensor and prints the distance in centimeters to the Serial Monitor.
📋 What You'll Learn
Use pins 9 for triggerPin and 10 for echoPin.
Create a variable to store the duration of the echo pulse.
Calculate the distance in centimeters using the duration.
Print the distance to the Serial Monitor.
💡 Why This Matters
🌍 Real World
Ultrasonic sensors are used in robots, parking sensors, and obstacle detection to measure distances without touching objects.
💼 Career
Understanding how to read sensor data and process it is important for embedded systems and robotics jobs.
Progress0 / 4 steps
1
Set up sensor pins
Create two integer variables called triggerPin and echoPin and set them to 9 and 10 respectively.
Arduino
Hint

Use int to create the variables and assign the numbers 9 and 10.

2
Configure pins in setup
In the setup() function, set triggerPin as an output and echoPin as an input. Also, start the serial communication at 9600 baud using Serial.begin(9600);.
Arduino
Hint

Use pinMode() to set pin modes and Serial.begin(9600); to start serial communication.

3
Measure distance in loop
In the loop() function, send a 10 microsecond pulse to triggerPin, then read the pulse duration from echoPin using pulseIn(). Calculate the distance in centimeters by dividing the duration by 58 and store it in an integer variable called distance.
Arduino
Hint

Send a short pulse on triggerPin, then use pulseIn() to measure the echo time. Divide by 58 to get centimeters.

4
Print the distance
Add a line in the loop() function to print the distance variable to the Serial Monitor using Serial.println(distance);.
Arduino
Hint

Use Serial.println(distance); to show the distance on the Serial Monitor.