# How to build a temperature and humidity sensor * Lowe Eriksson * le223bg # Project overview How can we use the dht11 in conjunction with the PyCom LoPy4 to get a temperature and humidity readout? Further how can the data be transmitted from the device using a transport protocol? **How much time will it might take to do?** The time required to perform this tutorial should in my opinion not span more than two of hours of time depending on experience. # Objective I choose to build the temperature and humidity sensor. This was an easy project to get started with as the resources (code / schematics) was openly available. This allowed me to get a good introduction to the subject of IoT technology, which was the purpose of the project. The data generated from the project – mainly temperature and humidity measurements, i don’t intend to do anything with other than broadcasting them via a webhook and displaying in the dashboard. The project has given me insight in python running directly on hardware (ESP32) i.e. MicroPython which is a new experience for me. # Material |Hardware |Purpose| |-----|--------| |1. LoPy4|development board| |2. PyCom Antenna|for wireless connectivity| |3. USB micro cable|for power supply and code upload| |4. Breadboard|for temporary circuit design| |5. GPIO cables|for temporary circuit design| |6. DHT11|temperature and humidity sensor| ![](https://i.imgur.com/GKHosNs.jpg) **Where you bought them and how much they cost** Most of the hardware was purchased in kit: (LNU - 1DT305 Tillämpad IoT - LoPy4 and sensors bundle) avalible at: https://www.electrokit.com/ The DHT11 sensor was purchased seperatly from Kjell & Company: (Artikelnr: 87086). Total cost for the hardware was: 1024.00 (Kit) + 99.90 (Sensor) = 1123.00 kr SEK including sales tax and shipping. # Computer setup **Choosen IDE** I choose to atom.io as my IDE with the Pymakr plugin for connecting and programming code on my LoPy4 unit. The plugin is installed via the Atom package manager under the 'Install Packages' tab. Flashing the units firmware was done through the pybytes.pycom.io/ webportal under the 'devices tab' once the device has been added. **How the code is uploaded** The code was uploaded via the Pymakr plugin in atom by the usb connector. **Steps Seting up pybytes and flashing firmware** 1. Go to: https://pybytes.pycom.io/devices 2. Add via USB -> Choose LoPy4 -> Choose WiFi -> Save Device. 3. Go to: https://pybytes.pycom.io/projects 4. Add project: Enter name -> Choose WiFi -> Enter WiFi credentials -> Save project. 5. Go to: https://pybytes.pycom.io/devices 6. Choose device -> Configuration -> OTA Firmware update. -> Update if outdated. **Steps for Atom.io and flashing MicroPython code** 1. Install Atom.io on your system (depends on OS: .exe based installer on win32, available in repo for linux). 2. In Atom: 'File' -> 'Settings' -> 'Install' -> search for 'Pymakr' and install. 3. Flasing code is done in the Pymakr plugin under the: 'Upload project to device'. # Putting everything together The below diagram show the sensor connected to an Arduino unit. Connecting the sensor to the LoPy4 however will look much the same. ![](https://i.imgur.com/d4UFQYJ.jpg) The pin-out on the DHT11 sensor may vary depending och manufacturer and i sugest verifying the pin-out on the respective spec sheet for your version. I used the VMA311 (Velleman) and connected it according to the table below: |LoPy4|VMA311| |-----|------| |P23|S| |3V3|+| |GND|-| **The spec sheet for the VMA311 calls for 5V power delivery, the 3V from the LoPy4 should however be sufficient.* This setup is only for development and would need to be refined for production use. I whould recommend using a IP rated enclosure to protect the device and sensor from damage in real-world use. # Platform The main platform used is the pybytes platform wich is a cloud-based device management platform. webhook.site was also used alongside for managing webhooks. webhook.site has both free and paid versions. For this introducturary project the free version will be sufficient. An alternative platform for future use whould Ubibots as it can act as an MQTT broker aswell as allowing for many other protocols wich the pybytes platform don't. # The code Folder hierarchy: ``` +---DHT11-22 | | main.py | | | \---lib | dht.py ``` main.py : ```python # Data is sent to Pybytes. Needs to flashed with Pybyte firmware import time from machine import Pin from dht import DHT # https://github.com/JurassicPork/DHT_PyCom # Type 0 = dht11 # Type 1 = dht22 th = DHT(Pin('P23', mode=Pin.OPEN_DRAIN), 0) # pin number, Pin.OPEN_DRAIN (can be used for input AND output), sensor type. time.sleep(2) # Wait for 2 seconds while True: # infinite loop result = th.read() # collect sensor data while not result.is_valid(): # no error codes returned. (!DHTResult.ERR_NO_ERROR). time.sleep(.5) # Wait for 0.5 seconds result = th.read() # collect sensor data print('Temp:', result.temperature) # print temperature print('RH:', result.humidity) # print humidity pybytes.send_signal(1,result.temperature) # send temp data to pybytes pybytes.send_signal(2,result.humidity) # send humidity data to pybytes time.sleep(5) # Wait for 5 seconds ``` dht.py : ```python # https://github.com/JurassicPork/DHT_PyCom import time import pycom from machine import enable_irq, disable_irq, Pin class DHTResult: 'DHT sensor result returned by DHT.read() method' ERR_NO_ERROR = 0 ERR_MISSING_DATA = 1 ERR_CRC = 2 error_code = ERR_NO_ERROR temperature = -1 humidity = -1 def __init__(self, error_code, temperature, humidity): self.error_code = error_code self.temperature = temperature self.humidity = humidity def is_valid(self): return self.error_code == DHTResult.ERR_NO_ERROR class DHT: 'DHT sensor (dht11, dht21,dht22) reader class for Pycom' #__pin = Pin('P3', mode=Pin.OPEN_DRAIN) __dhttype = 0 def __init__(self, pin, sensor=0): self.__pin = Pin(pin, mode=Pin.OPEN_DRAIN) self.__dhttype = sensor self.__pin(1) time.sleep(1.0) def read(self): # pull down to low self.__send_and_sleep(0, 0.019) data = pycom.pulses_get(self.__pin,100) self.__pin.init(Pin.OPEN_DRAIN) self.__pin(1) #print(data) bits = [] for a,b in data: if a ==1 and 18 <= b <= 28: bits.append(0) if a ==1 and 65 <= b <= 75: bits.append(1) #print("longueur bits : %d " % len(bits)) if len(bits) != 40: return DHTResult(DHTResult.ERR_MISSING_DATA, 0, 0) #print(bits) # we have the bits, calculate bytes the_bytes = self.__bits_to_bytes(bits) # calculate checksum and check checksum = self.__calculate_checksum(the_bytes) if the_bytes[4] != checksum: return DHTResult(DHTResult.ERR_CRC, 0, 0) # ok, we have valid data, return it [int_rh, dec_rh, int_t, dec_t, csum] = the_bytes if self.__dhttype==0: #dht11 rh = int_rh #dht11 20% ~ 90% t = int_t #dht11 0..50°C else: #dht21,dht22 rh = ((int_rh * 256) + dec_rh)/10 t = (((int_t & 0x7F) * 256) + dec_t)/10 if (int_t & 0x80) > 0: t *= -1 return DHTResult(DHTResult.ERR_NO_ERROR, t, rh) def __send_and_sleep(self, output, mysleep): self.__pin(output) time.sleep(mysleep) def __bits_to_bytes(self, bits): the_bytes = [] byte = 0 for i in range(0, len(bits)): byte = byte << 1 if (bits[i]): byte = byte | 1 else: byte = byte | 0 if ((i + 1) % 8 == 0): the_bytes.append(byte) byte = 0 #print(the_bytes) return the_bytes def __calculate_checksum(self, the_bytes): return the_bytes[0] + the_bytes[1] + the_bytes[2] + the_bytes[3] & 255 ``` # Transmitting the data / connectivity The data is transmitted every 5 seconds to the pybytes platform. The wireless protocol used for communicating with the platform API is WiFi. Other than WiFi, webhook is used as transport protocol and the package format is JSON. device (http) -> pybytes (JSON) -> webhook.site The choice of wireless protocols where not choosen for any other reason than being easy to get started with. As this was ment as being an introductory project on my part. # Presenting the data The data is presented in the pybytes dashboard with temperature and humidity added as widgets. The data does not seem to be purged from the pybytes database howerever it does by default only pull the first 50 entries stored. ![](https://i.imgur.com/xH0lxov.png) Below shows the webhook.site data being stored as JSON objects: ![](https://i.imgur.com/ba8ouYU.png) # Finalizing the design **Final thoughts** As final thoughts on the project i think it has been a good learning experience and introduction to IoT devices although being quite basic. As an improvement i could use another wireless protocol rather than WiFi for instance LoRa as WiFi might not always be available. Since i have the basic hardware i will most likely try to improve on the project and purchase additional sensors. **Pictures** ![](https://i.imgur.com/pGFq3UP.png) ![](https://i.imgur.com/rub4aUl.png)