sensor
Introduction
The sensor driver module provides and implements sensor-related Hardware Driver Interfaces (HDIs), including obtaining sensor information, enabling or disabling a sensor, subscribing to or unsubscribing from sensor data, and setting sensor options. These APIs make service development easier.
Figure 1 Sensor driver module architecture

Directory Structure
The directory structure of the sensor driver module is as follows:
/drivers/peripheral/sensor
├── hal # HAL code
│ └── include # HAL header files
│ └── src # HAL code implementation
├── interfaces # Driver capability APIs provided for upper-layer services
│ └── include # APIs exposed externally
├── test # Test code
│ └── unittest # Unit test code
Usage
This section uses the acceleration sensor as an example to describe how to use sensor APIs.
Available APIs
The HAL module of the sensor driver provides APIs that can be directly called by sensor services to obtain, set, and subscribe to or unsubscribe from sensor data. The following table lists the APIs provided by the sensor driver module.
Table 1 Major HDIs of the sensor module
Usage Guidelines
Sample code
#include "sensor_if.h"
#include "sensor_type.h"
/* Create a callback. */
void SensorDataCallback(struct SensorEvents *event)
{
if(event == NULL){
return;
}
float *sensorData=(float *)event->data;
printf("sensor data[%f]", *sensorData);
}
void SensorSample(void)
{
int ret;
struct SensorInformation *sensorInfo = NULL;
int32_t count = 0;
int32_t sensorInterval = 200000000; /* Set the data sampling rate to 200000000, in the unit of nanoseconds (200 ms). */
/* 1. Create a SensorInterface instance. */
const struct SensorInterface *sensorDev = NewSensorInterfaceInstance();
if (sensorDev == NULL) {
return;
}
/* 2. Register a sensor data callback. */
ret = sensorDev->Register(0, SensorDataCallback);
if (ret != 0) {
return;
}
/* 3. Obtain the list of sensors supported by the device. */
ret = sensorDev->GetAllSensors(&sensorInfo, &count);
if (ret != 0) {
return;
}
/* 4. Set the sensor sampling rate. */
ret = sensorDev->SetBatch(SENSOR_TYPE_ACCELEROMETER, sensorInterval, 0);
if (ret != 0) {
return;
}
/* 5. Enable the sensor. */
ret = sensorDev->Enable(SENSOR_TYPE_ACCELEROMETER);
if (ret != 0) {
return;
}
/* 6. Disable the sensor. */
ret = sensorDev->Disable(SENSOR_TYPE_ACCELEROMETER);
if (ret != 0) {
return;
}
/* 7. Unregister the sensor data callback. */
ret = sensorDev->Unregister(0);
if (ret != 0) {
return;
}
/* 8. Release the SensorInterface instance.
ret = FreeSensorInterfaceInstance();
if (ret != 0) {
return;
}
}