#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "driver/adc.h"
#include "esp_adc_cal.h"
// Number of readings for multiple sampling
#define NO_OF_SAMPLES 32
// Add a little hysteresis to prevent continuous messages (increase if necessary)
#define ADC_HYSTERESIS 2
// Defualt ADC voltage reference (internal)
#define DEFAULT_VREF 1100
static const adc1_channel_t channel = ADC1_CHANNEL_4; // GPIO32
static const adc_bits_width_t width = ADC_WIDTH_BIT_12;
static const adc_atten_t atten = ADC_ATTEN_DB_12;
static esp_adc_cal_characteristics_t *adc_chars;
static void print_char_val_type(esp_adc_cal_value_t val_type) {
if (val_type == ESP_ADC_CAL_VAL_EFUSE_TP) {
Serial.printf("Characterized using Two Point Value\n");
} else if (val_type == ESP_ADC_CAL_VAL_EFUSE_VREF) {
Serial.printf("Characterized using eFuse Vref\n");
} else {
Serial.printf("Characterized using Default Vref\n");
}
}
void adc_task(void *pvParameter) {
long old_reading = 0;
while (1) {
long adc_reading = 0;
for (int i = 0; i < NO_OF_SAMPLES; i++) {
adc_reading += adc1_get_raw((adc1_channel_t) channel);
vTaskDelay(pdMS_TO_TICKS(1));
}
adc_reading /= NO_OF_SAMPLES;
if (abs(adc_reading - old_reading) > 5) {
old_reading = adc_reading;
uint32_t voltage = esp_adc_cal_raw_to_voltage(adc_reading, adc_chars);
Serial.printf("Raw ADC value: %ld; voltage: %ld mV\n", adc_reading, voltage);
}
vTaskDelay(pdMS_TO_TICKS(10));
}
vTaskDelete(NULL);
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
// Characterize ADC
adc_chars = (esp_adc_cal_characteristics_t*) calloc(1, sizeof(esp_adc_cal_characteristics_t));
esp_adc_cal_value_t val_type = esp_adc_cal_characterize(ADC_UNIT_1, atten, width, DEFAULT_VREF, adc_chars);
print_char_val_type(val_type);
adc1_config_width(width);
adc1_config_channel_atten(channel, atten);
xTaskCreate(adc_task, "adc_task", 4096, NULL, 2, NULL);
}
void loop() {
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
}