1.. _sensor-fetch-and-get: 2 3Fetch and Get 4############# 5 6The stable and long existing APIs for reading sensor data and handling triggers 7are: 8 9* :c:func:`sensor_sample_fetch` 10* :c:func:`sensor_sample_fetch_chan` 11* :c:func:`sensor_channel_get` 12* :c:func:`sensor_trigger_set` 13 14These functions work together. The fetch APIs block the calling context which 15must be a thread until the requested :c:enum:`sensor_channel` (or all channels) 16has been obtained and stored into the driver instance's private data. 17 18The channel data most recently fetched can then be obtained as a 19:c:struct:`sensor_value` by calling :c:func:`sensor_channel_get` for each channel 20type. 21 22.. warning:: 23 It should be noted that calling fetch and get from multiple contexts without 24 a locking mechanism is undefined and most sensor drivers do not attempt to 25 internally provide exclusive access to the device during or between these 26 calls. 27 28Polling 29******* 30 31Using fetch and get sensor can be read in a polling manner from software threads. 32 33 34.. literalinclude:: ../../../../samples/sensor/magn_polling/src/main.c 35 :language: c 36 37Triggers 38******** 39 40Triggers in the stable API require enabling triggers with a device 41specific Kconfig. The device specific Kconfig typically allows selecting the 42context the trigger runs. The application then needs to register a callback with 43a function signature matching :c:type:`sensor_trigger_handler_t` using 44:c:func:`sensor_trigger_set` for the specific triggers (events) to listen for. 45 46.. note:: 47 Triggers may not be set from user mode threads, and the callback is not 48 run in a user mode context. 49 50There are typically two options provided for each driver where to run trigger 51handlers. Either the trigger handler is run using the system work queue thread 52(:ref:`workqueues_v2`) or a dedicated thread. A great example can be found in 53the BMI160 driver which has Kconfig options for selecting a trigger mode. 54See :kconfig:option:`CONFIG_BMI160_TRIGGER_NONE`, 55:kconfig:option:`CONFIG_BMI160_TRIGGER_GLOBAL_THREAD` (work queue), 56:kconfig:option:`CONFIG_BMI160_TRIGGER_OWN_THREAD` (dedicated thread). 57 58Some notable attributes of using a driver dedicated thread vs the system work 59queue. 60 61* Driver dedicated threads have dedicated stack (RAM) which only gets used for 62 that single trigger handler function. 63* Driver dedicated threads *do* get their own priority typically which lets you 64 prioritize trigger handling among other threads. 65* Driver dedicated threads will not have head of line blocking if the driver 66 needs time to handle the trigger. 67 68.. note:: 69 In all cases it's very likely there will be variable delays from the actual 70 interrupt to your callback function being run. In the work queue 71 (GLOBAL_THREAD) case the work queue itself can be the source of variable 72 latency! 73 74.. literalinclude:: tap_count.c 75 :language: c 76