#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#define LDR_PIN 2
//DHT
#include <dht.h>
#define dataPin 7
dht DHT;
//LDR Characteristics
const float GAMMA = 0.7;
const float RL10 = 50;
//servo
Servo myservo;
Servo myservo2;
//NTC
const float BETA = 3950;
//lcd 20x4 i2c
LiquidCrystal_I2C lcd(0x27, 20, 4);
//PIR and LCD
int ledPin = 3;
int ledPin2 = 2;
int inputPin = 4;
int pirState = LOW;
int val = 0;
//bargrah
const int ledCount = 10;
int ledPins[] = {
31, 33, 35, 37, 39, 41, 43, 45, 47, 49
};
void setup() {
//LCD
lcd.begin(16, 2);
lcd.init();
lcd.backlight();
pinMode(LDR_PIN, INPUT);
//servo
myservo.attach(6);
myservo2.attach(8);
//buzzer
pinMode(5, OUTPUT);
Serial.begin(9600);
//LED and PIR set up
lcd.init();
pinMode(ledPin, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(inputPin, INPUT);
//bargrah
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT);
}
}
void loop() {
// ค่าตัวแปรของ Temperature และ LUX
int analogValue = analogRead(A0);
float voltage = analogValue / 1024. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
float celsius = 1 / (log(1 / (1023. / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
lcd.setCursor(0, 1);
lcd.print("Temperature: ");
lcd.print(celsius);
lcd.print(" C");
if (lux >= 185) {
if (myservo.read() != 180) {
myservo.write(180);
tone(5, 2000);
delay(500);
noTone(5);
}
} else {
if (myservo.read() != 0) {
myservo.write(0);
tone(5, 1000);
delay(500);
noTone(5);
}
}
// แสดงผลค่า LUX
lcd.setCursor(0, 2);
lcd.print("lux: ");
lcd.print(lux);
delay(100);
//PIR Sensor
val = digitalRead(inputPin);
if (val == HIGH ) {
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin2, HIGH);
pirState = HIGH;
} else {
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, LOW);
pirState = LOW;
}
//DHT
int readData = DHT.read22(dataPin);
float t = DHT.temperature;
float h = DHT.humidity;
Serial.print("Temperature = ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(" Humidity = ");
Serial.print(h);
Serial.println(" % ");
if (h <= 50) {
if (myservo2.read() != 180) {
myservo2.write(180);
delay(500);
}
} else {
if (myservo2.read() != 0) {
myservo2.write(0);
delay(500);
}
}
//bargrah
int sensorReading = analogRead(h);
int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
if (thisLed < ledLevel) {
digitalWrite(ledPins[thisLed], HIGH);
}
else {
digitalWrite(ledPins[thisLed], LOW);
}
}
delay(1000);
}