Menu

Hcsr04

Perrotti

Hcsr04 Class

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();
};

How to use

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.


void begin(byte triggerPin, byte echoPin, DistUnit unit= centimeter);

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.

  • triggerPin: Trigger pin.
  • echoPin: Echo pin.
  • unit: Distance unit for hcDist() method readings (centimeter or inch)

int hcDist(byte tries=1);

Read distance an return in indicate unit.

  • tries: Maximum number of attempts if reading fails.
  • return: The distance in the unit indicated by begin method. If the read fails, return a negative value.

long ultraSonicRead();

Read the sensor and return the time in microseconds.

  • return: Echo time in microseconds or negative value if read fails.

Related

Wiki: HcsrArray
Wiki: HcsrAuto
Wiki: Home

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.