#define RED 25
#define GREEN 26
#define BLUE 27
#define PM 33
#define BUTTON 32
#define LEDC_CH_0 0
#define LEDC_CH_1 1
#define LEDC_CH_2 2
#define LEDC_TIMER_BIT 8
#define LEDC_BASE_FREQ 5000
int mode = 1;
bool buttonPressed = false;
void handleButtonPress() {
if (!buttonPressed) {
buttonPressed = true;
mode++;
if (mode > 4) mode = 1;
}
}
void setup() {
Serial.begin(115200);
pinMode(BUTTON, INPUT);
attachInterrupt(BUTTON, handleButtonPress, FALLING);
ledcAttachChannel(RED, LEDC_BASE_FREQ, LEDC_TIMER_BIT, LEDC_CH_0);
ledcAttachChannel(GREEN, LEDC_BASE_FREQ, LEDC_TIMER_BIT, LEDC_CH_1);
ledcAttachChannel(BLUE, LEDC_BASE_FREQ, LEDC_TIMER_BIT, LEDC_CH_2);
}
void loop() {
int dataPM = analogRead(PM);
int mode1 = map(dataPM, 0, 4095, 0, 100);
int mode2 = map(dataPM, 0, 4095, 100, 5000);
int mode3 = map(dataPM, 0, 4095, 0, 30);
if (buttonPressed) {
delay(500);
buttonPressed = false;
}
switch (mode) {
case 1:
Serial.println("mode 1");
// โหมด 1: สีขาว ปรับความสว่างด้วย mode1
ledcWrite(RED, map(mode1, 0, 100, 255, 0)); // สีแดง
ledcWrite(GREEN, map(mode1, 0, 100, 255, 0)); // สีเขียว
ledcWrite(BLUE, map(mode1, 0, 100, 255, 0)); // สีน้ำเงิน
break;
case 2:
Serial.println("mode 2");
// โหมด 2: สีเหลืองอ่อน ปรับความสว่างด้วย mode1
ledcWrite(RED, map(mode1, 0, 100, 255, 0)); // สีแดง
ledcWrite(GREEN, map(mode1, 0, 100, 255, 0)); // สีเขียว
ledcWrite(BLUE, 150); // สีน้ำเงิน
delay(50);
break;
case 3:
Serial.println("mode 3");
// โหมด 3: RGB 6 สี วิ่งช้าแบบโรแมนติก
static unsigned long lastUpdate = 0;
static int step = 0;
if (millis() - lastUpdate > 1500) { // เพิ่มความหน่วงให้การเปลี่ยนสีช้าลง (1.5 วินาที)
lastUpdate = millis();
switch (step) {
case 0: // Red
ledcWrite(RED, 255);
ledcWrite(GREEN, 0);
ledcWrite(BLUE, 0);
break;
case 1: // Green
ledcWrite(RED, 0);
ledcWrite(GREEN, 255);
ledcWrite(BLUE, 0);
break;
case 2: // Blue
ledcWrite(RED, 0);
ledcWrite(GREEN, 0);
ledcWrite(BLUE, 255);
break;
case 3: // Magenta
ledcWrite(RED, 255);
ledcWrite(GREEN, 0);
ledcWrite(BLUE, 255);
break;
case 4: // Cyan
ledcWrite(RED, 0);
ledcWrite(GREEN, 255);
ledcWrite(BLUE, 255);
break;
case 5: // Yellow
ledcWrite(RED, 255);
ledcWrite(GREEN, 255);
ledcWrite(BLUE, 0);
break;
}
step = (step + 1) % 6; // วนรอบ 6 ขั้นตอน
}
break;
case 4:
Serial.println("mode 4");
// โหมด 4: สีส้มอ่อน ปรับความสว่างด้วย mode3
ledcWrite(RED, map(mode3, 0, 30, 255, 0)); // สีแดง
ledcWrite(GREEN, map(mode3, 0, 30, 127, 0)); // สีเขียว
ledcWrite(BLUE, 100);
delay(50);
break;
}
delay(500);
}