Advanced arduino library for HC-SR04 ultrasonic sensors
Basic example:
#include <ST_HW_HC_SR04.h>
ST_HW_HC_SR04 ultrasonicSensor(13, 12); // ST_HW_HC_SR04(TRIG, ECHO)
// Get the time the ultrasonic pulses took from the sensor to the blocking object
int hitTime = ultrasonicSensor.getHitTime();
// Calculate the approximate distance in centimeters (as seen in extras/HC-SR04.txt)
int distanceInCm = hitTime / 29;
The getHitTime
function will return 0
if the ultrasonic sensor doesn't
receive back the packets it sent before the timeout value.
The default timeout value is 5000
microseconds, which sould be enough for approximately
86 centimeters ([5000 / 58] ~= 86.2).
Although I didn't confirm, it is stated in this datasheet (alternate link) that max. range of this sensor is 4 meters (400cm). As so, setting the timeout value to 23200 microseconds (23.2 ms) should be enough for all cases where the object distance is less or equal to 4 meters.
The timeout-related methods of this library are:
// Setters
ultrasonicSensor.setTimeout(unsigned long desiredTimeout);
ultrasonicSensor.setTimeoutToDefaultValue();
// Getters
unsigned long currentTimeout = ultrasonicSensor.getTimeout();
Information about how the ultrasonic sensor works is present in the
extras/HC-SR04.txt
file.