How to use a Ticker callback to sample an AnalogIn (ADC) at a given sample rate?

Hello Scott,

According to the Mbed documentation about Default timeouts the Mbed RTOS API has made the choice of defaulting to 0 timeout (no wait) for the producer methods, and osWaitForever (infinite wait) for the consumer methods.

A typical scenario for a producer could be a peripheral (e.g. a Ticker) triggering an interrupt to notify an event; in the corresponding interrupt service routine you cannot wait (this would deadlock the entire system).

To support many various targets the AnalogIn::read() member function calls an analog HAL function analogin_read(analogin_t *obj). The implementation of this function is target dependent. But in each case it:

  • configures the ADC channel
  • starts ADC conversion
  • waits for the conversion to be completed

Since these steps are quite time consuming the AnalogIn::read() function cannot be used as a producer (and called in ISR).

The fastest way to read an analog input is to utilize the hardware abstraction layer of the given target MCU. For example as in this project. This usually allows to:

  • configure the ADC channel only once and use it for all measurements
  • start ADC conversion only once and use a continuous conversion mode
  • utilize direct memory access to transfer the data from the ADC to the SRAM

Have a look also at this thread.

1 Like