Arduino Activity: Ultrasonic Sensor (HC-SR04)
Subject: SENSOR TECHNOLOGY
Duration: 1–2 hours
Tools: Arduino Uno, HC-SR04 ultrasonic sensor, jumper wires, breadboard
Simulator: TinkerCAD (for testing)
PART 1 — EXAMPLE
Goal: Read distance from ultrasonic sensor and print in the serial monitor.
Sample Code
#define trigPin 9
#define echoPin 10
void setup() {
[Link](9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
float distance = (duration * 0.0343) / 2;
[Link]("Distance: ");
[Link](distance);
[Link](" cm");
delay(500);
PART 2 — STUDENT ACTIVITY
This is the activity that atudent must complete to show understanding.
ACTIVITY TITLE:
“Object Detection Alert System using Ultrasonic Sensor”
GOAL: Students must create a system that activates LEDs + buzzer
depending on the distance.
REQUIREMENTS: Students must use the following topics:
1) IF / ELSE IF conditions
2) LOOP (for or while)
3) Functions (at least 1 function)
4) Ultrasonic reading
5) LED or buzzer output
CONDITIONS THEY MUST IMPLEMENT:
Distance Range Output
< 10 cm Red LED ON + Buzzer fast beep
10–20 cm Yellow LED ON + Buzzer slow beep
20–40 cm Green LED ON (no buzzer)
> 40 cm All off
GUIDED STARTER CODE (Students must complete)
Use this partial template:
#define trigPin 9
#define echoPin 10
#define redLED 3
#define yellowLED 4
#define greenLED 5
#define buzzer 6
long readDistance() {
// STUDENTS MUST COMPLETE THIS FUNCTION
void setup() {
[Link](9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(redLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(buzzer, OUTPUT);
void loop() {
float distance = readDistance();
// STUDENTS WILL CREATE CONDITIONS HERE
// Use if() / else if() / else()
// Use digitalWrite(), tone(), and noTone()
delay(200);
Learning Outcome
After the activity, students should be able to:
✔ Correctly read values from ultrasonic sensor
✔ Use functions to organize code
✔ Implement conditional statements
✔ Use loops or timing techniques
✔ Control LEDs and buzzers based on sensor readings
✔ Build a simple object detection system