UncleRus / esp-idf-lib

Component library for ESP32-xx and ESP8266
https://esp-idf-lib.readthedocs.io/en/latest/
1.42k stars 439 forks source link

Ultrasonic hogs the CPU #634

Open nostromo-1 opened 6 months ago

nostromo-1 commented 6 months ago

The issue

The ultrasonic module makes use of a critical section (between PORT_ENTER_CRITICAL and PORT_EXIT_CRITICAL). Within it, it uses active loops (that is, while (gpio_get_level(dev->echo_pin))).

If a task is continuously making calls to ultrasonic_measure, as it stops interrupts, it affects other tasks, causing delays in them. The function ultrasonic_measurehogs the CPU for several millisseconds. This causes difficulties in other tasks that need precise timing.

A solution would be to use interrupts in the echo pin and RTOS notifications.

Which SDK are you using?

esp-idf

Which version of SDK are you using?

5.1.2

Which build target have you used?

Component causing the issue

ultrasonic

Anything in the logs that might be useful for us?

I have tested an alternative approach with interrupts in the echo pin and RTOS notifications in the interrupt handler. It works correctly, it does not hog the CPU, and it maintains measuring accuracy.

Additional information or context

No response

Confirmation

nostromo-1 commented 6 months ago

A possible implementation with interrupts and RTOS signals can be found here: https://github.com/nostromo-1/robotic-car-ESP32/blob/master/components/ultrasonic/ultrasonic.c