drv_adc.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. #include "board.h"
  11. #include "drv_adc.h"
  12. #include "hardware/adc.h"
  13. #ifdef BSP_USING_ADC
  14. #define DBG_TAG "drv.adc"
  15. #define DBG_LVL DBG_INFO
  16. #include <rtdbg.h>
  17. static struct pico_adc_config adc_config[] =
  18. {
  19. #ifdef BSP_USING_ADC0
  20. ADC0_CONFIG,
  21. #endif
  22. #ifdef BSP_USING_ADC1
  23. ADC1_CONFIG,
  24. #endif
  25. #ifdef BSP_USING_ADC2
  26. ADC2_CONFIG,
  27. #endif
  28. };
  29. static struct pico_adc pico_adc_obj[sizeof(adc_config) / sizeof(adc_config[0])];
  30. static rt_err_t pico_adc_enabled(struct rt_adc_device *device, rt_int8_t channel, rt_bool_t enabled)
  31. {
  32. struct pico_adc_config *pico_adc_handler;
  33. RT_ASSERT(device != RT_NULL);
  34. pico_adc_handler = device->parent.user_data;
  35. if (enabled)
  36. {
  37. adc_gpio_init(pico_adc_handler->pin);
  38. adc_select_input(pico_adc_handler->channel);
  39. }
  40. return RT_EOK;
  41. }
  42. static rt_err_t pico_adc_get_value(struct rt_adc_device *device, rt_int8_t channel, rt_uint32_t *value)
  43. {
  44. RT_ASSERT(device != RT_NULL);
  45. RT_ASSERT(value != RT_NULL);
  46. /* get ADC value */
  47. *value = (rt_uint32_t)adc_read();
  48. return RT_EOK;
  49. }
  50. static const struct rt_adc_ops pico_adc_ops =
  51. {
  52. .enabled = pico_adc_enabled,
  53. .convert = pico_adc_get_value,
  54. .get_resolution = RT_NULL,
  55. .get_vref = RT_NULL,
  56. };
  57. int rt_hw_adc_init(void)
  58. {
  59. int result = RT_EOK;
  60. adc_init();
  61. for (rt_size_t i = 0; i < sizeof(pico_adc_obj) / sizeof(struct pico_adc); i++)
  62. {
  63. /* register ADC device */
  64. 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)
  65. {
  66. LOG_D("%s init success", adc_config[i].device_name);
  67. }
  68. else
  69. {
  70. LOG_E("%s register failed", adc_config[i].device_name);
  71. result = -RT_ERROR;
  72. }
  73. }
  74. return result;
  75. }
  76. INIT_BOARD_EXPORT(rt_hw_adc_init);
  77. #endif /* BSP_USING_ADC */