/*J. Paewai 2019
RGB Back light controller using a joy stick
Works much better in real world that simulator.
Pushing button makes while light.
*/
// Circuit Setup
const int PUSHBUTTON_PIN = 2;
const int RED_PIN = 11;
const int GREEN_PIN = 10;
const int BLUE_PIN = 9;
const int xAxis_PIN = A0;
const int yAxis_PIN = A1;
const int redX = 512;
const int redY = 1023;
const int greenX = 1023;
const int greenY = 0;
const int blueX = 0;
const int blueY = 0;
int distanceRed =0;
int distanceGreen=0;
int distanceBlue = 0;
int brightRed = 0;
int brightGreen = 0;
int brightBlue = 0;
int xAxis = 0;
int yAxis = 0;
//Mode Set the LED Type - Common Anode or Common Cathode
// byte mode = 1; // Common Cathode (-)
byte mode = 0; // Common Anode (+) ** My LCD Backlights
void setup() {
Serial.begin(9600);
pinMode(PUSHBUTTON_PIN, INPUT);
digitalWrite(PUSHBUTTON_PIN, HIGH);
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
}
void loop() {
int xAxis = analogRead(xAxis_PIN);
int yAxis = analogRead(yAxis_PIN);
// Flip orientation (if needed)
xAxis = map(xAxis, 0, 1023, 0, 1023);
yAxis = map(yAxis, 0, 1023, 1023, 0);
distanceRed = sqrt(pow(abs(redX - xAxis), 2) + pow(abs(redY - yAxis), 2));
distanceGreen = sqrt(pow(abs(greenX - xAxis), 2) + pow(abs(greenY - yAxis), 2));
distanceBlue = sqrt(pow(abs(blueX - xAxis), 2) + pow(abs(blueY - yAxis), 2));
if (mode==1) { // Common Cathode (-)
brightRed = 255 - constrain(map(distanceRed, 0, 1023, 0, 255), 0, 255);
brightGreen = 255 - constrain(map(distanceGreen, 0, 1023, 0, 255), 0, 255);
brightBlue = 255 - constrain(map(distanceBlue, 0, 1023, 0, 255), 0, 255);
if (digitalRead(PUSHBUTTON_PIN) == 0) {
brightRed = 255;
brightGreen = 255;
brightBlue = 255;
}
}
if (mode==0) { // Common Anode (-)
brightRed = constrain(map(distanceRed, 0, 1023, 0, 255), 0, 255);
brightGreen = constrain(map(distanceGreen, 0, 1023,0,555), 0, 255);
brightBlue = constrain(map(distanceBlue, 0, 1023, 0, 255), 0, 255);
if (digitalRead(PUSHBUTTON_PIN) == 0) {
brightRed = 0;
brightGreen = 0;
brightBlue = 0;
}
}
analogWrite(RED_PIN, brightRed);
analogWrite(GREEN_PIN, brightGreen);
analogWrite(BLUE_PIN, brightBlue);
delay(100);
//dataDisplay();
}
void dataDisplay(void)
{
Serial.print("KEY: ");
Serial.print(digitalRead(PUSHBUTTON_PIN));
Serial.print(", X: "); Serial.print(xAxis);
Serial.print(", Y: "); Serial.print(yAxis);
Serial.print(", R: "); Serial.print(brightRed);
Serial.print(", G: "); Serial.print(brightGreen);
Serial.print(", B: "); Serial.print(brightBlue);
Serial.print(", Mode "); Serial.print(mode,DEC);
Serial.println("\n");
}