ESP8266 - Sensor de Temperatura e Umidade - OLED

Este tutorial ensina você a usar o ESP8266 para ler a temperatura e a umidade do sensor DHT11/DHT22 e exibi-las em um OLED.

ESP8266 NodeMCU DHT11/DHT22 sensor de temperatura e umidade display OLED

Hardware Necessário

1×ESP8266 NodeMCU ESP-12F
1×Alternatively, ESP8266 D1 Mini NodeMCU ESP-12F
1×Alternatively, ESP8266 NodeMCU ESP-12E (Uno-form)
1×Micro USB Cable
1×Alternatively, ESP8266 NodeMCU ESP-12F (SMD-form)
1×Cabo USB Tipo-A para Tipo-C (para PC com USB-A)
1×Cabo USB Tipo-C para Tipo-C (para PC com USB-C)
1×Display OLED I2C SSD1306 128x64
1×Display OLED I2C SSD1306 128x32
1×Sensor de Temperatura e Umidade DHT11
1×(Alternativa) DHT11 Sensor
1×Fios Jumper

Você pode usar o sensor DHT22 no lugar do sensor DHT11.

1×(Recomendado) Placa de Expansão com Bornes de Parafuso para ESP8266

Or you can buy the following kits:

1×DIYables Sensor Kit (18 sensors/displays)
Divulgação: Alguns dos links desta seção são links de afiliado da Amazon. Podemos receber uma comissão pelas compras feitas por meio desses links, sem custo adicional para você. Agradecemos o seu apoio.

Buy Note: If you want a bigger OLED display, use the 2.42 inch OLED Display 128x64 .

Sobre o Display OLED e o Sensor de Temperatura e Umidade DHT11 e DHT22

Se você não conhece o display OLED e o sensor de temperatura e umidade DHT11 e DHT22 (incluindo pinagem, funcionamento, programação etc.), os tutoriais a seguir podem ajudar:

Diagrama de Ligação

ESP8266 - Ligação do Módulo DHT11 com LCD

ESP8266 NodeMCU DHT11 Sensor OLED diagrama de ligação

This image is created using Fritzing. Click to enlarge image

Para mais informações, veja Pinagem do ESP8266 e como alimentar o ESP8266 e outros componentes.

ESP8266 - Ligação do Módulo DHT22 com LCD

ESP8266 NodeMCU DHT22 Sensor OLED diagrama de ligação

This image is created using Fritzing. Click to enlarge image

Código ESP8266 - Sensor DHT11 - OLED

/* * Este código de ESP8266 NodeMCU foi desenvolvido por pt.newbiely.com * Este código de ESP8266 NodeMCU é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp8266/esp8266-temperature-humidity-sensor-oled */ #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include <DHT.h> #define OLED_WIDTH 128 // OLED display width, in pixels #define OLED_HEIGHT 64 // OLED display height, in pixels #define DHT_PIN 2 // pin connected to DHT11 sensor #define DHT_TYPE DHT11 Adafruit_SSD1306 oled(OLED_WIDTH, OLED_HEIGHT, &Wire, -1); // create SSD1306 display object connected to I2C DHT dht(DHT_PIN, DHT_TYPE); String temperature; String humidity; void setup() { Serial.begin(9600); // initialize OLED display with address 0x3C for 128x64 if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Serial.println(F("SSD1306 allocation failed")); while (true) ; } delay(2000); // wait for initializing oled.clearDisplay(); // clear display oled.setTextSize(3); // text size oled.setTextColor(WHITE); // text color oled.setCursor(0, 10); // position to display dht.begin(); // initialize DHT11 the temperature and humidity sensor temperature.reserve(10); // to avoid fragmenting memory when using String humidity.reserve(10); // to avoid fragmenting memory when using String } void loop() { float humi = dht.readHumidity(); // read humidity float tempC = dht.readTemperature(); // read temperature // check if any reads failed if (isnan(humi) || isnan(tempC)) { temperature = "Failed"; humidity = "Failed"; } else { temperature = String(tempC, 1); // one decimal places temperature += char(247); // degree character temperature += "C"; humidity = String(humi, 1); // one decimal places humidity += "%"; } Serial.print(tempC); // print to Serial Monitor Serial.print("°C | " ); // print to Serial Monitor Serial.print(humi); // print to Serial Monitor Serial.println("%"); // print to Serial Monitor oledDisplayCenter(temperature, humidity); // display temperature and humidity on OLED } void oledDisplayCenter(String temperature, String humidity) { int16_t x1; int16_t y1; uint16_t width_T; uint16_t height_T; uint16_t width_H; uint16_t height_H; oled.getTextBounds(temperature, 0, 0, &x1, &y1, &width_T, &height_T); oled.getTextBounds(temperature, 0, 0, &x1, &y1, &width_H, &height_H); // display on horizontal and vertical center oled.clearDisplay(); // clear display oled.setCursor((SCREEN_WIDTH - width_T) / 2, SCREEN_HEIGHT / 2 - height_T - 5); oled.println(temperature); // text to display oled.setCursor((SCREEN_WIDTH - width_H) / 2, SCREEN_HEIGHT / 2 + 5); oled.println(humidity); // text to display oled.display(); }

Passos Rápidos

Para começar com o ESP8266 no Arduino IDE, siga estes passos:

  • Confira o tutorial como configurar o ambiente para o ESP8266 no Arduino IDE se esta for a sua primeira vez usando o ESP8266.
  • Ligue os componentes como mostrado no diagrama.
  • Conecte a placa ESP8266 ao seu computador usando um cabo USB.
  • Abra o Arduino IDE no seu computador.
  • Escolha a placa ESP8266 correta, como (por exemplo, NodeMCU 1.0 (ESP-12E Module)), e a respectiva porta COM.
  • Clique no ícone Libraries na barra à esquerda do Arduino IDE.
  • Pesquise por “SSD1306” e localize a biblioteca SSD1306 da Adafruit.
  • Em seguida, pressione o botão Install para concluir a instalação.
ESP8266 NodeMCU biblioteca OLED
  • Você será solicitado a instalar dependências adicionais de bibliotecas.
  • Para instalar todas elas, clique no botão Install All.
ESP8266 NodeMCU biblioteca Adafruit GFX
  • Pesquise por “DHT” e localize a biblioteca de sensor DHT da Adafruit.
  • Pressione o botão Install para instalar a biblioteca.
ESP8266 NodeMCU biblioteca de sensor DHT
  • Você será solicitado a instalar algumas outras dependências de bibliotecas.
  • Clique no botão Install All para instalar todas as dependências de bibliotecas.
ESP8266 NodeMCU biblioteca Adafruit Unified Sensor
  • Copie o código e abra-o com o Arduino IDE.
  • Clique no botão Upload no Arduino IDE para compilar e fazer upload do código para o ESP8266.
  • Coloque o sensor em água quente e fria, ou segure-o na mão.
  • Veja o resultado no display OLED e no Serial Monitor.

※ Nota:

O código em questão centraliza o texto horizontal e verticalmente em um display OLED.

Código ESP8266 - Sensor DHT22 - OLED

/* * Este código de ESP8266 NodeMCU foi desenvolvido por pt.newbiely.com * Este código de ESP8266 NodeMCU é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp8266/esp8266-temperature-humidity-sensor-oled */ #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include <DHT.h> #define OLED_WIDTH 128 // OLED display width, in pixels #define OLED_HEIGHT 64 // OLED display height, in pixels #define DHT_PIN 2 // pin connected to DHT22 sensor #define DHT_TYPE DHT22 Adafruit_SSD1306 oled(OLED_WIDTH, OLED_HEIGHT, &Wire, -1); // create SSD1306 display object connected to I2C DHT dht(DHT_PIN, DHT_TYPE); String temperature; String humidity; void setup() { Serial.begin(9600); // initialize OLED display with address 0x3C for 128x64 if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Serial.println(F("SSD1306 allocation failed")); while (true) ; } delay(2000); // wait for initializing oled.clearDisplay(); // clear display oled.setTextSize(3); // text size oled.setTextColor(WHITE); // text color oled.setCursor(0, 10); // position to display dht.begin(); // initialize DHT22 the temperature and humidity sensor temperature.reserve(10); // to avoid fragmenting memory when using String humidity.reserve(10); // to avoid fragmenting memory when using String } void loop() { float humi = dht.readHumidity(); // read humidity float tempC = dht.readTemperature(); // read temperature // check if any reads failed if (isnan(humi) || isnan(tempC)) { temperature = "Failed"; humidity = "Failed"; } else { temperature = String(tempC, 1); // one decimal places temperature += char(247); // degree character temperature += "C"; humidity = String(humi, 1); // one decimal places humidity += "%"; Serial.print(tempC); // print to Serial Monitor Serial.print("°C | " ); // print to Serial Monitor Serial.print(humi); // print to Serial Monitor Serial.println("%"); // print to Serial Monitor } oledDisplayCenter(temperature, humidity); // display temperature and humidity on OLED } void oledDisplayCenter(String temperature, String humidity) { int16_t x1; int16_t y1; uint16_t width_T; uint16_t height_T; uint16_t width_H; uint16_t height_H; oled.getTextBounds(temperature, 0, 0, &x1, &y1, &width_T, &height_T); oled.getTextBounds(temperature, 0, 0, &x1, &y1, &width_H, &height_H); // display on horizontal and vertical center oled.clearDisplay(); // clear display oled.setCursor((SCREEN_WIDTH - width_T) / 2, SCREEN_HEIGHT / 2 - height_T - 5); oled.println(temperature); // text to display oled.setCursor((SCREEN_WIDTH - width_H) / 2, SCREEN_HEIGHT / 2 + 5); oled.println(humidity); // text to display oled.display(); }

※ Nota:

O código para o DHT11 e o DHT22 é o mesmo, exceto por uma única linha. A biblioteca para ambos também é a mesma.

Vídeo

※ NOSSAS MENSAGENS

  • Fique à vontade para compartilhar o link deste tutorial. Porém, por favor, não use nosso conteúdo em outros sites. Investimos muito esforço e tempo para criar este conteúdo, por favor respeite nosso trabalho!