/*
2按鈕,控制2Servo動作,LCD1602(I2C)顯示原始數值50。
按鈕1:Servo1開門,5秒後關閉,LCD顯示值-1。
按鈕2:Servo2開門,5秒後關閉,LCD顯示值+1。
*/
#include <ESP32Servo.h> //servo函式庫
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Servo 定義
Servo servo1;
Servo servo2;
const int SERVO1_PIN = 17;
const int SERVO2_PIN = 27;
// 按鈕定義
const int BUTTON1_PIN = 4;
const int BUTTON2_PIN = 13;
// LCD 定義
LiquidCrystal_I2C lcd(0x27, 16, 2);
// 初始值
int total_spaces = 50;
int available_spaces=total_spaces;
bool servo1Active = false;
bool servo2Active = false;
unsigned long servo1StartTime = 0;
unsigned long servo2StartTime = 0;
void setup() {
servo1.attach(SERVO1_PIN);// 初始化 Servo
servo2.attach(SERVO2_PIN);
servo1.write(0); // 初始位置關閉
servo2.write(0);
// 初始化按鈕
pinMode(BUTTON1_PIN, INPUT_PULLUP);
pinMode(BUTTON2_PIN, INPUT_PULLUP);
// 初始化 LCD
lcd.init();
lcd.backlight();
updateLCD();
}
void loop() {
unsigned long currentTime = millis();
// 按鈕1處理
if (digitalRead(BUTTON1_PIN) == LOW && !servo1Active) {
servo1.write(90); // 開門
servo1StartTime = currentTime;
servo1Active = true;
available_spaces--;
}
// 按鈕2處理
if (digitalRead(BUTTON2_PIN) == LOW && !servo2Active) {
servo2.write(90); // 開門
servo2StartTime = currentTime;
servo2Active = true;
available_spaces++;
}
// Servo1計時關閉
if (servo1Active && currentTime - servo1StartTime >= 5000) {
servo1.write(0); // 關門
servo1Active = false;
updateLCD();
}
// Servo2計時關閉
if (servo2Active && currentTime - servo2StartTime >= 5000) {
servo2.write(0); // 關門
servo2Active = false;
updateLCD();
}
}
// 更新 LCD 顯示
void updateLCD() {
lcd.setCursor(0, 0);
lcd.print("Total_spaces: ");
lcd.print(total_spaces);
lcd.setCursor(0, 1);
lcd.print("Available: ");
lcd.print(available_spaces);
lcd.print(" "); // 清除多餘字元
}