#include <Arduino.h>
// ขากำหนด
#define RED_PIN 19
#define GREEN_PIN 18
#define BLUE_PIN 5
#define POT_PIN 34
#define BTN_PIN 21
// ตัวแปร
int mode = 0;
int lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 200;
unsigned long lastChange = 0;
int colorIndex = 0;
// ตารางสีโหมด 3
int colors[7][3] = {
{255, 0, 0}, // แดง
{0, 255, 0}, // เขียว
{0, 0, 255}, // น้ำเงิน
{255, 255, 0}, // เหลือง
{0, 255, 255}, // ฟ้า
{255, 0, 255}, // ม่วง
{255, 255, 255} // ขาว
};
// ฟังก์ชันเขียนค่า RGB
void setColor(int r, int g, int b) {
ledcWrite(0, r);
ledcWrite(1, g);
ledcWrite(2, b);
}
void setup() {
Serial.begin(115200);
pinMode(BTN_PIN, INPUT_PULLUP);
// ตั้งค่า PWM (ESP32 ใช้ ledc)
ledcSetup(0, 5000, 8); // channel 0, freq 5kHz, 8-bit
ledcSetup(1, 5000, 8);
ledcSetup(2, 5000, 8);
ledcAttachPin(RED_PIN, 0);
ledcAttachPin(GREEN_PIN, 1);
ledcAttachPin(BLUE_PIN, 2);
setColor(0,0,0);
}
void loop() {
int reading = digitalRead(BTN_PIN);
if (reading == LOW && lastButtonState == HIGH && millis() - lastDebounceTime > debounceDelay) {
mode = (mode + 1) % 4;
Serial.print("Mode: "); Serial.println(mode+1);
lastDebounceTime = millis();
}
lastButtonState = reading;
int potValue = analogRead(POT_PIN);
int brightness = map(potValue, 0, 4095, 0, 255);
switch(mode) {
case 0: // โหมด 1 White Light
setColor(brightness, brightness, brightness);
break;
case 1: // โหมด 2 Warm Light (โทนส้ม เหลือง)
setColor(brightness, brightness * 0.6, brightness * 0.2);
break;
case 2: { // โหมด 3 RGB Mood
int speed = map(potValue, 0, 4095, 2000, 200); // เร็วขึ้นเมื่อหมุน
if (millis() - lastChange > speed) {
colorIndex = (colorIndex + 1) % 7;
lastChange = millis();
}
setColor(colors[colorIndex][0], colors[colorIndex][1], colors[colorIndex][2]);
}
break;
case 3: { // โหมด 4 Night Light
int nightBrightness = map(potValue, 0, 4095, 0, 76); // 0-30%
setColor(nightBrightness, nightBrightness * 0.5, nightBrightness * 0.1);
}
break;
}
}