I've got a circuit with two photo interrupters, a buzzer, an Arduino Nano, and two NeoPixel LEDs. Everything is powered by a 5V power supply feeding the breadboard. When one of the photo interrupter sensors is triggered, it lights one of the LEDs and triggers the buzzer, both for the duration of the sensor interruption. This all works great.
The problem:
When the sensor is NOT triggered, I'd like each of the LEDs to run a random sequence of colors, changing color ever 300 milliseconds. When I implement this random color cycle as the default setting, it introduces an unwanted delay time in how it responds to a sensor event: when the sensor is triggered, there is a delay before it shows the sensor color and tone.
I suspect the problem has to do with the "delay(300)" code in the random color generator, but don't know how to fix it. I think the delay is temporarily blocking the code from reading the sensor input. Any ideas on how to get around this?
Here's the code:
#include <Adafruit_NeoPixel.h>
// Which pin on the Arduino is connected to the NeoPixels?
#define LED_PIN 10
// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 2
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
// Time (in milliseconds) to pause between pixels
#define DELAYVAL 500
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_C6 1047
int val_1;
int val_2;
int speakerPin = 6;
void setup() {
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)
}
void loop() {
val_1 = (analogRead(A0));
val_2 = (analogRead(A1));
if (val_1 < 100)
{
strip.setPixelColor(0, 200, 0, 200);
strip.show();
tone(speakerPin, NOTE_AS5);
delay(500);
}
else
{
strip.setPixelColor(random(0, 1), random(0, 255), random(0, 255), random(0, 255));
strip.show();
noTone(speakerPin);
delay(500);
}
if (val_2 < 100)
{
strip.setPixelColor(1, 0, 200, 200);
strip.show();
tone(speakerPin, NOTE_C6);
delay(500);
}
else
{
strip.setPixelColor(random(1, 1), random(1, 255), random(1, 255), random(1, 255));
strip.show();
noTone(speakerPin);
delay(500);
}
}