Driver for ultrasonic distance sensors compatibles with HCSR-04.
Returns the distance in centimeters or inches.
Allows to operate the sensor with a single pin in arduino.
Public declaration:
#define hc_TimeOut 18000 // microseconds #define hcErr_Timeout -1 #define hcErr_Hardware -2 typedef enum{centimeter=0, inch} DistUnit; class Hcsr04{ public: Hcsr04(); void begin(byte triggerPin, byte echoPin, DistUnit unit= centimeter); int hcDist(byte tries=1); long ultraSonicRead(); };
Call begin() informing pins for trigger and echo and selecting the distance unit (centimeters or inchs).
It is possible to indicate the same arduino pin for trigger and echo, so it is necessary to install a pulldown resistor between the pin and GND.
Call hcDist() to read the sensor and get distance. There are some situations where the reading fails. You can indicate the number of tries if that happen.
TimeOut
If the echo does not return within the time set by hcTimeOut, the reading fails. In practice this value establishes the maximum distance that will be measured by the sensor. Manufacturers promise that the sensor is capable of measuring up to 4 meters, but this is rarely possible, especially in small robots. Usually the sensor is close to the ground which in itself limits the maximum distance. Therefore, it is better to set the timeout to the value that can actually be read, so the reading function returns faster and the program flows better.
Sensor params. Call before any other method. You can use the same Arduino pin for trigger and echo. For this you need to install a pull-down resistor between arduino pin and GND. 100 Kohms is a good value. The class suport this situation and performs the necessary processing. Just indicate the same pin for triggerPin and echoPin params.
Read distance an return in indicate unit.
Read the sensor and return the time in microseconds.