ESP32: M5Stack With DHT22


Introduction: ESP32: M5Stack With DHT22

About: Do you like technology? Follow my channel on Youtube and my Blog. In them I put videos every week of microcontrollers, arduinos, networks, among other subjects. New tutorials on Tuesdays and Fridays.

Let's talk today about a very special ESP32, perfect for the Internet of Things, which is M5Stack. It contains the ESP32 inside and even adds on a display, keyboard, amplifier, speaker, and battery. Thus, this device can do countless things. When I received this hardware, I already had software for ESP32 and only ported to the display used in this project, which is different. However, the source code we will use is the same one used in our video TEMPERATURE AND HUMIDITY WITH OLED DISPLAY.

In today's circuit, I specifically want to emphasize that we have the M5Stack with positive and negative connections, which feeds itself with a DHT22 sensor. Both are connected by a GPIO. The data is displayed in the chart.

In this article, let's introduce M5Stack and discuss its applications. I need to emphasize that this device has an input for a micro SD card, a 1W Speaker, and a battery socket, and also has interaction buttons, a i2c connector, a USB type C, exposed IOs, a two-inch TFT display, among other features. It is shown in the picture above. We can say this device is ready for IoT, as it already comes with Bluetooth and ESP32 WiFi. It also includes a magnet for attaching to metal surfaces.

Did you liked M5Stack? Click:

Step 1: M5Stack

One innovation of the M5Stack is that, if you take off the back, you can fit in different modules with different functions, such as the GPS module, GSM, LoRa, among others. This is shown in the image.

I have more examples of modules below, ranging from RS485, DC Motor, Maker, Core, to stepper motor control.

This is actually a very quick way to put together a prototype. In the old days, it was necessary to buy several transistor chips and perform numerous assemblies, which required a lot of time and investment. Only after came the product prototyping. It was then that Arduino and Raspberry appeared, which are plates.

Now, we finally have the M5Stack, which is this ready-for-use closed box. This liberates us from having to perform other innumerable steps.

Other M5Stack models are shown in images. We have a device with alphanumeric, numeric, and game keyboards. These allow you to work as if it’s a kind of computer. We also have an example of software running, which can be programmed in MicroPython, Arduino, ESP-IDF, NodeJS, in addition to Basic.

Step 2: M5Stack Possible Applications

Among the examples of M5Stack applications, we have the oscilloscope, as you can see in the image. We have also a kind of calculator / cutting tool table.

How about a bicycle speedometer?

It can also be a remote drill, which is printed in 3D and monitored remotely by a control.

All this shows that electronics control is much more affordable these days, just as the programming of these circuits has become easier.

Step 3: M5Stack - Pins

The back of the M5Stack is in this image, which shows that the power is at 5 volts. The image further reveals that we have everything that exists in ESP32 with connectivity.

Step 4: DHT Library

Use the SimpleDHT lib, which is the same one I used in the video: TEMPERATURE AND HUMIDITY WITH OLED DISPLAY.

Step 5: ​Arduino IDE Library Manage

In the "Menu: Sketch -> Add Library -> Manage Libraries,” let's install the two libraries shown in the image below. Remember that before all this, you need to install the Arduino core of ESP32. This video shows you how to do it: HOW TO INSTALL ARDUINO IDE IN ESP32.

Step 6: ​Source Code

The source code, as mentioned, is the same that I used in the video: TEMPERATURE GRAPH WITH OLED DISPLAY. The only change I made to this project was in relation to the size of the display.

Step 7: M5StackDHTGraph.ino

We will include the M5Stack.h and SimpleDHT.h libraries, and we will define colors used in the display, as well as the DHT data pin. We will also construct an object for communication with the sensor, define the variable responsible for the readings, and indicate the value of the X-axis.

//Libs do M5Stack e DHT
#include <M5Stack.h> #include <SimpleDHT.h> // definição das cores que serão utilizadas #define BLACK 0x0000 #define RED 0xF800 #define CYAN 0x07FF #define YELLOW 0xFFE0 #define WHITE 0xFFFF #define DHTPIN 5 //pino de dados do DHT //construtor do objeto para comunicar com o sensor SimpleDHT22 dht; //variável responsavel por contar o número de leituras realizadas e indicador do valor no eixo X int leituraAtual = 1;

We continue with X-axis and Y-axis positioning definitions, temperature and humidity data display coordinates, as well as the variables that will store the values read. We still point to the variable for printing the chart on the display.

//definições do posicionamento dos eixos X e Y
#define POS_X_GRAFICO 30 #define POS_Y_GRAFICO 3 #define ALTURA_GRAFICO 180 #define COMPRIMENTO_GRAFICO 270 //definição da coordenada onde escreveremos os dados de temperatura e umidade #define POS_X_DADOS 30 #define POS_Y_DADOS 200 //variáveis que armazenarão os valores lidos da umidade e temperatura int umidade = 0; int temperatura = 0; //variável que armazenará o valor da coordenada Y para desenharmos uma linha de exemplo //que varia os valores de 1 em 1 int linhaExemplo = 20; int fator = 1; //indicará se somaremos ou subtrairemos uma unidade na variável linhaExemplo

