#include <Servo.h> //library servo
#include <DHT.h>//library dht
#include <LiquidCrystal_I2C.h> //library lcd
#define TRIG_PIN 9 // Digital pin connected to the trigger pin of HC-SR04 sensor
#define ECHO_PIN 10 // Digital pin connected to the echo pin of HC-SR04 sensor
#define DHT_PIN 7 // Digital pin connected to the DHT22 sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302) sensor type
#define BUZZER_PIN 6 // Digital pin connected to the buzzer
Servo myservo;///Create a servo object to control the servo motor
DHT dht(DHT_PIN, DHTTYPE); // Create a DHT object to read data from the DHT22 sensor
LiquidCrystal_I2C LCD(0x27, 16, 2); /* Create an LCD object using the I2C address 0x27,
with 16 columns and 2 rows*/
long duration, distance; // variable ultrasonik
float temperature, humidity; // variabel DHT22
void setup() {
Serial.begin(9600);//memulai komunikasi serial dengan baud rate 9600
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
myservo.attach(5); // Attach the servo to the specified pin
dht.begin(); //inisialisasi dht
LCD.init(); //inisialisasi lcd
LCD.backlight(); // Turn on the backlight for the LCD
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
//pembacaan sensor ultrasonik di serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = (duration / 2) / 29.1;
/*The value 29.1 is derived from the speed of sound in air
(approximately 343 meters per second or 34300 centimeters per second)
divided by 2 (for one-way travel) and then converted from microseconds to centimeters.*/
//pembacaan sensor dht
temperature = dht.readTemperature();
humidity = dht.readHumidity();
//display lcd
LCD.clear();
LCD.setCursor(0,0);//letak di kolom 0, baris 0
LCD.print("T=");
LCD.print(int(temperature)); LCD.print(char(223)); LCD.print('C');
LCD.setCursor(8,0); // letak di kolom 8, baris 0
LCD.print(" H=");
LCD.print(int(humidity)); LCD.print(char(37));
delay(50);
// Check proximity
if (distance < 20) {
// If an object is close, activate the buzzer and move the servo to 90 degrees
tone(BUZZER_PIN, 1000);
tone(BUZZER_PIN, 1000);
myservo.write(90);
LCD.setCursor(0,1);
LCD.print("ada yang dekat");
}
else {
//// If no object is close, turn off the buzzer and move the servo to 0 degrees
myservo.write(0); // Return the servo to its initial position
noTone(BUZZER_PIN);
LCD.setCursor(0,1);
LCD.print("semua jauh");
}
delay(1000);//// Delay for 1 second before repeating the loop
}