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
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
This section uses the acceleration sensor as an example to describe how to use sensor 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
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;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。