Sensors

The sensor driver API provides functionality to uniformly read, configure, and setup event handling for devices that take real world measurements in meaningful units.

Sensors range from very simple temperature-reading devices that must be polled with a fixed scale to complex devices taking in readings from multitudes of sensors and themselves producing new inferred sensor data such as step counts, presence detection, orientation, and more.

Supporting this wide breadth of devices is a demanding task and the sensor API attempts to provide a uniform interface to them.

Using Sensors

Using sensors from an application there are some APIs and terms that are helpful to understand. Sensors in Zephyr are composed of Sensor Channels, Sensor Attributes, and Sensor Triggers. Attributes and triggers may be device or channel specific.

Note

Getting samples from sensors using the sensor API today can be done in one of two ways. A stable and long-lived API Fetch and Get, or a newer but rapidly stabilizing API Read and Decode. It’s expected that in the near future Fetch and Get will be deprecated in favor of Read and Decode. Triggers are handled entirely differently for Fetch and Get or Read and Decode and the differences are noted in each of those sections.

Implementing Sensor Drivers

Note

Implementing the driver side of the sensor API requires an understanding how the sensor APIs are used. Please read through Using Sensors first!

Implementing Attributes

  • SHOULD implement attribute setting in a blocking manner.

  • SHOULD provide the ability to get and set channel scale if supported by the device.

  • SHOULD provide the ability to get and set channel sampling rate if supported by the device.

Implementing Fetch and Get

  • SHOULD implement sensor_sample_fetch_t as a blocking call that stashes the specified channels (or all sensor channels) as driver instance data.

  • SHOULD implement sensor_channel_get_t without side effects manipulating driver state returning stashed sensor readings.

  • SHOULD implement sensor_trigger_set_t storing the address of the sensor_trigger rather than copying the contents. This is so CONTAINER_OF may be used for trigger callback context.

Implementing Read and Decode

API Reference

Sensor Interface
Sensor emulator backend API