#define BUTTON_PIN 2
byte lastButtonState = HIGH;
//byte ledState = LOW;
unsigned long debounceDuration = 50; // millis
unsigned long lastTimeButtonStateChanged = 0;
int a = 0; // นับจำนวนครั้งที่กดปุ่ม
#include "DHT.h"
#define DHTPIN 3
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
dht.begin();
lcd.init();
lcd.backlight();
lcd.clear();
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - lastTimeButtonStateChanged >= debounceDuration) {
byte buttonState = digitalRead(BUTTON_PIN);
if (buttonState != lastButtonState) {
lastTimeButtonStateChanged = currentMillis;
lastButtonState = buttonState;
if (buttonState == HIGH) {
// Serial.println("======= Press =======");
a=a+1;
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("DHT Failed!!!");
return;
}
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("Temp");
lcd.setCursor(6, 0);
lcd.print(temperature);
lcd.setCursor(1, 1);
lcd.print("Humi");
lcd.setCursor(6, 1);
lcd.print(humidity);
}
}
}
}