Bootstrap

RT-Thread OS ADC 模数转换使用

使用RT-Thread Studio 编程步骤:

1. 首先找到board.h中关于ADC配置部分,完成以下步骤

/*-------------------------- ADC CONFIG BEGIN --------------------------*/

/** if you want to use adc you can use the following instructions.
 *
 * STEP 1, open adc driver framework support in the RT-Thread Settings file
 *
 * STEP 2, define macro related to the adc
 *                 such as     #define BSP_USING_ADC1
 *
 * STEP 3, copy your adc init function from stm32xxxx_hal_msp.c generated by stm32cubemx to the end of board.c file
 *                 such as     void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)
 *
 * STEP 4, modify your stm32xxxx_hal_config.h file to support adc peripherals. define macro related to the peripherals
 *                 such as     #define HAL_ADC_MODULE_ENABLED
 *
 */

其中使用STM32CubeMX生成的初始化代码为:

void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(hadc->Instance==ADC1)
  {
  /* USER CODE BEGIN ADC1_MspInit 0 */

  /* USER CODE END ADC1_MspInit 0 */
    /* Peripheral clock enable */
    __HAL_RCC_ADC1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**ADC1 GPIO Configuration
    PA1     ------> ADC1_IN1
    */
    GPIO_InitStruct.Pin = GPIO_PIN_1;
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /* USER CODE BEGIN ADC1_MspInit 1 */

  /* USER CODE END ADC1_MspInit 1 */
  }

}

将这个函数复制到board.c文件

完成上述步骤后就可以编写应用程序了

#include <rtthread.h>
#include <rtdevice.h>

#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

#define ADC_DEV_NAME        "adc1"  /* ADC 设备名称 */
#define ADC_DEV_CHANNEL     1      /* ADC 通道 */
#define REFER_VOLTAGE       330         /* 参考电压 3.3V,数据精度乘以100保留2位小数*/
#define CONVERT_BITS        (1 << 12)   /* 转换位数为12位 */

rt_adc_device_t adc_dev;            /* ADC 设备句柄 */
rt_uint32_t value;

int main(void)
{

    rt_uint32_t vol = 0;
    /* 查找设备 */
    adc_dev = (rt_adc_device_t)rt_device_find(ADC_DEV_NAME);
    /* 使能设备 */
    rt_adc_enable(adc_dev, ADC_DEV_CHANNEL);
    /* 读取采样值 */
    value = rt_adc_read(adc_dev, ADC_DEV_CHANNEL);
    /* 转换为对应电压值 */
    vol = value * REFER_VOLTAGE / CONVERT_BITS;
    rt_kprintf("the voltage is :%d.%02d \n", vol / 100, vol % 100);
    /* 关闭通道 */
    rt_adc_disable(adc_dev, ADC_DEV_CHANNEL);

    return RT_EOK;
}

烧录代码进stm32,将PA1引脚分别接到GND和Vcc,观察测到的电压:

PA1接GND:

[2022-11-01_16:09:48:251]- RT -     Thread Operating System
[2022-11-01_16:09:48:251] / | \     4.0.3 build Nov  1 2022
[2022-11-01_16:09:48:251] 2006 - 2020 Copyright by rt-thread team
[2022-11-01_16:09:48:267]the voltage is :0.00 
[2022-11-01_16:09:48:267]msh >

PA1接Vcc:

[2022-11-01_16:10:14:201] \ | /
[2022-11-01_16:10:14:201]- RT -     Thread Operating System
[2022-11-01_16:10:14:201] / | \     4.0.3 build Nov  1 2022
[2022-11-01_16:10:14:201] 2006 - 2020 Copyright by rt-thread team
[2022-11-01_16:10:14:201]the voltage is :3.29 

应用程序编程很简单:

1. 查找ADC设备

2.使能ADC设备

3.读取ADC输出值Value

4.通过Value计算测量得到的电压

;