const int SW = 8;
const int switchPin = 9;
byte led = 10;
byte led1 = 11;
byte led2 = 12;
byte led3 = 13;
int lastSwitchState = HIGH;// เก็บค่าสถานะก่อนหน้า
int currentSwitchState;// เก็บค่าสถานะปัจจุบัน
bool ison = false;// เก็บสถานะ On/Off
int speedState = 0; // 0: off, 1: Speed1, 2: Speed2,Speed3
void setup() {
pinMode (SW, INPUT_PULLUP); // กำหนดสวิตซ์ให้เป็น INPUT_PULLUP
Serial. begin (9600);// เริ่ม Serial Monitor
pinMode(switchPin, INPUT_PULLUP); //กำหนดสวิตช์ให้เป็น INPUT JPULLUP
pinMode (led, OUTPUT);
pinMode (led1, OUTPUT);
pinMode (led2, OUTPUT);
Serial.println();
pinMode (led3, OUTPUT);
}
void loop() {
// อ่านค่าจากสวิตซ์
currentSwitchState = digitalRead (SW);
// ตรวจสอบการกดสวิตซ์
if (currentSwitchState
== LOW && lastSwitchState == HIGH) {
// สลับสถานะ On/Off
ison = true;// แสดงสถานะ
if (ison) {
Serial.println("สถานะ : On") ;
digitalWrite (led, 1);
} else {
Serial.println("สถานะ:off");
digitalWrite(led, 0);
delay (500);
}// หน่วงเวลาเพื่อป้องกันการอ่านซ้ำ
//อ่านค่าจากสวิตซ์
currentSwitchState = digitalRead(switchPin);
//ตรวจสอบการกดสวิตซ์
if (currentSwitchState == LOW && lastSwitchState == HIGH) {
// เปลี่ยนสถานะ Speed
} else if (speedState == 2) {
Serial. println("พัดลม: Speed2") ;
digitalWrite (led1, 0);
digitalWrite (led2, 1);
} else if (speedState == 3) {
Serial.println("พัดลม: Speed3") ;
digitalWrite(led2, 0) ;
digitalWrite(led3, 1) ;
}
delay (500);
// บันทึกสถานะปัจจุบันไว้เพื่อใช้ตรวจสอบในรอบถัดไป
lastSwitchState = currentSwitchState;
speedState = (speedState + 1) % 4;
//แสดงสถานะ
if (speedState == 1) {
Serial.println("พัดลม: Speed1") ;
digitalWrite(led3, 0);
digitalWrite(led1, 1);
}
}
}