Created
April 21, 2018 05:33
-
-
Save nkuln/acea75441fcfcaf9b895965834b31962 to your computer and use it in GitHub Desktop.
Color-changing RGB LED by rotating hue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Keyboard.h> | |
#include <math.h> | |
#define BLUE 3 | |
#define GREEN 5 | |
#define RED 6 | |
void setup() | |
{ | |
pinMode(RED, OUTPUT); | |
pinMode(GREEN, OUTPUT); | |
pinMode(BLUE, OUTPUT); | |
digitalWrite(RED, HIGH); | |
digitalWrite(GREEN, HIGH); | |
digitalWrite(BLUE, LOW); | |
} | |
int redValue; | |
int greenValue; | |
int blueValue; | |
// See https://stackoverflow.com/a/8510751. | |
double m[3][3] = { | |
{0.9998984634375941, -0.010025383273369482, 0.010126919835775301}, | |
{0.010126919835775301, 0.9998984634375941, -0.010025383273369482}, | |
{-0.010025383273369482, 0.010126919835775301, 0.9998984634375941}}; | |
int clamp(double v) { | |
if (v < 0) return 0; | |
if (v > 255) return 255; | |
return int(v + 0.5); | |
} | |
void apply(int* r, int* g, int* b) { | |
double ro = *r, go = *g, bo = *b; | |
*r = clamp(ro * m[0][0] + go * m[0][1] + bo * m[0][2]); | |
*g = clamp(ro * m[1][0] + go * m[1][1] + bo * m[1][2]); | |
*b = clamp(ro * m[2][0] + go * m[2][1] + bo * m[2][2]); | |
} | |
void loop() { | |
redValue = 255; | |
greenValue = 255; | |
blueValue = 0; | |
for(int i = 0; i < 360; i += 1) { | |
analogWrite(RED, redValue); | |
analogWrite(GREEN, greenValue); | |
analogWrite(BLUE, blueValue); | |
delay(10); | |
apply(&redValue, &greenValue, &blueValue); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment