ESP8266 Read ADC Values Micropython

ADC stands for “Analog to Digital Convertor”. As the name suggests, it takes an analog signal as input and gives it’s digital equivalent value as output. In embedded systems ADCs are used all the time whenever something is to be measured; be it the temprature, pressure, weight, voltage, current; anything like that.

Usually the sensors that give analog values as an output are connected to the ADC of the microcontroller.

With micropython it becomes very easy to read adc values from ESP8266. It is literally three lines of code.

To initiate ADC on ESP8266

>>> import machine
>>> adc = machine.ADC(0) # this is the pin A0 on NodeMcu ESp8266 module.

To read the Adc values:

>>> adc.read()

Following is the code that connects to the wifi, connects to the mqtt server and publishes ADC values on a perticular topic after a regular interval.

from umqtt.simple import MQTTClient
import time
import network
import machine


config = {"wifiSSID": "<Your-SSID>",
          "wifiPass": "<Your-Password>",
          "ip": "<IP-Of-your-server>",
          "nodeId": "Node3"}

# Connect to Wifi
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect(config['wifiSSID'], config['wifiPass'])

# initialize the the ADC
adc = machine.ADC(0)

# this is the delay after which the adc input will be read.
interval = 5


def sub_cb(topic, msg):
    print(msg, topic)
    # change the interval
    interval = int(msg)


def main(server=config['ip']):
    time.sleep(5)
    # connect to the Mqtt Broker (Mosquitto)
    c = MQTTClient('umqtt_client', server)
    c.set_callback(sub_cb)
    try:
        c.connect()
        print(b'{}/input'.format(config['nodeId']))
        c.subscribe(b'{}/input'.format(config['nodeId']))
    except OSError:
        main()

    while True:
        c.check_msg()
        val = adc.read() # read the adc value
        print(str(val))
        c.publish("Node3/output", str(val)) # publish the adc value
        time.sleep(interval)

    c.disconnect()

main()
comments powered by Disqus