#include <DHTesp.h>
#include <LiquidCrystal_I2C.h>
const int BTN_PIN = 5;
const int LED_PIN = 6;
const int DHT_PIN = 7;
const unsigned long TWO_SEC = 2000;
const unsigned long DEBOUNCE_TIME = 20;
unsigned long prevTime = 0;
DHTesp dhtSensor;
LiquidCrystal_I2C lcd(0x27, 16, 2);
void checkButton() {
static unsigned long lastTime = 0;
static bool lastState = HIGH;
bool currentState = digitalRead(BTN_PIN);
const unsigned long now = millis();
if (currentState != lastState && now - lastTime >= DEBOUNCE_TIME) {
if (!currentState) {
Serial.println("Button pressed!");
digitalWrite(LED_PIN, !digitalRead(LED_PIN));
} else {
Serial.println("Button released!");
}
lastTime = now;
lastState = currentState;
}
}
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
pinMode(BTN_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
Serial.println("\nDHT sensor on ESP32-C3!\n");
lcd.setCursor(3, 0);
lcd.print("DHT Temp &");
lcd.setCursor(4, 1);
lcd.print("Humidity");
delay(2000);
lcd.clear();
}
void loop() {
checkButton();
if (millis() - prevTime >= TWO_SEC) {
char dispBuffer[16];
char tempBuff[8];
char humidBuff[8];
TempAndHumidity data = dhtSensor.getTempAndHumidity();
dtostrf(data.temperature, 5, 1, tempBuff);
dtostrf(data.humidity, 5, 1, humidBuff);
snprintf(dispBuffer, 16, "Temp : %s%cC", tempBuff, char(223));
lcd.setCursor(0, 0);
lcd.print(dispBuffer);
snprintf(dispBuffer, 16, "Temp: %s%cC", tempBuff, char(176));
Serial.println(dispBuffer);
snprintf(dispBuffer, 16, "Humid: %s%%", humidBuff);
lcd.setCursor(0, 1);
lcd.print(dispBuffer);
Serial.println(dispBuffer);
Serial.println("---");
prevTime = millis();
}
delay(10); // this speeds up the simulation
}
Loading
esp32-c3-devkitm-1
esp32-c3-devkitm-1