#include <LiquidCrystal_I2C.h>
#define R_PIN 10
#define G_PIN 9
#define B_PIN 8
#define BUTTON_PIN 3
#define RESISTOR A0
class RGB
{
public:
RGB(uint8_t redPin, uint8_t greenPin, uint8_t bluePin)
: rPin(redPin)
, gPin(greenPin)
, bPin(bluePin)
{
pinMode(rPin, OUTPUT);
pinMode(gPin, OUTPUT);
pinMode(bPin, OUTPUT);
}
void setRGB(unsigned int red, unsigned int green, unsigned int blue) {
setR(red);
setG(green);
setB(blue);
}
void setR(unsigned int red) {
analogWrite(rPin, red);
}
void setG(unsigned int green) {
analogWrite(gPin, green);
}
void setB(unsigned int blue) {
analogWrite(bPin, blue);
}
private:
uint8_t rPin, gPin, bPin;
};
class RGBController
{
public:
RGBController(RGB led): m_led(led){}
setLight(unsigned int light) {
switch (m_state)
{
case RGBState::RED:
m_led.setR(light);
m_red = light;
break;
case RGBState::GREEN:
m_led.setG(light);
m_green = light;
break;
default:
m_led.setB(light);
m_blue = light;
}
}
RGBController& operator++() {
const int i = static_cast<int>(m_state);
m_state = static_cast<RGBState>((i + 1) % 3);
return *this;
}
String getState() {
return String(static_cast<int>(m_state));
}
uint16_t getR() {return m_red;}
uint16_t getG() {return m_green;}
uint16_t getB() {return m_blue;}
private:
enum class RGBState {
RED = 1,
GREEN = 2,
BLUE = 3,
};
RGB m_led;
RGBState m_state = RGBState::RED;
unsigned int m_red = 0;
unsigned int m_green = 0;
unsigned int m_blue = 0;
};
RGB led(R_PIN, G_PIN, B_PIN);
RGBController controller(led);
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(RESISTOR, INPUT);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
}
void loop() {
onButtonClick([]() { controller++; });
int light = analogRead(RESISTOR);
light = map(light, 0, 1023, 0, 255);
controller.setLight(light);
String r = String(controller.getR());
String g = String(controller.getG());
String b = String(controller.getB());
lcd.setCursor(0, 0);
lcd.print("R: ");
lcd.setCursor(2, 0);
lcd.print(r);
lcd.setCursor(6, 0);
lcd.print("G: ");
lcd.setCursor(8, 0);
lcd.print(g);
lcd.setCursor(0, 1);
lcd.print("B: ");
lcd.setCursor(2, 1);
lcd.print(b);
Serial.println(r + " " + g + " " + b);
delay(100);
}
int lastState = HIGH;
void onButtonClick(void (*callback)()) {
int buttonValue = digitalRead(BUTTON_PIN);
if (lastState != buttonValue) {
lastState = buttonValue;
if (buttonValue == HIGH) {
callback();
}
}
}