ultrasonic: Driver for ultrasonic range meters, e.g. HC-SR04, HY-SRF05

Defines

ESP_ERR_ULTRASONIC_NO_ECHO

No echo received (nothing in front of the sensor or out of range)

ESP_ERR_ULTRASONIC_BUSY

A measurement is already running.

ESP_ERR_ULTRASONIC_EMPTY

The group has no sensors.

ESP_ERR_ULTRASONIC_CANCELED

The measurement was canceled by the caller.

Typedefs

typedef void *ultrasonic_group_t

Group of sensors sharing a trigger line.

Created by ultrasonic_group_init() and destroyed by ultrasonic_group_delete(). The handle is opaque.

typedef void *ultrasonic_sensor_t

Sensor handle.

Created by ultrasonic_init() or ultrasonic_group_add_sensor() and destroyed by ultrasonic_delete() or ultrasonic_group_delete() respectively. The handle is opaque.

typedef void (*ultrasonic_done_cb_t)(ultrasonic_sensor_t sensor, const ultrasonic_result_t *result, void *user_ctx)

Measurement completion callback.

Called when a measurement finishes: the echo arrived, the deadline expired, or the measurement was canceled. Runs in a task, never in an interrupt, so ordinary FreeRTOS APIs may be used, but the callback should stay short.

With CONFIG_FREERTOS_USE_TIMERS the callback runs in the FreeRTOS timer service task, otherwise in the task the driver creates for the group. The result is valid only for the duration of the call.

Param sensor:

Sensor handle

Param result:

Measurement result

Param user_ctx:

Value of ultrasonic_sensor_config_t::user_ctx

Functions

esp_err_t ultrasonic_init(const ultrasonic_config_t *cfg, ultrasonic_sensor_t *out)

A single sensor is created with ultrasonic_init(), started with ultrasonic_start() and read with ultrasonic_get_result().

The result can be collected in three ways:

static void on_result(ultrasonic_sensor_t sensor, const ultrasonic_result_t *result, void *user_ctx)
{
if (result->status == ESP_OK)
        printf("%" PRIu32 " mm\n", result->distance_mm);
else
        printf("measurement failed: %s\n", esp_err_to_name(result->status));
}

void app_main(void)
{
ultrasonic_config_t cfg = {
        .group = { .trigger_gpio = GPIO_NUM_17 },
        .sensor = { .echo_gpio = GPIO_NUM_16, .done_cb = on_result },
    };
ultrasonic_sensor_t sensor;

    ESP_ERROR_CHECK(ultrasonic_init(&cfg, &sensor));
    ESP_ERROR_CHECK(ultrasonic_start(sensor));
}

ultrasonic_measure() blocks until the echo arrives, which never takes longer than max_echo_us plus 2 ms: the deadline is armed by a one-shot timer, so a missing echo ends the measurement with ESP_ERR_ULTRASONIC_NO_ECHO instead of hanging.

Neither ultrasonic_start() nor ultrasonic_get_result() keep any interrupt disabled and neither busy-waits: the ECHO line is handled by a GPIO interrupt, so the driver is safe to use on a busy system.

Several sensors wired to a common TRIG line are handled with the group API: ultrasonic_group_init(), ultrasonic_group_add_sensor(), ultrasonic_group_start() and ultrasonic_group_delete(). The group produces one pulse for all its sensors, so they measure simultaneously; the results are collected per sensor with the same functions as above.

Create a single sensor with its own trigger line

Installs the global GPIO ISR service if it is not installed yet.

Parameters:
  • cfg – Sensor configuration

  • out – [out] Sensor handle

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if cfg or out is NULL, the trigger GPIO is negative, the echo GPIO is negative, or the echo GPIO is the trigger GPIO

  • ESP_ERR_INVALID_STATE if the ISR service or the ISR handler can not be set up

  • ESP_ERR_NO_MEM if there is no memory

esp_err_t ultrasonic_delete(ultrasonic_sensor_t sensor)

Destroy a single sensor.

Stops a pending measurement, removes the ECHO interrupt and frees the handle. Use ultrasonic_group_delete() for a sensor added to a group.

Parameters:

sensor – Sensor handle

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if sensor is NULL

  • ESP_ERR_INVALID_STATE if the sensor belongs to a group

esp_err_t ultrasonic_start(ultrasonic_sensor_t sensor)

Start a measurement on a single sensor.

Returns immediately after the trigger pulse, the ECHO line is measured by the interrupt handler.

Parameters:

sensor – Sensor handle

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if sensor is NULL

  • ESP_ERR_ULTRASONIC_BUSY if a measurement is already running

esp_err_t ultrasonic_measure(ultrasonic_sensor_t sensor, ultrasonic_result_t *res)

Start a measurement and wait for its result.

Blocking one-call version of ultrasonic_start() followed by ultrasonic_get_result() with an infinite wait. The wait is bounded: max_echo_us plus about 2 ms after the trigger pulse the measurement is finished by the deadline timer, so this never hangs.

Parameters:
Returns:

  • ESP_OK if a result was collected, check res->status

  • ESP_ERR_INVALID_ARG if sensor or res is NULL

  • ESP_ERR_ULTRASONIC_BUSY if a measurement is already running

bool ultrasonic_is_busy(ultrasonic_sensor_t sensor)

Check whether a measurement is running.

Parameters:

