Using the ADC on a Wemos ESP8266 device
/I want to use an analogue to digital converter in my Connected Little Boxes project to convert a rotary position as set by the knob on the left hand box in the picture into a number I can use to control the servo on the right hand box. I like the idea of moving physical movement from one place to another.
An analogue to digital converter (ADC) is a piece of hardware that takes in a voltage and gives you a number that represents the level of the voltage. ADCs are useful to measure things like the battery voltage levels and for converting analogue sound signals into a sequence of digital values.
A potentiometer is a special kind of resistor. Turning the shaft of the potentiometer moves a contact along a circular carbon film in a way that allows the output to produce a different voltage output depending on the position of the contact. If I connect the output of the potentiometer into the ADC of my ESP8266 I can write a program that will read the position of the potentiometer and use this to control the servo.
The ESP8266 chip has a single ADC device which reads signal levels up to 1.8 volts or so. The good news is that my favourite ESP8266 based device, the Wemos D1 mini, has a “potential divider” circuit on the board that allows the input to accept inputs up to the 3.3 volt power supply. You can wire it up as shown above. Remember to use the 3v3 pin rather than the 5v one. Turning the knob on the potentiometer will move the input on the A0 pin between 0 and 3.3 volts.
You can use the ADC in your program like this:
int reading = analogRead(0);
If the input sees 0 volts you get the value 0 set in the variable reading. If the input sees 3.3 volts you get the value 1023. The numbers are fairly steady, although I see a bit of noise which causes the values to “jitter” around a bit. I’ve added some code that ignores changes of around 5 or so in the value.
I send the reading value across to the little box on the right of the picture above so that the position of the servo tracks the knob. It works really well, but in making it work I learned something which you might find useful to impress people with at any parties (or Microsoft Teams meetings) that you might go to in the future.
ADC Problems with the ESP8266
It turns out that reading from the ADC on an ESP8266 gets in the way of setting up a WiFi connection. If the device is connecting to a WiFi access point and your program reads the ADC while this is happening the connection will not be setup properly. I’ve had to modify the code so that it only starts to read from the ADC once a connection has been established.