adc_vol_sample.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright (c) 2006-2022, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018-11-29 misonyo first implementation.
  9. */
  10. /*
  11. * 程序清单: ADC 设备使用例程
  12. * 例程导出了 adc_sample 命令到控制终端
  13. * 命令调用格式:adc_sample
  14. * 程序功能:通过 ADC 设备采样电压值并转换为数值。
  15. * 示例代码参考电压为3.3V,转换位数为12位。
  16. */
  17. #include <rtthread.h>
  18. #include <rtdevice.h>
  19. #define ADC_DEV_NAME "adc1" /* ADC 设备名称 */
  20. #define ADC_DEV_CHANNEL 5 /* ADC 通道 */
  21. #define REFER_VOLTAGE 330 /* 参考电压 3.3V,数据精度乘以100保留2位小数*/
  22. #define CONVERT_BITS (1 << 12) /* 转换位数为12位 */
  23. static int adc_vol_sample(int argc, char *argv[])
  24. {
  25. rt_adc_device_t adc_dev;
  26. rt_uint32_t value, vol;
  27. rt_err_t ret = RT_EOK;
  28. /* 查找设备 */
  29. adc_dev = (rt_adc_device_t)rt_device_find(ADC_DEV_NAME);
  30. if (adc_dev == RT_NULL)
  31. {
  32. rt_kprintf("adc sample run failed! can't find %s device!\n", ADC_DEV_NAME);
  33. return RT_ERROR;
  34. }
  35. /* 使能设备 */
  36. ret = rt_adc_enable(adc_dev, ADC_DEV_CHANNEL);
  37. /* 读取采样值 */
  38. value = rt_adc_read(adc_dev, ADC_DEV_CHANNEL);
  39. rt_kprintf("the value is :%d \n", value);
  40. /* 转换为对应电压值 */
  41. vol = value * REFER_VOLTAGE / CONVERT_BITS;
  42. rt_kprintf("the voltage is :%d.%02d \n", vol / 100, vol % 100);
  43. /* 关闭通道 */
  44. ret = rt_adc_disable(adc_dev, ADC_DEV_CHANNEL);
  45. return ret;
  46. }
  47. /* 导出到 msh 命令列表中 */
  48. MSH_CMD_EXPORT(adc_vol_sample, adc voltage convert sample);