doc/hardware/peripherals/sensor/read_and_decode.rst
.. _sensor-read-and-decode:
Read and Decode ###############
The quickly stabilizing APIs for reading sensor data are:
sensor_readsensor_read_async_mempoolsensor_get_decodersensor_decodeBenefits over :ref:sensor-fetch-and-get
These APIs allow for a wider usage of sensors, sensor types, and data flows with
sensors. These are the future looking APIs in Zephyr and solve many issues
that have been run into with :ref:sensor-fetch-and-get.
:c:func:sensor_read and similar functions acquire sensor encoded data into
a buffer provided by the caller. Decode (:c:func:sensor_decode) then
decodes the sensor specific encoded data into fixed point :c:type:q31_t values
as vectors per channel. This allows further processing using fixed point DSP
functions that work on vectors of data to be done (e.g. low-pass filters, FFT,
fusion, etc).
Reading is by default asynchronous in its implementation and takes advantage of
:ref:rtio to enable chaining asynchronous requests, or starting requests
against many sensors simultaneously from a single call context.
This enables incredibly useful code flows when working with sensors such as:
sensing) all from a single thread with DAG
process ordering.Additionally, other shortcomings of :ref:sensor-fetch-and-get related to memory
and trigger handling are solved.
.. note::
For Read and Decode_ benefits to be fully realized requires
:ref:rtio compliant communication access to the sensor. Typically this means
an :ref:rtio enabled bus driver for SPI or I2C.
Polling Read
Polling reads with Read and Decode_ can be accomplished by instantiating a
polling I/O device (akin to a file descriptor) for the sensor with the desired
channels to poll. Requesting either blocking or non-blocking reads, then
optionally decoding the data into fixed point values.
Polling a temperature sensor and printing its readout is likely the simplest sample to show how this all works.
.. literalinclude:: temp_polling.c :language: c
Polling Read with Multiple Sensors
One of the benefits of Read and Decode is the ability to concurrently read many sensors with many channels in one thread. Effectively read requests are started asynchronously for all sensors and their channels. When each read completes we then decode the sensor data. Examples speak loudly and so a sample showing how this might work with multiple temperature sensors with multiple temperature channels:
.. literalinclude:: multiple_temp_polling.c :language: c
Streaming
Handling triggers with Read and Decode_ works by setting up a stream I/O device
configuration. A stream specifies the set of triggers to capture and if data
should be captured with the event.
.. literalinclude:: accel_stream.c :language: c