Sending data to the cloud using MicroPython

This recipe is going to introduce us to the IoT using MicroPython. We will use MicroPython to send measurement data to dweet.io from the ESP8266. Through that, you will learn some IoT basics and how to implement them using MicroPython.

Getting ready

The hardware setup will be the same as the one you used in the previous recipe. The only difference is that we will be connecting and sending data to dweet.io. dweet.io is a cloud server that you can use to easily publish and subscribe to data. It does not require you to sign up or set it up. All you need to do is publish and you are good to go.

A simple HAPI web API is used to send data from your thing to the cloud. Sending data is accomplished by calling a URL such as https://dweet.io/dweet/for/my-thing-name?hello=world.

Replace my-thing-name in the URL with the name of your choice and then proceed to log data online. The query parameters you add to the URL will be added as key value pairs to the dweet content.

How to do it…

  1. To successfully log sensor data to dweet.io, you should first connect the ESP8266 board to a Wi-Fi network that has an Internet connection. Then read data from the DHT11 sensor and publish it to dweet.io. The following code will accomplish all these tasks.

    This function connects the ESP8266 to the Internet:

    # Function to connect to the WiFi
    def do_connect():
        import network
        sta_if = network.WLAN(network.STA_IF)
        if not sta_if.isconnected():
            print('connecting to network...')
            sta_if.active(True)
            sta_if.connect('<essid>', '<password>')
            while not sta_if.isconnected():
                pass
        print('network config:', sta_if.ifconfig())
  2. Make sure you modify the ssid and password in the sta_if.connect('<essid>', '<password>') line of the code, so that they match those of the Wi-Fi network you want the ESP8266 to connect to.

    This function is for sending the HTTP request:

    # Function to send an HTTP request
    def http_get(url):
        _, _, host, path = url.split('/', 3)
        addr = socket.getaddrinfo(host, 80)[0][-1]
        s = socket.socket()
        s.connect(addr)
        s.send(bytes('GET /%s HTTP/1.0
    Host: %s
    
    ' % (path, host), 'utf8'))
        while True:
            data = s.recv(100)
            if data:
                print(str(data, 'utf8'), end='')
            else:
                break
  3. Connect to the Internet by executing this function:
    # Connect to WiFi
    do_connect();
  4. Get temperature and humidity readings from the DHT11 sensor:
    # Make measurements
    import dht
    import machine
    d = dht.DHT11(machine.Pin(5))
    
    d.measure();
    temperature = d.temperature();
    humidity = d.humidity();
  5. Build a http request that will be sent to dweet.io:
    # Build request
    url = 'https://dweet.io/dweet/for/myesp8266';
    url += '?temperature=' + temperature;
    url += '&humidity' + humidity;
  6. Send the http request:
    # Send request
    http_get();
  7. Set your prompt into paste mode by pressing Ctrl+E and then copy and paste the code to the prompt. You can get the complete code from this link: https://github.com/marcoschwartz/esp8266-iot-cookbook. Once you have successfully pasted the code, press Ctrl+D to exit paste mode and execute the code.

You should start seeing data being logged on your console. The data you see is the replies from dweet.io every time data is published.

How it works…

The code has two functions, which handle connecting to the Internet and publishing data to dweet.io. The function that connects the ESP8266 board to the Internet is called do_connect(). In this function, the network library is imported and a network object is created in STA mode. If the ESP8266 is not connected to a Wi-Fi network, the network object is set to active using the active() function and the board gets connected to the Wi-Fi network whose SSID and password have been provided. This is done by the connect() function. If the connection is successful, the ESP8266 prints out the network configuration on the prompt, otherwise nothing happens.

The function that publishes data to dweet.io is called http_get(url). It starts by dividing the URL into its different parts, that is, host name and path, using the split() function. The program then uses the host name and socket to create an address, which the ESP8266 uses to connect to the server, using the connect() function. The send() function is then used to publish a GET request to the server. The ESP8266 then listens to the reply from the server, using the recv() function. If there is a reply, it is printed on the serial terminal.

The main part of the program begins with calling the do_connect() function so that the ESP8266 can connect to the Internet. Once the board successfully connects to the Internet, it takes the temperature and humidity readings from the DHT11 sensor and saves the readings in two variables: temperature and humidity. The http request is then built and the temperature and humidity readings are added to it. The http_get() function then publishes the temperature and humidity measurements to dweet.io.

See also

There are some problems you may run into when using MicroPython to program your ESP8266 board. Check out the next recipe for some of their causes and ways to solve them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.70.93