Hi, I am trying to light up some LEDs and Adafruit RGB neopixels based on serial button clicks from a p5.js sketch. I have connected the p5.js to the Arduino Uno sketch through p5.serialcontrol. The LED lights light up, so I know I am getting serial input and that it is not a problem with the p5.js. I have tested the Neopixels in an Arduino Sketch that is not reliant on serial control, so I also know it is not a problem with the circuit.
I read that there can be some problems with the RGB Neopixels and serial control due to something with timing. Does anyone have any ideas?
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif
#define PIN 2
// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS 4 // Popular NeoPixel ring size
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
int LED1 = 8; //declares a variable for an led and defines the pin it will use
int LED2 = 9; //declares a variable for an led and defines the pin it will use
int inData;
void setup() {
Serial.begin(9600); //sets the serial data communication speed
pinMode(LED1, OUTPUT); //sets pin 8 as an output pin suitable for an output pin
pinMode(LED2, OUTPUT); //sets pin 9 as an output pin suitable for an output pin
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
// END of Trinket-specific code.
pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
}
void loop() {
if (Serial.available() > 0) { // if there's serial data available do this:
pixels.setPixelColor(0, pixels.Color(0, 255, 0));
pixels.setPixelColor(1, pixels.Color(0, 255, 0));
pixels.setPixelColor(2, pixels.Color(0, 255, 0));
pixels.setPixelColor(3, pixels.Color(0, 255, 0));
pixels.show();
inData = Serial.read(); // read the serial data and put the value into a variable called inData
if (inData == '1' ){ //if the value for inData is "1" then do this:
digitalWrite(LED1,HIGH); //send power to pin 8
}
if (inData == '2' ){ //if the value for inData is "2" then do this:
digitalWrite(LED2,HIGH); //send power to pin 9
}
if (inData == '0' ){ //if the value for inData is "0" then do this:
digitalWrite(LED1,LOW); //stop sending power to pin 8
digitalWrite(LED2,LOW); //stop sending power to pin 9
}
} else {
pixels.setPixelColor(0, pixels.Color(255, 0, 0));
pixels.setPixelColor(1, pixels.Color(255, 0, 0));
pixels.setPixelColor(2, pixels.Color(255, 0, 0));
pixels.setPixelColor(3, pixels.Color(255, 0, 0));
}
}