I am using interrupts in my Arduino project to switch between modes on an LED piece I'm working on.
The issue is, while the interrupt is working and my mode number is incrementing, my switch / case isn't switching until the current function / loop ends.
This means that if I have a function that cycles through a ton of colors slowly and I press my mode button, nothing happens until all cycles are done.
Here is my code.
Thanks.
Phil
#include "LPD8806.h"
#include "SPI.h"
int dataPin = 5;
int clockPin = 4;
int mode = 0;
LPD8806 strip = LPD8806(28, dataPin, clockPin);
void setup() {
strip.begin();
strip.show();
pinMode(2, INPUT_PULLUP);
attachInterrupt(0, deBounce, LOW);
Serial.begin(9600);
}
void loop() {
switch (mode) {
case 0:
colorChase(strip.Color(127,127,127), 10);
break;
case 1:
rainbowCycle(100);
break;
case 2:
colorWipe(strip.Color(127,0,0), 10);
colorWipe(strip.Color(0,127,0), 10);
colorWipe(strip.Color(0,0,127), 10); // red
break;
} // case
} // loop
void rainbowCycle(uint8_t wait) {
uint16_t i, j;
for (j=0; j < 384 * 5; j++) { // 5 cycles of all 384 colors in the wheel
for (i=0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, Wheel( ((i * 384 / strip.numPixels()) + j) % 384) );
}
strip.show();
}
}
void colorWipe(uint32_t c, uint8_t wait) {
int i;
for (i=0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, c);
strip.show();
delay(wait);
}
}
void colorChase(uint32_t c, uint8_t wait) {
int i;
for (i=0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, 0); // turn all pixels off
}
for (i=0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, c);
if (i == 0) {
strip.setPixelColor(strip.numPixels()-1, 0);
} else {
strip.setPixelColor(i-1, 0);
}
strip.show();
delay(wait);
}
}
/* Helper functions */
//Input a value 0 to 384 to get a color value.
//The colours are a transition r - g -b - back to r
uint32_t Wheel(uint16_t WheelPos)
{
byte r, g, b;
switch(WheelPos / 128)
{
case 0:
r = 127 - WheelPos % 128; //Red down
g = WheelPos % 128; // Green up
b = 0; //blue off
break;
case 1:
g = 127 - WheelPos % 128; //green down
b = WheelPos % 128; //blue up
r = 0; //red off
break;
case 2:
b = 127 - WheelPos % 128; //blue down
r = WheelPos % 128; //red up
g = 0; //green off
break;
}
return(strip.Color(r,g,b));
}
void buttonPressed()
{
mode = (mode + 1) %3;
Serial.println(mode);
}
void deBounce()
{
static unsigned long last_interrupt_time = 0;
unsigned long interrupt_time = millis();
// If interrupts come faster than 200ms, assume it's a bounce and ignore
if (interrupt_time - last_interrupt_time > 200)
{
buttonPressed();
}
last_interrupt_time = interrupt_time;
}