Skip to content

Instantly share code, notes, and snippets.

@sobreira
Forked from doojinkang/RBGLED.ino
Created October 15, 2020 01:47
Show Gist options
  • Save sobreira/046d472ab76f329028e386396e9dc4ac to your computer and use it in GitHub Desktop.
Save sobreira/046d472ab76f329028e386396e9dc4ac to your computer and use it in GitHub Desktop.
// #define HC_05
#ifdef HC_05
// Arduino + HC_05 altserial
#define SERIAL_BAUD 19200
#include "AltSoftSerial.h"
AltSoftSerial altSerial;
#define MySerial altSerial
#else
// BLE NANO
#define SERIAL_BAUD 19200
#define MySerial Serial
#endif
// Common Anode I have
int red_light_pin= 3;
int green_light_pin = 5;
int blue_light_pin = 6;
void RGB_color(int red_light_value, int green_light_value, int blue_light_value)
{
analogWrite(red_light_pin, red_light_value);
analogWrite(green_light_pin, green_light_value);
analogWrite(blue_light_pin, blue_light_value);
}
void setup() {
MySerial.begin(SERIAL_BAUD);
pinMode(red_light_pin, OUTPUT);
pinMode(green_light_pin, OUTPUT);
pinMode(blue_light_pin, OUTPUT);
}
enum STATE {
COMD,
RVAL,
GVAL,
BVAL
};
uint8_t currentLED[] = { 0, 0, 0 };
uint8_t RGB_CMD[3]; // Stored by SCRATCH
// command format (4byte) : 0x81, R, G, B
boolean parseCmd(int c) {
static int CURRENT_STATE = COMD;
switch (CURRENT_STATE) {
case COMD:
if ( c == 0x81 )
CURRENT_STATE = RVAL;
return false;
case RVAL:
RGB_CMD[0] = c;
CURRENT_STATE = GVAL;
return false;
case GVAL:
RGB_CMD[1] = c;
CURRENT_STATE = BVAL;
return false;
case BVAL:
RGB_CMD[2] = c;
CURRENT_STATE = COMD;
return true;
}
}
void serialEvent1() {
while (MySerial.available()) {
if ( parseCmd(MySerial.read()) ) {
currentLED[0] = RGB_CMD[0];
currentLED[1] = RGB_CMD[1];
currentLED[2] = RGB_CMD[2];
RGB_color(255-currentLED[0], 255-currentLED[1], 255-currentLED[2]);
}
}
}
void loop() {
delay(1000);
MySerial.write(currentLED, 3);
serialEvent1();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment