ESP32 MicroPython MQTT Tutorial with Raspberry Pi, DHT-22 & OLED

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this tutorial will demonstrate how to connect a dht22 temperature humidity sensor to an ESP 32 running micro Python the sensor data will then be transmitted wirelessly to a Raspberry Pi using MQTT protocol and the results will display it in an eye to see o LED display my videos are fast paced but all the code notes updates and more are available on our website and as always a link will be placed in the description this tutorial builds on my last video which showed how to load the micro Python firmware on ESP 32 use our shell to manipulate files and run Python code in the repple I recommend you watch it first all the tools from the previous video have been installed on a Raspberry Pi run the latest updated version of raspbian Jessie there's been one breaking changed is the last video with respect to loading the micro Python firmware which I'd like to address therefore I'll use the ESP tool to erase the existing firmware on the ESP 32 again this has already been covered in part one I already downloaded the latest firmware build for the ESP 32 to the Downloads folder I'll copy the file name to the clipboard the SP tool is used again to write the firmware erase flash has changed to write flash notice that I now specified hex address 1004 the starting address instead of zero this is new since the last video and it's mandatory I specify the Downloads folder and paste in the firmware file name the new firmware is now being written to the ESP 32 ok the ports ready to go mq TC is a very lightweight connectivity protocol it's very popular with IOT devices because it R is much less code in memory compared to other approaches such as a REST API and uses a publish/subscribe model a single broker acts as a server and manages messages among multiple clients client can publish the message to a topic and any client that subscribes to the topic will get the message for this video in ESP 32 client connected to a dht22 temperature humidity sensor will publish the sensor data to a topic called temp humidity topics are usually organized in the hierarchical order using slashes like a file system on a computer they are referred to as topic trees and it's possible to reference them with wildcards plus for single level and hash for multi level for example you could have topics called sensors / temperature / attic and sensor / temperature / workshop and you could subscribe to both by using sensors / temperature / hash for the simple example there will be just one top temp humidity the Raspberry Pi will be the broker and it will also be the client a Python MQTT client running on the PI will subscribe to the temp unity topic and show the results on a no LED display again this is a very simple example you could have multiple USB 32 is publishing and subscribing to topics and all types of sensors such as solar power tracking water pressure motion detection GPS beacons etc and it doesn't have to be limited to sensors you could fire relays activate home automation macros run programs and much more mosquito will be used for the server it's an open source message broker that implements the MPTV protocol it can be installed on a Raspberry Pi using sudo apt-get install mosquito mosquito clients is also installed it's a command-line mqtt client that's helpful for debugging in addition to the PI will need a micro Python and qtt client for the ESP 32 a good one is available from the micro Python Lib repository on the github site scroll down to you MQTT dot simple and click it then click you MQTT click simplify click raw to show only the code this is a simple mqtt client for micro Python I'll right click to download the simple pipe file to the PI and save it in my home folder once the download completes close the browser LS shows the downloaded simple pipe file our shell is run to connect to the ESP 32 which is plugged into the PI via a USB cable on TTY USB 0 LS / PI board shows that the ESP 32 contains only a single file boot PI mkdir / PI board / u MQTT creates a folder on the ESP 32 called the u MQTT LS / pi board again shows the newly created folder LS alone shows the contents of my home directory on the PI CPA simple PI / Pi board / u mqtt slash copies the simple pipe file to the u MQTT folder on the ESP 32 LS / PI board / u MQTT shows simple PI file was copied successfully the dht22 temperature humidity sensor is easy to connect to the ESP 32 in one BCC on the dht22 is connected to a three point we bolt pin on the ESP 32 into the dht22 data line is connect it's GPIO 15 he use any available GPIO pin in three is left disconnected and pin for ground is connected to a ground on the ESP 32 normally you connect a pull-up resistor between the data line in the 3.3 volt line but it's not necessary because the ESP 32 GPIO pins have internal pull ups that can be turned on from the code on a small breadboard I have a GPS p32 bought on ebay and a dht22 temperature humidity sensor 3.3 volt pin from the ESP 32 is connected to a rail on the breadboard this will be the 3.3 volt rail a ground pin is connected to a ground rail the dht22 pin 1 VCC is connected to the 3.3 volt rail pin for ground is connected to the ground rail in two data is connected to the ESP 32 GPIO 15 it's a good practice in terms of reliability to keep the data wire short preferably under 15 centimeters ok the temperature humidity sensor is ready to go so let's create the code to publish the sensor data back on the pile open idol 3 I'll create a new blank file for the ESP 32 mqtt client from x that was imported from UM QT t dot simple mqtt client is imported this is the micro Python MQTT client that we downloaded from github and copy to the UM qtt folder on the ESB 32 from machined pin is important this library provides control the ESP 32 GPIO pins from tht import dht22 the micro Python firmware for the ESP 32 comes with this built in DHT library a surfer constant holds the IP address of the broker which is just the IP address of the PI your PI will probably have a different IP address so open a terminal and type hostname tak I this will provide the IP address of your PI set your server just to the return value client ID is a unique ID for this client I'll use the SP 32 underscore dht22 underscore sensor topic indicates the topic name that'll be published the B preceding the topic indicates bytes it's not necessary because this method will automatically convert the string to bytes but I like to add the B to remind me of the conversion client instantiate sanam QT client the client ID and server address are passed Lyon Connect attempts to connect to the MTC broker a sensor is instantiate it for the dht22 on GPIO 15 and in indicates that the GPIO pin is an input as opposed to an output pin pull-up turns on the GPIO internal pull up this obviates the need for the pull-up resistor between the dht22 data line and BCC the main program loop is an infinite while loop a try statement is used to catch errors the sensor measurement pulls the dht22 T stores the temperature and H stores the humidity occasionally the dht22 will have a bad reading isn't since checks to make sure that temperature humidity readings are numeric float values if so a variable MSG is stores the byte formatted temperature and humidity values client publish publishes to the broker topic is the temp community topic and MSG is the message containing the temperature and humidity values else catches bad readings and prints an error message to the console except OS error buyers if the sensor can't be read and again logs the error to the console luke pauses for 4 seconds and repeats please note that you must wait at least two seconds between calls to dht22 to avoid errors ok that's it for the ESP 3 to client code I'll save the program to the Documents folder and call it DHT publish back in our shell CD documents to switch the Documents folder where the ESP 32 client code was saved LS shows the DHT published python file CP DHT publish pi / pi board copies the client code to the root directory of the ESP 32 LS / pi board shows the file was copied successfully type repple to access the micro Python repple before writing the client is necessary to connect the SP 32 to a Wi-Fi network import network loads the network library ok something went wrong looks like loading the network library caused the ESP 32 to crash which disconnected our shell I did a little research into the import network crash and someone suggested that I should use a shorter USB cable they theorized that the network library turns on the Wi-Fi radio which causes a power draw that when combined with the increased resistance of a long USB cable and caused a brownout this helped but it didn't fix the problem but it was on the right track turns out my cheap eBay ESP 32 has a effective microUSB port that resists current flow you can see that if I jiggle the USB plug ESP 30 to power LED blinks I can even go out I tried reflow in the solder but it didn't help I'll remove the bad ESP 32 from the breadboard and replace it with a we Moss Lolan 32 that I got an Aliexpress this board appears to be much higher quality it's also narrower so I can access the breadboard tie points on both sides of the board and it has a lithium battery jack and charging circuit the breakout board pin out is different from the previous board I'll reconnect the ground rail to a ground pin on the ESP 32 and connect the 3.3 volt rail to a 3.3 volt pin the data line is reconnected to GPIO 15 and the USB cable is plugged in the LED on the board does not come on unless the battery is charging I assume this is to save battery power okay I restarted the PI from a terminal our shells connected to the newly SP 32 board type repple to open the repple and import network now that's more like it and network library is loaded station instantiate sat Network W LAN and enables the station interface station active true activates the network interface station connect connects to my Wi-Fi access point the method takes two parameters the first is the SSID of my access point which is roto Tron and the second is the Wi-Fi password which I will change before publishing this video we're connected and we got an IP address for the SP 32 board which is 192 dot 168 182 19 import DHT published runs the client for some reason the first reading of the dht22 often fails however a few seconds later and we get a good reading 25.3 / - picture in Celsius and 38.5 for the humidity percentage every 4 seconds the sensor is pulled and new data is published we can test that the data is actually being published by using the mosquito command-line client in a new terminal window type mosquitoes sub tack D to enable debug messages tack T for topic followed by our topic temp humidity mosquito client connects to the MQTT broker and subscribes to the temp community topic as the ESP 32 publishes new sensor readings the data is displayed in the terminal 25.3 temperature and 38.9 humidity control see is used to exit the client the command line is great for testing but now let's create a Python client program that's a little more useful I'll install the Pahoa Python client using sudo pip3 install aho - MQTT the Python client will run on the same raspberry pi that's also serving the mosquito mqt broker and display the temperature humidity readings on an SSD one 306 oh le d-- display Adafruit provides a simple Python library for driving the SSD one 306 display it's installed using sudo pip 3 install Adafruit - SSD one 306 the ad approved library and all required dependencies have been installed the O LED display it's very easy to connect to the PI the displays SDA pin is connected to the PI's SDA pin which is GPIO 2 displays SCL pin is connected to the PI's sel GPIO 3 the BCC pin is connected to a 3.3 volt pin on the PI and the grounds are connected the display uses an I squared C protocol so it only needs 2 GPIO pins for communication in addition to the power and ground next to a Raspberry Pi 3 on a breadboard I have a small 128 by 32 pixel oh le d-- display the SDA pin from the display is connected to GPIO to on the PI the SCL pin is connected to GPIO 3 on the PI ECC is connected to a 3.3 volt pin ground is connected to a ground pin that's all it takes for the display hardware oil ID is a great solution for the PI because it runs at 3.3 volts it's very bright and it's energy efficient all open idol 3 and create a blank file for the Python client the paho and PhD client is imported as MQTT the Adafruit SSD 1 306 library is imported the upper library is very rudimentary all can really do is transfer images to the display therefore from PIL which stands for Python imaging library image image draw and image font are imported heal library lets you create images and draw shapes and fonts discipline sachets and Adafruit SSD 1 306 128 by 32 pixels display my I squared C oil a display doesn't have a reset pin so 0 is passed for the required rst parameter begin initializes the display font path specifies the file location on the the Roboto condensed regular two type font this font will be used to display text but any true type font could be used on instantiates an image font true type takes parameters for the font path and the font size which is set to 22 the method display data will be used to display temperature and humidity on a monochrome LED display a new image is instantiated the first parameter is mode one indicates one bit per pixel which is black and white mode the width and height are set to width and height of the Oly to display draw instantiates and image draw object which is used to draw shapes and text on the image draw text ricetec sub location 0 comma 8 the text is the formatted temperature font specifies the Roboto condensed regular font above and fill sets the color since this is a monochrome blue display there's only one color nonzero numbers illuminate the pixels and 0 turns the pixel off draw text is used again at location 71 comma 8 to display the formatted humidity draw rectangle creates an outline of a bar chart to graph the current temperature zero comma zero comma 50 comma 8 defines the bounding box for the rectangle outline 255 illuminates the border of the rectangle and fills 0 leaves the inside of the rectangle dark draw a rectangle is used again at 71 income a zero comma 121 comma 8 to create an outline for a humidity graph 1/3 draw rectangle fills the temperature graph proportionally to the current temperature bill is nonzero so the rectangle is fully illuminated I should have used 255 instead of 1 to be more consistent but it'll function the same again nonzero numbers are illuminated and 0 is dark when working with monochrome displays 1/4 draw rectangle fills the community graph the display is cleared and image is transferred to the display image isn't actually displayed until the display method is called a callback function called on connect will fire when the Mt HD client connects to the broker the most important argument is RC which stands for result code it's printed to the terminal it's 0 then the connections successful I'm trying to keep the code simple for demo purposes but it'd be a good idea to add some error checking here to handle failed result codes polland connect the clients subscribed method is called to subscribe to the temp unity topic another callback function called on message will fire when a message is received from the broker the MSG argument is the message which in this example contains a temperature humidity temperature humidity are extracted from the message payload decode utf-8 translates the byte data to a string which is split on the comma into two parts temperature and humidity this comprehension converts the two values from string to numeric clothes the data is printed to the terminal and the display data has passed the temperature and humidity which will be presented on the o LED display with a bar graph client instantiates and MQTT client client on connect sets the on connect call back to the function above client on message sets the on message callback function client connect initiates a client connection localhost is used for the host address instead of an IP because this client and the broker are both running on the same raspberry pi 2083 is the port and 60 specifies to keep alive this is the number of seconds to timeout after no activity client loop forever blocks the program and causes it to run indefinitely during which it handles all network traffic callbacks and reconnections the program is saved to the Documents folder and called DHT subscribe since this program uses the I squared C communication protocol it's necessary to enable the I squared C interface click the PI main menu click preferences click Raspberry Pi configuration click the interfaces tab and for I squared C check enable to ensure the only display is wired properly open a terminal and type I to C detect at y1 a single I squared C device is present at X address 3c which is the default for my display I move the breadboard with the e SP 32 and dht22 sensor outside I'm powering it with a three point seven volt lipo battery the board can now be used wirelessly to monitor and publish temperature and humidity data as long as it's within range of my Wi-Fi access point now I'll run the Python client program on the PI result code zero indicates a successful client connection to the MQTT broker the temperature humidity data is received and presented on the o LED display please let me know if you found this tutorial helpful and let me know if you have any suggestions for future videos you can support this channel by subscribing even a like and sharing thanks for watching
Info
Channel: rdagger68
Views: 116,078
Rating: undefined out of 5
Keywords: MQTT, ESP32, MicroPython, DHT-22, OLED, Raspberry Pi, Python, Rshell, ESPTool, SSD1306, Paho, Mosquitto
Id: _vcQTyLU1WY
Channel Id: undefined
Length: 17min 46sec (1066 seconds)
Published: Fri Aug 25 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.