#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
// กำหนดที่อยู่ของ LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo gateServo;
// กำหนดพินต่าง ๆ
const int ir_in = 32; // IR sensor สำหรับรถเข้า
const int ir_out = 33; // IR sensor สำหรับรถออก
const int LED_green = 26; // LED สีเขียว
const int LED_red = 27; // LED สีแดง
int total = 0; // จำนวนรถที่จอดในลานจอดรถ
const int capacity = 10; // ความจุของลานจอดรถ
void setup() {
Serial.begin(115200); // เริ่มต้น Serial Monitor
// กำหนดพินของเซ็นเซอร์และ LED
pinMode(ir_in, INPUT);
pinMode(ir_out, INPUT);
pinMode(LED_green, OUTPUT);
pinMode(LED_red, OUTPUT);
// เริ่มต้น servo
gateServo.attach(25);
gateServo.write(180); // ตั้งตำแหน่งเริ่มต้น (ปิดประตู)
// เริ่มต้น LCD
lcd.begin();
lcd.backlight();
lcd.print("Smart Parking");
delay(3000);
lcd.clear();
updateDisplay();
}
void loop() {
if (digitalRead(ir_in) == LOW) {
if (total < capacity) {
total++;
updateDisplay();
controlGate(true); // เปิดประตู
} else {
lcd.setCursor(0, 0);
lcd.print("Parking Full");
delay(1500); // แสดงข้อความ "Parking Full" เป็นเวลา 1.5 วินาที
lcd.clear();
updateDisplay();
}
}
if (digitalRead(ir_out) == LOW) {
if (total > 0) {
total--;
updateDisplay();
controlGate(true); // เปิดประตู
}
}
delay(1000); // หน่วงเวลาสั้นๆ เพื่อความเสถียร
}
void controlGate(bool open) {
if (open) {
gateServo.write(90); // เปิดประตู
delay(3000); // หน่วงเวลา 3000 มิลลิวินาทีให้รถผ่าน
gateServo.write(180); // ปิดประตู
}
}
void updateDisplay() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Slots:");
lcd.print(capacity - total);
lcd.setCursor(0, 1);
lcd.print("In:");
lcd.print(total);
// อัพเดตไฟ LED
if (total < capacity) {
digitalWrite(LED_red, LOW); // ปิดไฟ LED สีแดง
digitalWrite(LED_green, HIGH); // เปิดไฟ LED สีเขียว
} else {
digitalWrite(LED_red, HIGH); // เปิดไฟ LED สีแดง
digitalWrite(LED_green, LOW); // ปิดไฟ LED สีเขียว
}
}