363f2c6c67f87af7b8a005237d0e5223651d79e0
[apps/native/st-things-co2-meter.git] / src / co2-sensor.c
1 /* ****************************************************************
2  *
3  * Copyright 2017 Samsung Electronics All Rights Reserved.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  ******************************************************************/
18
19 #include <peripheral_io.h>
20 #include "adc-mcp3008.h"
21 #include "log.h"
22
23 #define CO2_SENSOR_REF_VOLTAGE (5)
24 #define CO2_SENSOR_VALUE_MAX (1024)
25
26 static bool initialized = false;
27
28 void co2_sensor_close(void)
29 {
30         adc_mcp3008_fini();
31         initialized = false;
32 }
33
34 int co2_sensor_read(int ch_num, unsigned int *out_value)
35 {
36         unsigned int read_value = 0;
37         int ret = 0;
38
39         if (!initialized) {
40                 ret = adc_mcp3008_init();
41                 retv_if(ret != 0, -1);
42                 initialized = true;
43         }
44         ret = adc_mcp3008_read(ch_num, &read_value);
45         retv_if(ret != 0, -1);
46
47         *out_value = read_value;
48
49         return 0;
50 }
51
52 double co2_sensor_value_to_voltage(unsigned int value)
53 {
54         double v = 0;
55
56         v = (double)value * CO2_SENSOR_REF_VOLTAGE / CO2_SENSOR_VALUE_MAX;
57
58         return v;
59 }
60
61 /* Not implemented, please see c source code */
62 unsigned int co2_sensor_voltage_to_ppm(double voltage)
63 {
64         int ppm = 0;
65
66         /* Make this function yourself */
67         /* Please ref. 'Theory' section in https://sandboxelectronics.com/?p=147#Theory */
68
69         return ppm;
70 }
71
72 unsigned int co2_sensor_value_to_ppm(unsigned int value)
73 {
74         /* You can use this function after implementing co2_sensor_voltage_to_ppm() function */
75         return co2_sensor_voltage_to_ppm(co2_sensor_value_to_voltage(value));
76 }
77