const int buttonPin = 2; // 按鈕接在Arduino的2號腳位
const int relayPin = 3; // 繼電器接在Arduino的3號腳位
int buttonState = 0; // 按鈕當前狀態
int lastButtonState = 0; // 按鈕前一次狀態
bool relayState = false; // 繼電器狀態 (false = 關閉, true = 開啟)
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, LOW);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {
if (buttonState == LOW) {
relayState = !relayState;
digitalWrite(relayPin, relayState ? HIGH : LOW);
}
delay(50);
}
lastButtonState = buttonState;
}