Step 8: M5StackDHTGraph.ino - Setup

In Setup, we initialize the M5Stack. We define commands for drawing the graph, configure the font as well as text colors, and position the cursor for writing.

void setup(void) {
Serial.begin(115200); //Inicializa o M5Stack M5.begin(); //pinta a tela toda de preto M5.Lcd.fillScreen(BLACK); //os comandos a seguir irão desenhar as linhas dos eixos cartesianos na cor branca //drawFastVLine(x,y,width,color) --> linha vertical M5.Lcd.drawFastVLine(POS_X_GRAFICO,POS_Y_GRAFICO, ALTURA_GRAFICO,WHITE); //eixo Y //drawFastHLine(x,y,width,color) --> linha horizontal M5.Lcd.drawFastHLine(POS_X_GRAFICO,ALTURA_GRAFICO+1,COMPRIMENTO_GRAFICO,WHITE); //eixo X //configura o tamnaho do texto que escreveremos em tela M5.Lcd.setTextSize(3); //configura a cor branca para o texto M5.Lcd.setTextColor(WHITE); //posiciona o cursor para escrita M5.Lcd.setCursor(POS_X_DADOS, POS_Y_DADOS); M5.Lcd.print("T: "); //indicando a temperatura M5.Lcd.setCursor(POS_X_DADOS+105, POS_Y_DADOS); M5.Lcd.print(" U: "); //indicando a umidade }

Step 9: M5StackDHTGraph.ino - Loop

In the first part of the Loop, we read the temperature and humidity, map the value of the variables for placement on the graph, and draw the point on the screen that refers to these values read from the sensor.

void loop() {
//Fazemos a leitura da temperatura e umiade float temp, umid; int status = dht.read2(DHTPIN, &temp, &umid, NULL); if (status == SimpleDHTErrSuccess) { temperatura = temp; umidade = umid; } //mapeando o valor das variáveis para colocar no gráfico //necessário pois o display tem 240px de altura e separamos apenas 180 para o gráfico //umidade pode ser lida de 0-100 int temperaturaMapeada = map(temperatura,0,100,0,ALTURA_GRAFICO); int umidadeMapeada = map(umidade,0,100,0,ALTURA_GRAFICO); //desenha na tela o ponto referente aos valores lidos do sensor M5.Lcd.drawPixel(POS_X_GRAFICO+leituraAtual, ALTURA_GRAFICO-temperaturaMapeada, RED); M5.Lcd.drawPixel(POS_X_GRAFICO+leituraAtual, ALTURA_GRAFICO-umidadeMapeada, CYAN); //desenha na tela o ponto referente a nossa linha de exemplo que fica variando M5.Lcd.drawPixel(POS_X_GRAFICO+leituraAtual, ALTURA_GRAFICO-linhaExemplo, YELLOW);

Then, we define possibilities of printing the graphic on the display.

//aqui controlamos nossa linha de exemplo, quando chega no valor máximo decrementamos o valor
//até um valor mínimo determinado (no nosso caso 10), e a partir daí, incrementa novamente if(linhaExemplo == 50) fator = -1; else if(linhaExemplo == 10) fator = 1; //soma o valor de linhaExemplo linhaExemplo += fator; //incrementa o contador de leituras realizadas leituraAtual++; //se a leitura chegar em 270 (número máximo do eixo X) então limparemos a área do gráfico para voltarmos a desenhar. if(leituraAtual == 270) { //limpa a área toda do gráfico M5.Lcd.fillRect(POS_X_GRAFICO+1, POS_Y_GRAFICO-1, COMPRIMENTO_GRAFICO, ALTURA_GRAFICO-1, BLACK); leituraAtual = 1; //volta o contador de leitura para 1 (nova coordenada X) } //limpa a área onde colocamos o valor da temperatura e da umidade M5.Lcd.fillRect(POS_X_DADOS+50, POS_Y_DADOS, 60, 30, BLACK); M5.Lcd.fillRect(POS_X_DADOS+165, POS_Y_DADOS, 90, 30, BLACK);

//reposiciona o cursor para escrever a temperatura
M5.Lcd.setCursor(POS_X_DADOS+50, POS_Y_DADOS); M5.Lcd.setTextColor(RED); M5.Lcd.print(temperatura); M5.Lcd.print((char)247); //reposiciona o cursor para escrever a umidade M5.Lcd.setCursor(POS_X_DADOS+165, POS_Y_DADOS); M5.Lcd.setTextColor(CYAN); M5.Lcd.print(umidade); M5.Lcd.print("%"); delay(1000); }

Step 10: Files

Did you like M5Stack? Want to buy one?
Go to:

Download the files:





    • Casting Contest

      Casting Contest
    • Woodworking Contest

      Woodworking Contest
    • Make it Move Contest

      Make it Move Contest

    We have a be nice policy.
    Please be positive and constructive.