I have been using a library to control a LED Strip with buttons. My current code does not execute properly. It skips the if statement and just runs the code in a loop with no regard to the button and I'm uncertain why. I'm using an Arduino Uno with an LPD8806.
#include "LPD8806.h"
#include "SPI.h" // Comment out this line if using Trinket or Gemma
#ifdef __AVR_ATtiny85__
#include <avr/power.h>
#endif
int nLEDs = 160;
// Chose 2 pins for output; can be any valid output pins:
int dataPin = 2;
int clockPin = 3;
// First parameter is the number of LEDs in the strand. The LED strips
// are 32 LEDs per meter but you can extend or cut the strip. Next two
// parameters are SPI data and clock pins:
LPD8806 strip = LPD8806(nLEDs, dataPin, clockPin);
int inPin = 4;
boolean lastState = LOW;//storage for last button state
void setup(){
pinMode(inPin, INPUT);//this time we will set the pin as INPUT
Serial.begin(9600);//initialize Serial connection
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
#endif
strip.begin();
// Update the strip, to start they are all 'off'
strip.show();
}
void loop(){
if (digitalRead(inPin) == HIGH && lastState == LOW){//if button has just
been pressed
// Start up the LED strip
theaterChase(strip.Color(127, 127, 127), 50); // White
delay(100);
} else if(digitalRead(inPin) == LOW && lastState == HIGH){
digitalWrite(dataPin, LOW);
digitalWrite(clockPin, LOW);
}
lastState = digitalRead(inPin);
}
//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
for (int j=0; j<10; j++) { //do 10 cycles of chasing
for (int q=0; q < 3; q++) {
for (int i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, c); //turn every third pixel on
}
strip.show();
delay(wait);
for (int i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, 0); //turn every third pixel off
}
}
}
}
1 Answer 1
If you have just connected a switch to the Arduino pin, like the image below, it will just return "random" undefined results:
There are various ways of avoiding this, including using a pull-down resistor to ensure that, if the switch is open, it will read LOW. For example:
There are other possible techniques as discussed on this page.
One is to change:
pinMode(inPin, INPUT);//this time we will set the pin as INPUT
to:
pinMode(inPin, INPUT_PULLUP);//this time we will set the pin as INPUT
Then wire the switch to ground, not +5 V. That way the pull-up resistor pulls the switch HIGH, and when you close the switch it is LOW.
theatherChase()
function insideloop()
, where it should be before or after.