Skip to content

Instantly share code, notes, and snippets.

@nkuln
Created April 21, 2018 05:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkuln/acea75441fcfcaf9b895965834b31962 to your computer and use it in GitHub Desktop.
Save nkuln/acea75441fcfcaf9b895965834b31962 to your computer and use it in GitHub Desktop.
Color-changing RGB LED by rotating hue
#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