#include <Arduino.h>
// ประกาศฟังก์ชันล่วงหน้า
void setWarmColor(int potValue);
void handleButton();
void setBrightnessColor(int potValue, int rBase, int gBase, int bBase);
void setColor(int r, int g, int b);
void rgbMood(int potValue);
void hsvToRgb(int h, float s, float v, int &r, int &g, int &b);
// Pin Mapping
const int redPin = 5;
const int greenPin = 4;
const int bluePin = 2;
const int potPin = 12;
const int buttonPin = 13;
int mode = 1;
bool lastButtonState = HIGH;
unsigned long lastDebounce = 0;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(115200);
}
void loop() {
handleButton();
int potValue = analogRead(potPin);
switch (mode) {
case 1: setBrightnessColor(potValue, 255, 255, 255); break;
case 2: setWarmColor(potValue); break;
case 3: rgbMood(potValue); break;
case 4: {
int brightness = map(potValue, 0, 4095, 0, 76);
setBrightnessColor(brightness, 255, 120, 0);
break;
}
}
}
void handleButton() {
bool currentState = digitalRead(buttonPin);
if (currentState == LOW && lastButtonState == HIGH && millis() - lastDebounce > 200) {
mode = (mode % 4) + 1;
Serial.println("โหมดปัจจุบัน: " + String(mode));
lastDebounce = millis();
}
lastButtonState = currentState;
}
void setBrightnessColor(int potValue, int rBase, int gBase, int bBase) {
float factor = potValue / 255.0;
setColor(rBase * factor, gBase * factor, bBase * factor);
}
void setColor(int r, int g, int b) {
// Common Anode: invert PWM
analogWrite(redPin, 255 - constrain(r, 0, 255));
analogWrite(greenPin, 255 - constrain(g, 0, 255));
analogWrite(bluePin, 255 - constrain(b, 0, 255));
}
void rgbMood(int potValue) {
static unsigned long lastChange = 0;
static int colorIndex = 0;
int delayTime = map(potValue, 0, 4095, 200, 1000); // ยิ่งหมุนเร็ว ยิ่งเปลี่ยนเร็ว
if (millis() - lastChange > delayTime) {
switch (colorIndex) {
case 0: setColor(255, 0, 0); break; // แดง
case 1: setColor(0, 255, 0); break; // เขียว
case 2: setColor(0, 0, 255); break; // น้ำเงิน
case 3: setColor(255, 255, 0); break; // เหลือง
case 4: setColor(255, 0, 255); break; // ม่วง
case 5: setColor(0, 255, 255); break; // ฟ้า
}
colorIndex = (colorIndex + 1) % 6;
lastChange = millis();
}
}
void hsvToRgb(int h, float s, float v, int &r, int &g, int &b) {
float c = v * s;
float x = c * (1 - abs(fmod(h / 60.0, 2) - 1));
float m = v - c;
float rp, gp, bp;
if (h < 60) { rp = c; gp = x; bp = 0; }
else if (h < 120) { rp = x; gp = c; bp = 0; }
else if (h < 180) { rp = 0; gp = c; bp = x; }
else if (h < 240) { rp = 0; gp = x; bp = c; }
else if (h < 300) { rp = x; gp = 0; bp = c; }
else { rp = c; gp = 0; bp = x; }
r = (rp + m) * 255;
g = (gp + m) * 255;
b = (bp + m) * 255;
}
void setWarmColor(int potValue) {
int brightness = map(potValue, 0, 4095, 0, 255);
int r = brightness;
int g = brightness * 0.5;
int b = brightness * 0.2;
setColor(r, g, b);
}