#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#define DHT_PIN 6
#define DHT_TYPE DHT22
DHT dht(DHT_PIN, DHT_TYPE);
#define BTN_PIN 2
#define TRIG_PIN 3
#define ECHO_PIN 4
#define LED_PIN 8
#define BUZZER_PIN 7
int btn_state;
float temperature;
float humidity;
LiquidCrystal_I2C lcd(0x27, 16, 2);
float measureDistance(){
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
float distance = duration*0.034/2;
return distance;
}
void setup() {
Serial.begin(115200);
pinMode(BTN_PIN, INPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
dht.begin();
lcd.init(); //initialize the lcd
lcd.backlight(); //open the backlight
}
void loop() {
temperature = dht.readTemperature();
humidity = dht.readHumidity();
btn_state = digitalRead(BTN_PIN);
if (btn_state == HIGH){
float distance = measureDistance();
lcd.clear();
lcd.setCursor(0,0);
lcd.print(distance);
lcd.setCursor(13,0);
lcd.print("cm.");
lcd.setCursor(0,1);
lcd.print(temperature);
lcd.setCursor(6,1);
lcd.print("C");
lcd.setCursor(9,1);
lcd.print(humidity);
lcd.setCursor(15,1);
lcd.print("%");
digitalWrite(LED_PIN, HIGH);
tone(BUZZER_PIN, 500);
delay(500);
noTone(BUZZER_PIN);
delay(500);
delay(250);
}
else{
digitalWrite(LED_PIN, LOW);
}
delay(100);
}