#include <driver/adc.h>
void setup()
{
// https://dl.espressif.com/doc/esp-idf/latest/api-reference/peripherals/adc.html
// set up A:D channels
adc1_config_width(ADC_WIDTH_12Bit);
adc1_config_channel_atten(ADC1_CHANNEL_6, ADC_ATTEN_DB_11);
}
//
void TaskAnalogVoltRead_LIDAR( void *pvParameters )
{
// String localBuffer;
// localBuffer.reserve ( StringBufferSize300 );
int iBit = 1;
float ADbits = 4095.0f;
float offSET = 1.0f;
float r1 = 100800.0f; // R1 in ohm, 100k = 100,800.0 //
float r2 = 38780.0f; // R2 in ohm, 38k = 38000.0 //actual 38780K
float uPvolts = 3.3f;
// ADC1 channel 0 is GPIO36
// ADC1 channel 1 is GPIO37
// ADC1 channel 6 is GPIO34
// https://dl.espressif.com/doc/esp-idf/latest/api-reference/peripherals/adc.html
// to get resistor R2 go to:
// http://www.ohmslawcalculator.com/voltage-divider-calculator
// used 12 volts for the input voltage to calculate R2, used 100K for R1
for (;;)
{
// group handle, WaitForBits, ClearOnExitBit, WaitForAllBits, TicksToWait
xEventGroupWaitBits( eg, evtAnalogVoltReadTask_LIDAR, pdTRUE, pdTRUE, portMAX_DELAY );
// // read the input
iBit = iBit << 1;
if ( iBit == 1073741824 )
{
if ( xSemaphoreTake( sema_AnalogVoltRead_LIDAR, xSemaphoreTicksToWait ) == pdTRUE )
{
ptrVbatt_LIDAR[0] += ( ((( uPvolts * adc1_get_raw(ADC1_CHANNEL_6)) / ADbits) / r2 * ( r1 + r2)) + offSET );
} // if ( xSemaphoreTake( sema_AnalogVoltRead_LIDAR, xSemaphoreTicksToWait ) == pdTRUE )
iBit = 1;
} // if ( iBit == 1073741824 )
}
vTaskDelete( NULL );
}
Some code removed but the basics of using the ESP32 AD API