Created
November 9, 2010 18:30
-
-
Save aambrozkiewicz/669544 to your computer and use it in GitHub Desktop.
Arduino 3x1 byte wise RGB Serial driven LED
This file contains 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
/* | |
.. | |
RGB led(7, 8, 9); | |
led.color.r = 234; | |
led.color.g = 223; | |
led.color.b = 167; | |
led.write(); | |
.. | |
*/ | |
#ifndef _RGB_H_ | |
#define _RGB_H_ | |
#include <inttypes.h> | |
struct Color | |
{ | |
uint8_t r, g, b; | |
}; | |
class RGB | |
{ | |
public: | |
RGB(uint8_t, uint8_t, uint8_t); | |
void write(void); | |
Color color; | |
private: | |
uint8_t Rpin, Gpin, Bpin; | |
}; | |
#endif |
This file contains 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 "RGB.h" | |
#include "WProgram.h" | |
RGB::RGB(uint8_t r, uint8_t g, uint8_t b) | |
{ | |
Rpin = r; | |
Gpin = g; | |
Bpin = b; | |
} | |
void RGB::write(void) | |
{ | |
analogWrite(Rpin, color.r); | |
analogWrite(Gpin, color.g); | |
analogWrite(Bpin, color.b); | |
} |
This file contains 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 <RGB.h> | |
#define DEBUG | |
RGB led(9, 10, 11); | |
byte *colors[] = { &led.color.r, &led.color.g, &led.color.b }; | |
void setup() | |
{ | |
Serial.begin(9600); | |
} | |
void loop() | |
{ | |
if (Serial.available() > 0) | |
{ | |
unsigned long rgb = 0; | |
for (int i=6; i>0; i--) | |
{ | |
byte incomingByte = Serial.read(); | |
#ifdef DEBUG | |
Serial.println(incomingByte); | |
#endif | |
rgb += hex2int(incomingByte)*myPow(16, i-1); // MFB first | |
} | |
led.color.r = (rgb >> 16); | |
led.color.g = ((rgb >> 8) & 0xFF); | |
led.color.b = (rgb & 0xFF); | |
led.write(); | |
#ifdef DEBUG | |
Serial.print(*colors[0], HEX); | |
Serial.print(*colors[1], HEX); | |
Serial.print(*colors[2], HEX); | |
Serial.println(); | |
#endif | |
} | |
} | |
int hex2int(char c) | |
{ | |
if (c >= '0' && c <= '9') { | |
return c - '0'; | |
} else if (c >= 'a' && c <= 'f') { | |
return c - 'a' + 10; | |
} else if (c >= 'A' && c <= 'F') { | |
return c - 'A' + 10; | |
} else { | |
return -1; | |
} | |
} | |
unsigned long myPow(int b, int e) | |
{ | |
unsigned long result = 1; | |
for (; e>0; e--) | |
result *= b; | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment