<h1>Lopy4 and DHT22</h1> <p>Tutorial written by Tomas Berggren, lun student id:tb222nk</p> <p>Time consumtion, depending on previous experience, took me three weeks to get here before the pieces fell into the right place, an hour to send data to ubidots. <i>This tutorial shows how to connect a lopy4 with a dht22 and send data temp and humidity data over wifi to ubidots.</i> The first part will show you how to get things up and running, the other part will try to explain why and what certain things of the code does. ![](https://i.imgur.com/TLgF82k.jpg) *image of expected end result* <h2>Objectives</h2> <p>Temperature and humidity is of interests in many situations. I have an existing arduino system setup in my house measuring several sensors in the house and sending the data to the cloud. I tought this should be simple to do with the lopy4. Low temperature or high levels of humidity can harm a building and the people or goods that stay there. Running around measuring every day or week is time consuming. The insights are mostly on lopy4 and micropython.</p> <h2> Material needed</h2> <p>I bought mine from the links below and already had some in stock. Total cost aproxamately €60</p> <p>you need a microcontroller <a href="https://pycom.io/product/lopy4/">Lopy4 from pycom, order WITH headers</a> <img src="https://pycom.io/wp-content/uploads/2020/03/Webshop-Product-Box-LoPy4.png" alt="Lopy4"></p> <p>you also need an expansion board <a href="https://pycom.io/product/expansion-board-3-0/">Expansionboard from pycom, however, mine says 3.1</a></p> <p>you also need a sensor, dht11/22/rht03 <a href="https://www.electrokit.com/produkt/temp-fuktsensor-rht03/">temp sensor from electrokit</a></p> <p>A few connection cables and a breadboard kan be useful but is not mandatory</p> <h2>Computer setup</h2> <p>Don't fix whats not broken, I dit not do any updates to the hardware, I was using Visual Code from microsoft with the recomended <a href="https://docs.pycom.io/pymakr/installation/vscode/">Pymakr extension </a> I write the python code locally, then I press upload and a copy of the project is uploaded to the lopy4 device. Not sure if node was needed, I already had it installed</p> <h2>Putting everything together</h2> <p>The lopy4 is connected to the expansion board. The dht is connected to pin 23, 3.3v and ground, all three next to each other. The board is connected to the pc and if everything is correct, thats it. My pins are not in the same order as in the documentation but I used the 3 next to each other.</p> <img src="https://i.imgur.com/IIMxhcw.jpg" alt="Wiring">) <h2>Plattform</h2> <p>I was going for a cloud plattform from the start. Setting up my own server needed to much time. However, my first choice thingspeak stopped me for over 2 weeks, could just not get the code to cooperate with me. Pybytes did not attract me. Out of the blue came suddenly ubidots, or at least from a friendly link on the course documentation. It took me only a few minutes to realize this was the solution I've been looking for. See more details further down</p> <h2>The code</h2> ```python= boot.py #the settings file from machine import UART import machine import osuart = UART(0, baudrate=115200) os.dupterm(uart) machie.main('main.py') #main.py from network import WLAN import urequests as requests //lib import, copied local import machine import time from machine import Pin from dht import DTH //lib import, copied local import _thread import pycom Type 0 = dht11#this is only comment Type 1 = dht22#this is only comment th = DTH(Pin('P23', mode=Pin.OPEN_DRAIN), 1) #using pin23, 1 for dht22 time.sleep(2) TOKEN = "BBFF-bn9Fi8ADAyXXXXXFCrgindccJKgWHG" #Ubidots TOKEN DELAY = 1 # Delay in seconds wlan = WLAN(mode=WLAN.STA) wlan.antenna(WLAN.INT_ANT) //Assign your Wi-Fi credentials wlan.connect("NETGEAR", auth=(WLAN.WPA2, "myverygoodpw"), timeout=5000) pycom.heartbeat(False) # own idea, red while no wifi pycom.rgbled(0x7f0000) # red while not wlan.isconnected (): machine.idle() print("Connected to Wifi\n") pycom.rgbled(0xff00) #green when wifi is acitve time.sleep(4) //Builds the json to send the request def build_json(variable1, value1, variable2, value2): try: data = {variable1: {"value": value1}, variable2: {"value": value2}} return data except: return None //Sends the request. Please reference the REST API reference https://ubidots.com/docs/api/ def post_var(device, value1, value2): try: url = "https://industrial.api.ubidots.com/" url = url + "api/v1.6/devices/" + device headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"} data = build_json("humidity", value1, "temp", value2) if data is not None: print(data) req = requests.post(url=url, headers=headers, json=data) return req.json() else: pass except: pass while True: result = th.read() while not result.is_valid(): time.sleep(.5) result = th.read() print('Temp:', result.temperature) print('RH:', result.humidity) post_var("pycom", result.humidity, result.temperature) time.sleep(DELAY) ``` ## Transmitting the data Tried mqtt earlier without sucess with thingspeak. The code for ubidots create json in any way the programmer want. The jason pkg is sent by the REST-api over wifi every fifth second. ## Presenting the data ubidots make things really easy, cannot take much credit but really impressive functionality. Data is saved when uploaded, right now every five seconds. Haven't found how much it can store. ![](https://i.imgur.com/HvEly9V.png) ## Final thoughts Got the blinking led up and running quite fast with a few pointers, then I got stucked for a few weeks. With Ubidots I finally got the full picture and could put the pieces together. [See a short video here](https://youtu.be/rzqySmk9zrs) or here https://youtu.be/rzqySmk9zrs or here <iframe src="https://drive.google.com/file/d/1PwO-CApnAKFI8OsuZ13icq-cxd1c3COu/preview" width="640" height="480"></iframe> ## uncut material ## Trivia list 1. Lopy4 is programmed with micropython. Micropython is a limited version of python. The lopy can read pythoncode but to handle packages it is easier to copy the code into a preferred directory structure. [Learn basic python](https://www.learnpython.org/) 2. Embedded require some hardware knowledge. Here is an image trying to explain the most important parts of the lopy4. ![](https://i.imgur.com/biufniH.jpg) A pin can be set either as input or output. 3. Its good to start coding something simple. Hello world is probably what most programmers start with just to check that you can get an output.[Hello world history if you would like to know more.](https://blog.hackerrank.com/the-history-of-hello-world/) With embedded you don't have a monitor but the equliant to hello world is normally blinking a led. The lopy has a builtin rgbled. [Code example for builtin rgb led](https://docs.pycom.io/tutorials/all/rgbled/) 4. There are two versions of the dht11 and 22, 3 or 4 pins, make sure you use correct datasheet. The sensor needs power, ground and a data pin to send sesor data. Now we can read values. [dht22 datasheet to 3 pin version](https://components101.com/sensors/dht22-pinout-specs-datasheet) [dht22 lib and sample code](https://github.com/dmasb/applied-iot-20/tree/master/sensor-examples/DHT11-22) 5. IoT sends sensordata to the internet. We don't need to set up our own webserver right now. There are several cloud services available. [List with IoT cloud services](https://dzone.com/articles/12-iot-platforms-for-building-iot-projects) 6. For this project I found my new favourite, ubidots [ubidots](https://ubidots.com/) 7. Ubidots supports several IoT cards and the data is sent as json. [ubidots example to send fake data from lopy](https://help.ubidots.com/en/articles/569964-simulate-data-in-ubidots-using-python) When the data is received in the cloud you can set up a dashboard and pick suitable widgets. 8. Json is probably the most common format to send and receive data 2020. [Learn the basics of json](https://www.w3schools.com/js/js_json_intro.asp) 9. Lets put it all together, connect the sensor to the lopy, write (or copy) some code reading the sensor, send the data to the cloud with ubidots. ### easy test code that works https://docs.pycom.io/tutorials/all/rgbled/ runs green rgb and do a traffic light use the right tools, after spending a week trying to get thingspeak to work with my lopy I tried after a suggestions ubidots https://help.ubidots.com/en/articles/569964-simulate-data-in-ubidots-using-python Based on previous experience with arduino, arm and pi I wanted to send weather info from a dht22 to the cloud with the lopy4. I ordered 2 lopys, wasn't sure about the differences, realized when they arrived that one was lacking pins. I started with dht11 a long time ago but since it only worked with positive integers it did not fit my needs. The dht22 supports decimals and negative values. My first idea was to use thingspeak to which I am familiar. Trying to get the little lopy4 to do this was harder than it looked. First there was a problem with the cable, my computer never found the lopy4. It took a while before someone recomended me to try another cable. Brand new cable made a difference. Blink the built in rgb-led was quite easy. Finding the tutorial was harder. Everywhere was an upgrade of the expansion board recomended but a wise man once said, never fix what not is broken. Next step was to break out a led to a breadboard. Of course I managed to use the forbidden pin and nothing worked. Not used with the python way of working I have lost my code several times. Make sure to take backups. The next step was wifi, in software python you use a package installer and add what you need. On the lopy you need to create subdirectories and copy the library code into the correct structure. The update does not always work as it is supposed to, sometimes need a hard reset. I added a plugin to VS code and it works really good. When I finally got my connection I did not know how to test it. The course recomended pybytes but that was not real coding. I tried thingspeak and adafruit with mqtt but since that is an unknown area to me I was also looking to alternatives. Suddenly someone mentioned Ubidots and out of nowhere all pieces fell into the right place. Ubidots is impressive, supports 70+ IoT-cards with different languages and you create your own json and send it to their cloud service. They have ready made widgets for temperature, speed and so on.