1 /*
2 * Copyright (C) 2015-2020 Alibaba Group Holding Limited
3 */
4 #include "exp_adc.h"
5 #include "aos/kernel.h"
6 #include "hal_iomux_haas1000.h"
7 #include "ulog/ulog.h"
8 #include <stdio.h>
9
10 #define TAG "ex_adc"
11
12 typedef struct {
13 uint8_t installed;
14 adc_dev_t st_adc_info;
15 } exp_adc_dev_t;
16
17 #define ADC_DEFAULT_TIMEOUT 3000
18 #define ADC_MAX_VALUE 3300
19 #define ADC_AVERAGE_TIME 32
20
21 /*exp adc device*/
22 static exp_adc_dev_t exp_adc_dev[ADC_PORT_SIZE] = {
23 {0, {2, {1000}, NULL}}, // not installed
24 {0, {1, {1000}, NULL}},
25 {0, {0, {1000}, NULL}},
26 };
27
expansion_board_adc_init(void)28 int32_t expansion_board_adc_init(void)
29 {
30 int32_t ret = 0;
31 int32_t i = 0;
32
33 for (i = 0; i < ADC_PORT_SIZE; i++) {
34 if (exp_adc_dev[i].installed) {
35 continue;
36 }
37 ret = hal_adc_init(&exp_adc_dev[i].st_adc_info);
38 if (ret) {
39 LOGE(TAG, "adc port %d init fail %d ", i, ret);
40 return -1;
41 }
42 exp_adc_dev[i].installed = 1;
43 }
44
45 return 0;
46 }
47
expansion_board_adc_get_value(uint32_t port,uint32_t * adc_value)48 int32_t expansion_board_adc_get_value(uint32_t port, uint32_t *adc_value)
49 {
50 int32_t ret = 0;
51 uint32_t i = 0;
52 uint32_t adc_sum = 0;
53 uint32_t adc_avrg = 0;
54 /*for haas1000 adc max value */
55 uint32_t adc_min = ADC_MAX_VALUE;
56 uint32_t adc_max = 0;
57
58 if (port >= ADC_PORT_SIZE || NULL == adc_value) {
59 LOGE(TAG, "%s %d invalid input port %d", __FILE__, __LINE__, port);
60 return -1;
61 }
62
63 if (exp_adc_dev[port].installed == 0) {
64 LOGE(TAG, "exp adc %d haven't init yet , get value fail", port);
65 return -1;
66 }
67 ret = hal_adc_value_get(&exp_adc_dev[port].st_adc_info, adc_value, ADC_DEFAULT_TIMEOUT);
68 if (ret) {
69 LOGE(TAG, "Get adc %d port value fail ", port);
70 return -1;
71 }
72 return 0;
73
74 }
75
board_get_voltage(uint32_t port,uint32_t * output)76 int32_t board_get_voltage(uint32_t port, uint32_t *output)
77 {
78 int32_t ret = 0;
79 uint32_t i = 0;
80 uint32_t adc_sum = 0;
81 uint32_t adc_avrg = 0;
82 /*for haas1000 adc max value */
83 uint32_t adc_min = ADC_MAX_VALUE;
84 uint32_t adc_max = 0;
85 uint32_t adc_value = 0;
86
87 for (i = 0; i < ADC_AVERAGE_TIME + 2; i++)
88 {
89 ret = expansion_board_adc_get_value(port, &adc_value);
90 if (ret) {
91 LOGE(TAG, "Get adc %d port value fail ", port);
92 return -1;
93 }
94 adc_sum += adc_value;
95
96 /* the min sampling voltage */
97 if (adc_min >= adc_value)
98 {
99 adc_min = output;
100 }
101 /* the max sampling voltage */
102 if (adc_max <= output)
103 {
104 adc_max = output;
105 }
106
107 aos_msleep(20);
108 }
109 /*adc sum value reduce adc min value reduse adc max value; and divided by
110 * 32*/
111 adc_avrg = (adc_sum - adc_min - adc_max) >> 5;
112 *output = adc_avrg;
113 return 0;
114 }
115