ESP32-使用ADC笔记
基于ESP-IDF4.1
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include "freertos/FreeRTOS.h" 4 #include "freertos/task.h" 5 #include "driver/gpio.h" 6 #include "driver/adc.h" 7 #if CONFIG_IDF_TARGET_ESP32 8 #include "esp_adc_cal.h" 9 #endif 10 11 #define DEFAULT_VREF 1100 //使用 adc2_vref_to_gpio() 获得更好的估计值 12 #define NO_OF_SAMPLES 64 //多重采样 13 14 15 static esp_adc_cal_characteristics_t *adc_chars; 16 static const adc_channel_t channel = ADC_CHANNEL_6; //GPIO34 if ADC1, GPIO14 if ADC2 17 18 static const adc_atten_t atten = ADC_ATTEN_DB_0; 19 static const adc_unit_t unit = ADC_UNIT_1; 20 21 22 static void check_efuse(void) 23 { 24 //检查TP是否烧入eFuse 25 if (esp_adc_cal_check_efuse(ESP_ADC_CAL_VAL_EFUSE_TP) == ESP_OK) { 26 printf("eFuse Two Point: Supported\n"); 27 } else { 28 printf("eFuse Two Point: NOT supported\n"); 29 } 30 31 //检查Vref是否烧入eFuse 32 if (esp_adc_cal_check_efuse(ESP_ADC_CAL_VAL_EFUSE_VREF) == ESP_OK) { 33 printf("eFuse Vref: Supported\n"); 34 } else { 35 printf("eFuse Vref: NOT supported\n"); 36 } 37 } 38 39 static void print_char_val_type(esp_adc_cal_value_t val_type) 40 { 41 if (val_type == ESP_ADC_CAL_VAL_EFUSE_TP) { 42 printf("Characterized using Two Point Value\n"); 43 } else if (val_type == ESP_ADC_CAL_VAL_EFUSE_VREF) { 44 printf("Characterized using eFuse Vref\n"); 45 } else { 46 printf("Characterized using Default Vref\n"); 47 } 48 } 49 50 51 void app_main(void) 52 { 53 54 //检查TP和Vreff是否烧录进eFuse 55 check_efuse(); 56 57 //配置 ADC 58 if (unit == ADC_UNIT_1) { 59 adc1_config_width(ADC_WIDTH_BIT_12); 60 adc1_config_channel_atten(channel, atten); 61 } else { 62 adc2_config_channel_atten((adc2_channel_t)channel, atten); 63 } 64 65 //描述 ADC 66 adc_chars = calloc(1, sizeof(esp_adc_cal_characteristics_t)); 67 esp_adc_cal_value_t val_type = esp_adc_cal_characterize(unit, atten, ADC_WIDTH_BIT_12, DEFAULT_VREF, adc_chars); 68 print_char_val_type(val_type); 69 70 //连续采样ADC1 71 while (1) { 72 uint32_t adc_reading = 0; 73 //多重采样 74 for (int i = 0; i < NO_OF_SAMPLES; i++) { 75 if (unit == ADC_UNIT_1) { 76 adc_reading += adc1_get_raw((adc1_channel_t)channel); 77 } else { 78 int raw; 79 adc2_get_raw((adc2_channel_t)channel, ADC_WIDTH_BIT_12, &raw); 80 adc_reading += raw; 81 } 82 } 83 adc_reading /= NO_OF_SAMPLES; 84 85 //将ADC读取转换为毫伏的电压 86 uint32_t voltage = esp_adc_cal_raw_to_voltage(adc_reading, adc_chars); 87 printf("Raw: %d\tVoltage: %dmV\n", adc_reading, voltage); 88 89 vTaskDelay(pdMS_TO_TICKS(1000)); 90 } 91 }
原文:https://gitee.com/EspressifSystems/esp-idf/tree/master/examples/peripherals/adc