Skip to content

Instantly share code, notes, and snippets.

@shfitz
Created April 12, 2020 19:59
Show Gist options
  • Save shfitz/075938de7ca887f640d8fbc9186316bc to your computer and use it in GitHub Desktop.
Save shfitz/075938de7ca887f640d8fbc9186316bc to your computer and use it in GitHub Desktop.
// include the neopixel library
#include <Adafruit_NeoPixel.h>
int ledPin = 3; // the pin the LED data line is connected to
int numLED = 5; // number of LEDs you are controlling
// call the constructor for the neopixels
Adafruit_NeoPixel leds(numLED, ledPin, NEO_GRB + NEO_KHZ800);
int input[] = {0, 0, 0}; // an array to hold color data
String inputString = ""; // a String to hold incoming data
bool stringComplete = false; // whether the string is complete
void setup() {
// start serial
Serial.begin(9600);
// start communication with the LEDs
leds.begin();
// it's necessary to call show() to write the values to the lights
// in this case, right after begin(), it just insures that they are all off
leds.show();
// reserve memory for the inputString:
inputString.reserve(50);
establishContact(); // make sure we're communicating
delay(16); // small delay
}
void loop() {
// while there's data available
while (Serial.available()) {
// get the new byte and store it
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline,
// set a flag so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
inputString.trim(); // trim off any whitespace
}
}
// if we have a valid string
if (stringComplete) {
// parse the data and save it into an array
int maxIndex = inputString.length() - 1; // get the number of elements
int index = 0;
int next_index;
String value;
int counter = 0;
do {
// this chunk of code parses a string with comma-separated values
// and adds the values to an array
next_index = inputString.indexOf(',', index); // find the next comma
value = inputString.substring(index, next_index); //get the next number
value.trim(); // trim any whitespace
input[counter] = value.toInt(); // convert to an int and store in the array
index = next_index + 1; // this shifts to find the next value
counter++; // increment the array
} while ((next_index != -1) && (next_index < maxIndex)); // do the above while we have a string
unsigned long stripcolor = leds.Color(input[0], input[1], input[2]); // use the values to make a color
leds.fill(stripcolor); // fill the strip witht he color and display it
leds.show();
inputString = ""; // clear the string for more information
stringComplete = false; // get ready for another new set of information
Serial.print('A'); // ask for more
}
}
void establishContact() {
while (Serial.available() <= 0) {
Serial.print('A'); // send an initial string
delay(300);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment