1 /*
2  * Copyright (c) 2006-2023, RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author       Notes
8  * 2023-06-04     Chushicheng  first version
9  */
10 
11 #include "board.h"
12 #include "drv_adc.h"
13 #include "hardware/adc.h"
14 
15 #ifdef BSP_USING_ADC
16 #define DBG_TAG              "drv.adc"
17 #define DBG_LVL               DBG_INFO
18 #include <rtdbg.h>
19 
20 static struct pico_adc_config adc_config[] =
21 {
22 #ifdef BSP_USING_ADC0
23     ADC0_CONFIG,
24 #endif
25 
26 #ifdef BSP_USING_ADC1
27     ADC1_CONFIG,
28 #endif
29 
30 #ifdef BSP_USING_ADC2
31     ADC2_CONFIG,
32 #endif
33 };
34 
35 static struct pico_adc pico_adc_obj[sizeof(adc_config) / sizeof(adc_config[0])];
36 
pico_adc_enabled(struct rt_adc_device * device,rt_int8_t channel,rt_bool_t enabled)37 static rt_err_t pico_adc_enabled(struct rt_adc_device *device, rt_int8_t channel, rt_bool_t enabled)
38 {
39     struct pico_adc_config *pico_adc_handler;
40     RT_ASSERT(device != RT_NULL);
41     pico_adc_handler = device->parent.user_data;
42 
43     if (enabled)
44     {
45         adc_gpio_init(pico_adc_handler->pin);
46         adc_select_input(pico_adc_handler->channel);
47     }
48 
49     return RT_EOK;
50 }
51 
pico_adc_get_value(struct rt_adc_device * device,rt_int8_t channel,rt_uint32_t * value)52 static rt_err_t pico_adc_get_value(struct rt_adc_device *device, rt_int8_t channel, rt_uint32_t *value)
53 {
54     RT_ASSERT(device != RT_NULL);
55     RT_ASSERT(value != RT_NULL);
56 
57     /* get ADC value */
58     *value = (rt_uint32_t)adc_read();
59 
60     return RT_EOK;
61 }
62 
63 static const struct rt_adc_ops pico_adc_ops =
64 {
65     .enabled = pico_adc_enabled,
66     .convert = pico_adc_get_value,
67     .get_resolution = RT_NULL,
68     .get_vref = RT_NULL,
69 };
70 
rt_hw_adc_init(void)71 int rt_hw_adc_init(void)
72 {
73     int result = RT_EOK;
74 
75     adc_init();
76 
77     for (rt_size_t i = 0; i < sizeof(pico_adc_obj) / sizeof(struct pico_adc); i++)
78     {
79         /* register ADC device */
80         if (rt_hw_adc_register(&pico_adc_obj[i].pico_adc_device, adc_config[i].device_name, &pico_adc_ops, &adc_config[i]) == RT_EOK)
81         {
82             LOG_D("%s init success", adc_config[i].device_name);
83         }
84         else
85         {
86             LOG_E("%s register failed", adc_config[i].device_name);
87             result = -RT_ERROR;
88         }
89     }
90 
91     return result;
92 }
93 INIT_BOARD_EXPORT(rt_hw_adc_init);
94 
95 #endif /* BSP_USING_ADC */
96