sensor – Sensor handle

Returns:

true if a measurement was started and no result is available yet

esp_err_t ultrasonic_get_result(ultrasonic_sensor_t sensor, ultrasonic_result_t *res, TickType_t wait)

Get the result of the measurement.

Parameters:
  • sensor – Sensor handle

  • res – [out] Result. res->status is ESP_OK when the measurement succeeded, ESP_ERR_ULTRASONIC_NO_ECHO when the echo did not arrive within max_echo_us, and ESP_ERR_ULTRASONIC_CANCELED when the measurement was canceled. Distances are recalculated on every call, so the ambient temperature can be changed before collecting a result.

  • wait – Ticks to wait for the result. 0 polls without blocking

Returns:

  • ESP_OK if a result was collected, check res->status

  • ESP_ERR_INVALID_ARG if sensor or res is NULL

  • ESP_ERR_TIMEOUT if wait == 0 and the measurement is still running, or the result was not ready within wait

esp_err_t ultrasonic_cancel(ultrasonic_sensor_t sensor)

Cancel a running measurement.

Stops the timeout timer and makes the pending result ESP_ERR_ULTRASONIC_CANCELED. Does nothing if no measurement is running.

Parameters:

sensor – Sensor handle

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if sensor is NULL

esp_err_t ultrasonic_set_ambient_temperature(ultrasonic_sensor_t sensor, int16_t temperature_c)

Set the ambient temperature used for the temperature correction.

Parameters:
  • sensor – Sensor handle

  • temperature_c – Ambient temperature, degrees Celsius

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if sensor is NULL

esp_err_t ultrasonic_group_init(const ultrasonic_group_config_t *cfg, ultrasonic_group_t *out)

Create a group of sensors sharing one trigger line.

Installs the global GPIO ISR service if it is not installed yet.

Parameters:
  • cfg – Group configuration

  • out – [out] Group handle

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if cfg or out is NULL, or the trigger GPIO is negative

  • ESP_ERR_INVALID_STATE if the ISR service can not be installed

  • ESP_ERR_NO_MEM if there is no memory

esp_err_t ultrasonic_group_add_sensor(ultrasonic_group_t group, const ultrasonic_sensor_config_t *cfg, ultrasonic_sensor_t *out)

Add a sensor to the group.

Configures the ECHO line as an input with interrupts on both edges.

Parameters:
  • group – Group handle

  • cfg – Sensor configuration

  • out – [out] Sensor handle

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if group or out is NULL, the ECHO GPIO is negative, or the ECHO GPIO is the group trigger GPIO

  • ESP_ERR_INVALID_STATE if the ISR handler can not be added

  • ESP_ERR_NO_MEM if there is no memory

esp_err_t ultrasonic_group_start(ultrasonic_group_t group)

Arm all sensors of the group and produce one trigger pulse.

Returns immediately after the pulse. The results are collected later with ultrasonic_get_result() or delivered via ultrasonic_sensor_config_t::done_cb.

If any sensor of the group is still measuring, nothing is started and ESP_ERR_ULTRASONIC_BUSY is returned, so that a group is never left half-armed.

Parameters:

group – Group handle

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if group is NULL

  • ESP_ERR_ULTRASONIC_EMPTY if the group has no sensors

  • ESP_ERR_ULTRASONIC_BUSY if a measurement is running

  • ESP_ERR_TIMEOUT if the group mutex can not be taken

esp_err_t ultrasonic_group_delete(ultrasonic_group_t group)

Destroy the group and all its sensors.

Stops pending measurements, removes the ECHO interrupts and frees every sensor handle. Sensor handles become invalid.

Parameters:

group – Group handle

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if group is NULL

struct ultrasonic_group_config_t
#include <ultrasonic.h>

Group configuration.

Public Members

gpio_num_t trigger_gpio

GPIO connected to the TRIG line of all sensors in the group.

uint16_t pulse_us

Trigger pulse width, microseconds.

0 means 10

struct ultrasonic_result_t
#include <ultrasonic.h>

Measurement result.

Public Members

esp_err_t status

ESP_OK or one of ESP_ERR_ULTRASONIC_NO_ECHO /

ESP_ERR_ULTRASONIC_CANCELED

uint32_t echo_us

Echo pulse duration, microseconds.

uint32_t distance_mm

Distance to the object in millimeters.

float distance_m

Distance to the object in meters.

struct ultrasonic_sensor_config_t
#include <ultrasonic.h>

Sensor configuration.

Public Members

gpio_num_t echo_gpio

GPIO connected to the ECHO line of this sensor.

uint32_t max_echo_us

Longest echo to wait for, microseconds.

0 means 38000. A longer echo is reported as ESP_ERR_ULTRASONIC_NO_ECHO

bool pull_down

Enable the internal pull-down on the ECHO line.

bool temperature_compensation

Apply the ambient temperature correction to the speed of sound.

int16_t ambient_temperature_c

Ambient temperature used when compensation is enabled.

ultrasonic_done_cb_t done_cb

Optional completion callback, NULL to poll instead.

void *user_ctx

Passed to done_cb as is.

struct ultrasonic_config_t
#include <ultrasonic.h>

Configuration of a sensor with its own trigger line.

Public Members

ultrasonic_group_config_t group

Trigger line of this sensor.

ultrasonic_sensor_config_t sensor

Echo line and measurement parameters.