# Exercise 2: Ultrasonic Sensor
We should by now be acquainted with the Arduino IDE, and confirmed that the servos work as expected.
The main goals of this exercise are to understand how to use the serial monitor in the Arduino IDE and confirm that the ultrasonic sensor works as expected.
# Task 1: Obstacle detection (virtual)
Goal: Understand obstacle detection distance with an ultrasonic sensor
Our robot also has an ultrasonic sensor for detecting obstacles. This will allow us to use this as feedback for navigation. Refer to presented information on the HC-SR04 ultrasonic sensor to understand how the sensor works. The program (sketch) below triggers the ultrasonic pin by sending a
HIGH signal for 10 microseconds and then uses
pulseIn to get the time in microseconds it took for the echo received by to the sensor when an obstacle is present to reflect the signal. The program also uses the
Serial to output that duration in microseconds.
By clicking on the buttons under the robot environment, you can change the position of the robot. Find the distance of the obstacle for each position.
The time between a triggered sound wave pulse and its received echo is used to determine distance. Specifically, you can use this equation in the code:
Can you explain why?
# Task 2: Obstacle detection (physical)
Goal: test the ultrasonic sensor using your modified code.
- Take an inventory of all your hardware components.
- Download the working example from task 1 (click the 3 vertical dots). Upload this to your Arduino Uno board.
- Open the serial monitor on the Arduino IDE while the program is running by clicking the magnifying glass icon on the far right of the icon ribbon. [see demo]
The Serial Monitor is a separate pop-up window that outputs serial data communicated between the Arduino and your computer. It can be useful for debugging hardware and programming logic.
- Using an object such as a notebook or piece of paper, place it at a known perpendicular distance, say 50cm. Confirm that the sensor is working properly by taking measurements. 2cm accuracy is fairly reasonable. Troubleshoot if you are not getting a reasonable result.
Ultrasonic Sensor Range
The HC-SR04 sensor provides 2cm to 400cm of non-contact measurement functionality with a ranging accuracy that can reach up to 3mm.
- Some other things to experiment with:
Place your object at different angles to the sensor to see how the reading changes;
delay()to vary how often a measurement is taken.
# About the ultrasonic sensor
If you want to learn more how the HC-SR04 ultrasonic sensor works, here are some resources: