This is an old revision of the document!
The SR-04 ultrasound module can be used for many applications. For example, it can be used to trigger Halloween decorations, as car back-up proximity alerts in garages, movement alarms in homes, or as a basement sump water level alarm.
There are four pins: Vcc and GND, which supply power to the module, trigger, which is used to send an ultrasonic pulse when brought high by the Arduino, and echo, which is used to receive the echo of the pulse. The time it takes for the emitted pulse to echo back to the module is what's used to calculate the distance to the object or person. The SR-04 can measure distances from 2cm to about 400cm optimally, but in most cases, using the 5V supply from the Arduino, you can measure from about 4cm to 120cm.
The pulse is a 40kHz audio tone, which is too high a frequency for humans to hear. We'll be sending a short pulse of 20ms (one fiftieth of a second) every quarter of a second or so. When the receiver hears a 40kHz tone, it will set the echo pin high.
The formula for calculating distance is time x speed of sound. And because that measures the distance from the emitter to the object and back, we will divide it by two to get the distance to the object. We are using 29.1 as the speed of sound, though obviously this is varies depending on air pressure and temperature.
So, if we have an object in front of our sensor, and it takes 5ms for our pulse to bounce off it and be detected by our sensor, we get the following formula, where distance is in cm, time in ms and speed of sound is cm per ms:
distance = time x speed of sound / 2
distance = 5 x 29.1 / 2
distance = 73 cm
RGB LEDs come in two flavours: common anode (positive supply) and common cathode (negative). They are essentially three LEDs in one package, with either the positive or negative leads connected internally. As with all LEDs, we will add a current-limiting resistor to prevent the LED from drawing too much current and getting damaged. We are using the same value resistor for all 3 LEDs in this workshop, but if you were to do this for a long-term project you would want to calculate the optimum resistance for each LED.
The code for this workshop is available here.
This example shows an LED changing from white to red when someone gets within about 60cm of it, but the outputs could be easily changed to be more LEDS, motors, servos, sound circuits, etc.