Skip to content

Instantly share code, notes, and snippets.

@jw910731
Created August 20, 2019 07:57
Show Gist options
  • Save jw910731/0e2def48c2d439afc6f52c71d53dc822 to your computer and use it in GitHub Desktop.
Save jw910731/0e2def48c2d439afc6f52c71d53dc822 to your computer and use it in GitHub Desktop.
Arduino RGB LED Library
#include "rgbled.h"
void rgbLed::off(){
emit(0,0,0);
}
void rgbLed::emit(int r, int g, int b){
r = safeAnalog(r);
g = safeAnalog(g);
b = safeAnalog(b);
if(common){
r = 255 - r;
g = 255 - g;
b = 255 - b;
}
analogWrite(srcR, r);
analogWrite(srcG, g);
analogWrite(srcB, b);
}
rgbLed::rgbLed(int r, int g, int b){
rgbLed(r, g, b, false);
}
rgbLed::rgbLed(int r, int g, int b, bool com){
common = com;
srcR = r;
srcG = g;
srcB = b;
pinMode(r, OUTPUT);
pinMode(g, OUTPUT);
pinMode(b, OUTPUT);
off();
}
#ifndef RGBLED_H
#define RGBLED_H
#include "Arduino.h"
class rgbLed{
private:
int srcR, srcG, srcB;
bool common; // common anode => false, common cathode => true;
inline int safeAnalog(int n) const{return min(255, max(0, n));}
public:
rgbLed(int r, int g, int b);
rgbLed(int r, int g, int b, bool com);
void emit(int r, int g, int b);
void off();
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment