Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Nemo64
Last active April 8, 2021 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nemo64/8756f6bde37d5225be629a3daf346c7b to your computer and use it in GitHub Desktop.
Save Nemo64/8756f6bde37d5225be629a3daf346c7b to your computer and use it in GitHub Desktop.
A class to take multiple samples of the ESP32 ADC
#include "SmoothAdc.h"
// define all the channels you want to watch
SmoothAdc<ADC1_CHANNEL_0, ADC1_CHANNEL_3> adc;
esp_adc_cal_characteristics_t adc1_chars;
void setup() {
Serial.begin(115200);
// configure and characterize the adc1
esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, ADC_WIDTH_12Bit, 1100, &adc1_chars);
adc1_config_width(adc1_chars.bit_width);
adc1_config_channel_atten(ADC1_CHANNEL_0, adc1_chars.atten);
adc1_config_channel_atten(ADC1_CHANNEL_3, adc1_chars.atten);
// start the asynchronious job to sample the adc
adc.xTaskCreate();
}
void loop() {
delay(1000);
auto v1 = esp_adc_cal_raw_to_voltage(adc.sample(0), &adc1_chars);
Serial.print(v1);
Serial.print(" ");
auto v2 = esp_adc_cal_raw_to_voltage(adc.sample(1), &adc1_chars);
Serial.print(v2);
Serial.println(" mv");
}
#pragma once
#include <driver/adc.h>
template<adc1_channel_t... PINS>
class SmoothAdc {
private:
const adc1_channel_t pins[sizeof...(PINS)] = {PINS...};
volatile uint32_t results[sizeof...(PINS)] = {};
uint16_t reads[sizeof...(PINS)][256] = {};
uint8_t position = 0;
public:
uint16_t sample(size_t pin) {
return results[pin] / 256;
}
void xTaskCreate(const UBaseType_t priority = 1, const BaseType_t xCoreID = -1) {
::xTaskCreateUniversal(task, "SmoothAdc", 1024, this, priority, NULL, xCoreID);
}
private:
void static task (void * parameter) {
auto self = (SmoothAdc *)parameter;
for (;;) {
delay(8 - millis() % 8);
self->measure();
}
}
void measure() {
for (size_t i = 0; i < sizeof...(PINS); ++i) {
adc1_get_raw(pins[i]); // ignore the value on first try
uint16_t read = adc1_get_raw(pins[i]);
results[i] += read - reads[i][position];
reads[i][position] = read;
}
++position;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment