/**
ESP32 + DHT22 Example for Wokwi
https://wokwi.com/arduino/projects/322410731508073042
*/
#include "DHTesp.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Sound speed in air
#define SOUND_SPEED 340
#define TRIG_PULSE_DURATION_US 10
const int trig_pin = 5;
const int echo_pin = 18;
const int DHT_PIN = 15;
DHTesp dhtSensor;
// set the LCD number of columns and rows
int lcdColumns = 16;
int lcdRows = 2;
// set LCD address, number of columns and rows
// if you don't know your display address, run an I2C scanner sketch
LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows);
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
long ultrason_duration;
float distance_cm;
void setup() {
// Wire.begin();
Serial.begin(115200);
pinMode(trig_pin, OUTPUT); // We configure the trig as output
pinMode(echo_pin, INPUT); // We configure the echo as input
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// Serial.println("\nI2C Scanner");
// initialize LCD
lcd.init();
// turn on LCD backlight
lcd.backlight();
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
delay(2000);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 10);
// Display static text
display.println("Hello, world!");
display.display();
}
void loop() {
display.clearDisplay();
// display.display();
TempAndHumidity data = dhtSensor.getTempAndHumidity();
Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
Serial.println("---");
// delay(1000);
// set cursor to first column, first row
lcd.setCursor(0, 0);
// print message
lcd.print("Hello, World!");
display.setCursor(5, 10);
// Display static text
display.println("tes");
delay(1000);
// clears the display to print new message
lcd.clear();
display.display();
// set cursor to first column, second row
lcd.setCursor(0,1);
lcd.print("Hello, World!");
display.setCursor(3, 40);
// Display static text
display.println("tes");
// Set up the signal
digitalWrite(trig_pin, LOW);
delayMicroseconds(2);
// Create a 10 µs impulse
digitalWrite(trig_pin, HIGH);
delayMicroseconds(TRIG_PULSE_DURATION_US);
digitalWrite(trig_pin, LOW);
// Return the wave propagation time (in µs)
ultrason_duration = pulseIn(echo_pin, HIGH);
//distance calculation
distance_cm = ultrason_duration * SOUND_SPEED/2 * 0.0001;
// We print the distance on the serial port
Serial.print("Distance (cm): ");
Serial.println(distance_cm);
delay(1000);
lcd.clear();
display.display();
}