The code

Now is time to copy our code on the ESP8266-01.

All the code is downloadable from my git.hub.

Some libraries are needed which are not included in the distribution of MicroPython.
Here is a list of those libraries and where you can find them.

To copy these files on the ESP8266-01 I will use rshell whose basics I covered here. Remember that you want your ESP connected to the USB-TTL serial converter but not in flash mode.

Once your rshell promt (the one ending with “>” is there), navigate to the location of the files on you computer and use the following command to copy them.

[yourfolder]> cp file_name.py /pyboard

Is now time to open the ds_sensor.py file, as you will need to add some information.

The information you need is:

  • name of your SSID
  • password of your SSID
  • the IP of your MQTT server (in my case is the IP of my raspberry)
  • name of the client (for example “bedroom”)
  • username for the MQTT server
  • password for the MQTT server
  • topic

In case you have not configured yet your MQTT on Home Assistant, or are not too sure on where these information is have a look here.

The code is the following (but please refer to the one on git.hub)

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

s = 0
roms = []
c = 0
temp = 0
topic = ''
client_id = ''

def do_connect():
    SSID = 'your SSID'
    PASSWORD = 'your PWD'
    sta_if = network.WLAN(network.STA_IF)
    ap_if = network.WLAN(network.AP_IF)
    if ap_if.active():
        ap_if.active(False)
    if sta_if.active(False):
        sta_if.active()
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect(SSID, PASSWORD)
        while not sta_if.isconnected():
            pass
    print('Network configuration:', sta_if.ifconfig())
    
def switch_off_wifi():
    print('Switching off WLAN')
    sta_if = network.WLAN(network.STA_IF)
    sta_if.disconnect()  
    sta_if.active(False)

def set_sensor():
    dat = machine.Pin(2)
    ow = onewire.OneWire(dat)
    global ds
    ds = ds18x20.DS18X20(ow)
    global roms
    roms = ds.scan()
    print('found devices:', roms)

def read_sensor():    
    print('temperatures:', end=' ')
    ds.convert_temp()
    time.sleep_ms(750)
    for rom in roms:
        global temp
        temp = ds.read_temp(rom)
        if isinstance (temp, float):
            temp = round(temp, 2) #rounded to 2 digits from the decimal point
            print(temp, end=' ')
        else:
            print('error in reading sensor')
        print()
                        
def connect_mqtt():
    server = "server IP"
    global client_id
    client_id = "client" #insert your client ID
    username='user' #insert your MQTT username
    password='pwd' #insert your MQTT password
    global topic
    topic = ('sensor/temperature')
    global c
    c = MQTTClient(client_id,server,0,username,password)
    c.connect()
    time.sleep(3)

def publish_temp():
    print('publishing: ',temp)
    c.publish(topic, str(temp)) 
    time.sleep(3) #Wait to be sure the message has time to be sent

set_sensor()
while True:
    do_connect()
    connect_mqtt()
    read_sensor()
    publish_temp()
    switch_off_wifi()
    time.sleep(300) #sleep 5 minutes

Now that you have included the needed information you can save the file and copy it on the ESP8266-01.

NOTE

You can rename the file main.py and see if it gets executed when you restart everything (in this case it may help to have all the libraries’ files in a separate folder and have only boot.py and main.py. Or you can leave the name unchanged and modify boot.py.

The second option is the one I followed. To do that, with rshell open:

cd /pyboard
sudo nano boot.py which will open the editor
simply add import ds_sensor and save with Control+O, check the name of the file (if ok, hit ENTER) and the Control+X to exit the editor.

 

Unplug and plug again the USB, open rshell, open REPL and you should be able to see the messages printed via the serial connection. It may be necessary to use the unplug-replug trick to start rshell.

If all the information is correct and all the files are where they should… well, it should work!

Opening the Home Assistant dashboard you should now be able to see the reading of the sensor. Hooray!

 

Go back to: The firmware || Go back to: My Internet of Things