// Declare pins and constants
const int led_red = 4;
const int led_yellow = 5;
const int led_green = 6;
const int button = 2;
int Vread;
int Vpot;
bool state = 0;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;
bool lastButtonState = HIGH;
bool currentButtonState = HIGH;
unsigned long previousMillis = 0; // สำหรับการกระพริบ LED ใน mode2
const unsigned long interval = 1000; // หน่วงเวลา 1 วินาที
bool ledState = LOW; // สถานะของ LED ใน mode2
void setup() {
pinMode(led_red, OUTPUT);
pinMode(led_yellow, OUTPUT);
pinMode(led_green, OUTPUT);
pinMode(button, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
// อ่านสถานะของปุ่มและ debounce
bool reading = digitalRead(button);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading == LOW && currentButtonState == HIGH) {
state = !state; // สลับโหมด
Serial.println("Mode changed to: " + String(state));
}
currentButtonState = reading;
}
lastButtonState = reading;
// อ่านค่า potentiometer
Vread = analogRead(A0);
Vpot = map(Vread, 0, 1023, 0, 5);
Serial.println("Vpot = " + String(Vpot) + " V");
// เรียกโหมดที่เหมาะสม
if (state == 0) {
mode1();
} else {
mode2();
}
}
// Mode 1: ควบคุม LED ตามค่า Vpot
void mode1() {
if (Vpot == 0) {
digitalWrite(led_red, LOW);
digitalWrite(led_yellow, LOW);
digitalWrite(led_green, LOW);
} else if (Vpot == 1) {
digitalWrite(led_red, HIGH);
digitalWrite(led_yellow, LOW);
digitalWrite(led_green, LOW);
} else if (Vpot == 2) {
digitalWrite(led_red, LOW);
digitalWrite(led_yellow, HIGH);
digitalWrite(led_green, LOW);
} else {
digitalWrite(led_red, LOW);
digitalWrite(led_yellow, LOW);
digitalWrite(led_green, HIGH);
}
}
// Mode 2: LED กระพริบทุกดวงแบบ non-blocking
void mode2() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// เปลี่ยนสถานะ LED
ledState = !ledState;
digitalWrite(led_red, ledState);
digitalWrite(led_yellow, ledState);
digitalWrite(led_green, ledState);
}
}