An ultrasonic sensor is used to detect the distance to the closest object in front of the sensor. It uses ultrasound, sound with a frequency higher than humans can hear. As you probably know sound can reflect from surfaces creating an echo. This echo is what the sensor uses to estimate the distance. The sensor sends out a burst of ultrasound and then waits for the echo. By knowing the speed of sound and the time between the burst, with the detection, it is possible to calculate the distance. The shorter time it takes to detect the echo, the closer the object is.
Materials
- 1 Arduino Uno board
- 1 education shield
- 1 ultrasonic sensor
- 4 jumper wires
Instructions
- Attach the shield onto the top of the Arduino board.
- Connect the Ultrasonic sensor to the breadboard.
- Connect VCC to 5V, Trig to digital pin 11, Echo to digital pin 12 and GND to GND using jumper wires.
- Connect the board to the computer and upload example ‘UltrasonicSensor’.
Code
Find the code in File>Example>EducationShield>Help>UltrasonicSensor.
You should now open the serial monitor and move your hand back and forth in front of the ultrasonic sensor. The distance in cm between the sensor your hand should be printed to the monitor.
Commands
UltrasonicSensor( triggerPin, echoPin)
– creates an UltrasonicSensor object.- Parameters
- (
int
)triggerPin
– the digital pin to which the ultrasonic sensor’s trigger pin is connected. -
(
int
)echoPin
– the digital pin to which the ultrasonic sensor’s echo pin is connected.
- (
- Parameters
getDistance()
– checks the distance to the closest object in front of the sensor- Return
- (
int
) the distance in centimeters.
- (
- Return
Troubleshooting
- Make sure the connections between the Ultrasonic sensor, wires and board are correct.
- Make sure that the pin on the ultrasonic sensor marked as ‘Trig’ is connected to the Arduino digital pin that you have stated as the
triggerPin
in your code. - Make sure that the pin on the ultrasonic sensor marked as ‘Echo’ is connected to the Arduino digital pin that you have stated as the
echoPin
in your code.