I have a project with some NeoPixels and other LEDs and an Arduino UNO.
Once switched on, the defaultLEDAnimation
with colors and blinking, etc. starts.
I want to trigger some other animations, so I connected two buttons to the Arduino. Whenever you press button1
, the Arduino should stop everything it is doing and run animation1
. The same goes for button2
. if you press it, the Arduino should run animation2
. All animations are quite complex and run for several seconds and even minutes.
Now for the challenge: How do I use the two buttons to immediately stop every animation happening and display the appropriate animation?
The tried using interrupts and connected the two buttons to pin 2 and 3. However, when I press the buttons, the animation starts after several seconds delay. Is there any way to restart the loop function immediately after the interrupt has been made? Or is there another way to trigger my animations with those two buttons?
The code looks something like this:
#define button1 2
#define button2 3
volatile bool shouldPerformButton1Action = false;
volatile bool shouldPerformButton2Action = false;
void setup() {
attachInterrupt(digitalPinToInterrupt(button1), button1Pressed, RISING);
attachInterrupt(digitalPinToInterrupt(button2), button2Pressed, RISING);
}
void loop() {
if (shouldPerformButton1Action) {
doAnimation1();
shouldPerformButton1Action = false;
} else if (shouldPerformButton2Action) {
doAnimation2();
shouldPerformButton2Action = false;
} else {
runDefaultAnimation();
}
}
void button1Pressed() {
shouldPerformButton1Action = true;
}
void button2Pressed() {
shouldPerformbutton2Action = true;
}
void doAnimation1() {
for(int i=0; i<10; i++){
neoPixelStrip.setPixelColor(neoPixelArray[i], neoPixelStrip.Color(255, 0, 0, 255));
neoPixelStrip.show();
delay(100);
}
delay(1000);
for(int i=0; i<10; i++){
neoPixelStrip.setPixelColor(neoPixelArray[i], neoPixelStrip.Color(0, 0, 0, 0));
neoPixelStrip.show();
delay(100);
}
}
The function doAnimation1
is just an example. It will be much more complex.
longjmp()
directly from the ISR to the main loop.