2 * Copyright (C) 2014-2015 Intel Corporation.
9 #include <hardware/sensors.h>
11 #include "calibration.h"
15 #define GYRO_MAX_ERR 0.05
16 #define GYRO_DS_SIZE 100
17 #define GYRO_CALIBRATION_PATH "/data/gyro.conf"
20 static void reset (gyro_cal_t* cal_data)
24 cal_data->bias_x = cal_data->bias_y = cal_data->bias_z = 0;
26 cal_data->min_x = cal_data->min_y = cal_data->min_z = 1.0;
27 cal_data->max_x = cal_data->max_y = cal_data->max_z =-1.0;
31 void gyro_cal_init (sensor_info_t* info)
34 gyro_cal_t* cal_data = (gyro_cal_t*) info->cal_data;
44 data_file = fopen (GYRO_CALIBRATION_PATH, "r");
45 if (data_file == NULL)
48 ret = fscanf(data_file, "%f %f %f",
49 &cal_data->bias_x, &cal_data->bias_y, &cal_data->bias_z);
51 ALOGE("Gyro calibration - init failed!\n");
57 void gyro_store_data (sensor_info_t* info)
60 gyro_cal_t* cal_data = (gyro_cal_t*) info->cal_data;
66 data_file = fopen (GYRO_CALIBRATION_PATH, "w");
68 if (data_file == NULL)
71 ret = fprintf(data_file, "%f %f %f",
72 cal_data->bias_x, cal_data->bias_y, cal_data->bias_z);
75 ALOGE ("Gyro calibration - store data failed!");
81 static int gyro_collect (float x, float y, float z, gyro_cal_t* cal_data)
83 /* Analyze gyroscope data */
85 if (fabs(x) >= 1 || fabs(y) >= 1 || fabs(z) >= 1) {
87 /* We're supposed to be standing still ; start over */
90 return 0; /* Uncalibrated */
93 if (cal_data->count < GYRO_DS_SIZE) {
95 if (x < cal_data->min_x)
98 if (y < cal_data->min_y)
101 if (z < cal_data->min_z)
104 if (x > cal_data->max_x)
107 if (y > cal_data->max_y)
110 if (z > cal_data->max_z)
113 if (fabs(cal_data->max_x - cal_data->min_x) <= GYRO_MAX_ERR &&
114 fabs(cal_data->max_y - cal_data->min_y) <= GYRO_MAX_ERR &&
115 fabs(cal_data->max_z - cal_data->min_z) <= GYRO_MAX_ERR)
116 cal_data->count++; /* One more conformant sample */
118 reset(cal_data); /* Out of spec sample ; start over */
120 return 0; /* Still uncalibrated */
123 /* We got enough stable samples to estimate gyroscope bias */
124 cal_data->bias_x = (cal_data->max_x + cal_data->min_x) / 2;
125 cal_data->bias_y = (cal_data->max_y + cal_data->min_y) / 2;
126 cal_data->bias_z = (cal_data->max_z + cal_data->min_z) / 2;
128 return 1; /* Calibrated! */
132 void calibrate_gyro (sensors_event_t* event, sensor_info_t* info)
134 gyro_cal_t* cal_data = (gyro_cal_t*) info->cal_data;
136 if (cal_data == NULL)
139 /* Attempt gyroscope calibration if we have not reached this state */
140 if (info->cal_level == 0)
141 info->cal_level = gyro_collect(event->data[0], event->data[1],
142 event->data[2], cal_data);
145 event->data[0] = event->data[0] - cal_data->bias_x;
146 event->data[1] = event->data[1] - cal_data->bias_y;
147 event->data[2] = event->data[2] - cal_data->bias_z;
150 event->gyro.status = SENSOR_STATUS_ACCURACY_HIGH;