Skip to content

Instantly share code, notes, and snippets.

@lassombra
Created April 1, 2023 06:40
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 lassombra/ecad5451d7104e3f839d28443d78cb8a to your computer and use it in GitHub Desktop.
Save lassombra/ecad5451d7104e3f839d28443d78cb8a to your computer and use it in GitHub Desktop.
Synchronizing arduino to Razer Chroma
#include <Arduino.h>
#define R 11
#define G 10
#define B 9
String read;
String getMessage() {
return Serial.readStringUntil('|');
}
struct RGB {
byte r;
byte g;
byte b;
bool valid = false;
};
void writeRGB(int r_v, int g_v, int b_v) {
analogWrite(R, r_v);
analogWrite(G, g_v);
analogWrite(B, b_v);
}
void writeRGB(const RGB *rgb) {
analogWrite(R, rgb->r);
analogWrite(G, rgb->g);
analogWrite(B, rgb->b);
}
bool initConnection() {
String t = getMessage();
if (t.length() > 0) {
Serial.print("2560");
return true;
}
return false;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(R, OUTPUT);
pinMode(G, OUTPUT);
pinMode(B, OUTPUT);
writeRGB(125, 0, 0);
}
const RGB parseRGB(const String& string) {
RGB rgb;
String processing = string.substring(1);
int index = processing.indexOf('-');
String part = processing.substring(0, index);
processing = processing.substring(index+1);
rgb.r = part.toInt();
index = processing.indexOf('-');
part = processing.substring(0, index);
processing = processing.substring(index+1);
rgb.g = part.toInt();
index = processing.indexOf('|');
part = processing.substring(0,index);
rgb.b = part.toInt();
rgb.valid = true;
return rgb;
}
const RGB parseRGB() {
String t = getMessage();
if (t.length() > 0) {
return parseRGB(t);
} else {
return RGB();
}
}
bool initFinshed = false;
void loop() {
if (!initFinshed) {
initFinshed = initConnection();
if (initFinshed) {
writeRGB(0, 125, 0);
}
} else {
RGB rgb = parseRGB();
if (rgb.valid) {
writeRGB(&rgb);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment