Built in ADC of ESP32 can be used to read analog values from sensors like potentiometer,LDR,Load cell,Thermistor,etc..
On the ESP32 ADC functionality is available on Pins 32-39.
Only the pins of ADC1 are enabled for ADC. ADC2 is not enabled in Micropython.
pins 36-39 are recommended for analog input due to the available preamplifier.
ESP32 ADC pins by default have 12 bit resolution.
These pins read voltage between 0 to 3.3v & return value between 0 and 4095
To get value bet 0-1023 CHANGE RESOLUTION TO 10 BIT
Connect a LDR to+3.3v , other end to Gnd through 10k Resistor.
The junction point of LDR & Resistor is connected to ADC GPIO Pin 36.
Open Thonny Python & use the interpreter to test ADC code.
From machine module import classes Pin & ADC.
Create ad adc object by passing on the GPIO Pin 36.
Read the analog value using read() method.
LDR faced to light gives some resistance , and the value is 1348.
This function returns a whole number between 0 and 4095. Because we know that 0 refers
to 0 V and 4095 refers to 3.3 V
In full dark condition (LDR closed) the value is 4095.
The ADC resolution by default is 12 bits
2 power 12 is 4096.
We can convert the reading to voltage by multiplying with 0.000805
2 power 12 is 4096
Voltage is 3.3v , 3.3/4096 = 0.000805
You can see , at full dark condition the ADC value is 3.3v
As per documentation of ESP32 the maximum ADC volt can be set using attenuation.
ADC.atten(attenuation)
This method allows for the setting of the amount of attenuation on the input of the ADC.
This allows for a wider possible input voltage range, at the cost of accuracy
(the same number of bits now represents a wider range). The possible attenuation options are:
ADC.ATTN_0DB: 0dB attenuation, gives a maximum input voltage of 1.00v – this is the default configuration (but while testing it shows 3.3v)
ADC.ATTN_2_5DB: 2.5dB attenuation, gives a maximum input voltage of approximately 1.34v
ADC.ATTN_6DB: 6dB attenuation, gives a maximum input voltage of approximately 2.00v
ADC.ATTN_11DB: 11dB attenuation, gives a maximum input voltage of approximately 3.6v
Setting the attenuation to 11DB gives value of 1.72 volt ( but the document says 3.3v)
So leave it to default 0DB which practically gives 3.3v
The resolution can be changed to 10 bit by setting width to 10BIT.
Default is 12 BIT.
ADC.width(width)
This method allows for the setting of the number of bits to be utilised and returned during ADC reads. Possible width options are:
ADC.WIDTH_9BIT: 9 bit data
ADC.WIDTH_10BIT: 10 bit data
ADC.WIDTH_11BIT: 11 bit data
ADC.WIDTH_12BIT: 12 bit data – this is the default configuration
After testing with interpreter we shall use the Editor to write code.
Save the file as main.py on to Micropython device.
Click on F5 to execute.
The analog output value is displayed according to light fall on LDR.
Video :