2 * Copyright (C) 2014 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);
54 void gyro_store_data (sensor_info_t* info)
57 gyro_cal_t* cal_data = (gyro_cal_t*) info->cal_data;
63 data_file = fopen (GYRO_CALIBRATION_PATH, "w");
65 if (data_file == NULL)
68 ret = fprintf(data_file, "%f %f %f",
69 cal_data->bias_x, cal_data->bias_y, cal_data->bias_z);
72 ALOGE ("Gyro calibration - store data failed!");
78 static int gyro_collect (float x, float y, float z, gyro_cal_t* cal_data)
80 /* Analyze gyroscope data */
82 if (fabs(x) >= 1 || fabs(y) >= 1 || fabs(z) >= 1) {
84 /* We're supposed to be standing still ; start over */
87 return 0; /* Uncalibrated */
90 if (cal_data->count < GYRO_DS_SIZE) {
92 if (x < cal_data->min_x)
95 if (y < cal_data->min_y)
98 if (z < cal_data->min_z)
101 if (x > cal_data->max_x)
104 if (y > cal_data->max_y)
107 if (z > cal_data->max_z)
110 if (fabs(cal_data->max_x - cal_data->min_x) <= GYRO_MAX_ERR &&
111 fabs(cal_data->max_y - cal_data->min_y) <= GYRO_MAX_ERR &&
112 fabs(cal_data->max_z - cal_data->min_z) <= GYRO_MAX_ERR)
113 cal_data->count++; /* One more conformant sample */
115 reset(cal_data); /* Out of spec sample ; start over */
117 return 0; /* Still uncalibrated */
120 /* We got enough stable samples to estimate gyroscope bias */
121 cal_data->bias_x = (cal_data->max_x + cal_data->min_x) / 2;
122 cal_data->bias_y = (cal_data->max_y + cal_data->min_y) / 2;
123 cal_data->bias_z = (cal_data->max_z + cal_data->min_z) / 2;
125 return 1; /* Calibrated! */
129 void calibrate_gyro (sensors_event_t* event, sensor_info_t* info)
131 gyro_cal_t* cal_data = (gyro_cal_t*) info->cal_data;
133 if (cal_data == NULL)
136 /* Attempt gyroscope calibration if we have not reached this state */
137 if (info->cal_level == 0)
138 info->cal_level = gyro_collect(event->data[0], event->data[1],
139 event->data[2], cal_data);
142 event->data[0] = event->data[0] - cal_data->bias_x;
143 event->data[1] = event->data[1] - cal_data->bias_y;
144 event->data[2] = event->data[2] - cal_data->bias_z;
147 event->gyro.status = SENSOR_STATUS_ACCURACY_HIGH;