GD32F4xx的ADC采样分辨率可配置,最高12位
1、在工程中添加gd32f4xx_adc.c 源文件以及头文件到工程中,如下图所示:
2、新建一个adc.c 和 adc.h文件,并添加到工程当中
在adc.c文件中进行ADC的初始化以及配置
///adc.c 文件
#include "adc.h"
#define ADC_BASE_VOL 3300 //ADC基准电压
int32_t adc_opt_init(void)
{
adc_deinit();
rcu_periph_clock_enable(RCU_ADC0);//初始化时钟
rcu_periph_clock_enable(RCU_GPIOA);
adc_clock_config(ADC_ADCCK_PCLK2_DIV4);//时钟分频
(void)gpio_mode_set(GPIOA, GPIO_MODE_ANALOG, GPIO_PUPD_NONE, GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6);
adc_channel_length_config(ADC0,ADC_REGULAR_CHANNEL,8);//通道长度
adc_regular_channel_config(ADC0,0,ADC_CHANNEL_4,ADC_SAMPLETIME_144);//通道配置
adc_regular_channel_config(ADC0,0,ADC_CHANNEL_5,ADC_SAMPLETIME_144);
adc_regular_channel_config(ADC0,0,ADC_CHANNEL_6,ADC_SAMPLETIME_144);
adc_special_function_config(ADC0,ADC_CONTINUOUS_MODE,ENABLE);
adc_data_alignment_config(ADC0,ADC_DATAALIGN_RIGHT);//LSB模式
adc_resolution_config(ADC0,ADC_RESOLUTION_12B);//ADC分辨率配置
adc_sync_mode_config(ADC_SYNC_MODE_INDEPENDENT);
adc_sync_delay_config(ADC_SYNC_DELAY_5CYCLE);//采样周期
adc_enable(ADC0);
delay_1ms(1);
adc_calibration_enable(ADC0);
return 0;
}
//将获取的到通道AD值转化成对应电压值
uint32_t adc_opt_get_adc_vol(uint8_t channel)
{
uint16_t ad_val=0;
uint32_t vol=0;
ad_val = adc_opt_m_get_channel_data(channel);
vol = (ad_val*ADC_BASE_VOL)/4095;
return vol;
}
uint16_t adc_opt_m_get_channel_data(uint8_t channel)//获取通道的AD值
{
uint16_t ad_value=0;
/* ADC regular channel config */
adc_regular_channel_config(ADC0,0,channel,ADC_SAMPLETIME_144);
/* ADC software trigger enable */
adc_software_trigger_enable(ADC0, ADC_REGULAR_CHANNEL);
/* wait the end of conversion flag */
while(!adc_flag_get(ADC0, ADC_FLAG_EOC));
ad_value = adc_regular_data_read(ADC0);
/* clear the end of conversion flag */
adc_flag_clear(ADC0, ADC_FLAG_EOC);
/* return regular channel sample value */
return ad_value;
}
void adc_opt_stop(void)
{
adc_disable(ADC0);//禁用ADC0
}
//adc.h文件
#ifndef _ADC_H_
#define _ADC_H_
#include "gd32f4xx.h"
#include "systick.h"
int32_t adc_opt_init(void);
uint16_t adc_opt_m_get_channel_data(uint8_t channel);
uint32_t adc_opt_get_adc_vol(uint8_t channel);
#endif
3、在main函数中进行初始化调用以及读取采样电压
4、下载编写好的软件进行调试,查看读取到的电压值:
我这里配置的采样通道是4、5、6通道,这里可以查看到通道5的采样值为4097,基准电压使用的是3.3V,采样值转换成电压值为3.287V,使用万用表量电压值也基本一致。因此GD32F4xx的AD采样配置基本无误。