Hello programming gurus!
I am and extreme novice, and I have been struggling with a button press behavior. What I am trying to accomplish seems simple to me, but the logic just isn't working the way I expect. When I press my button I want a certain set of LEDs to come on, and stay on. When pressed again, to revert to the starting set of LEDs. The behavior that it exhibits is I have my starting LEDs on, when I press the button it changes to the other set, and changes back when I release the button. I tried a number of different methods for saving the state of the button press to no avail. This is a stepping stone to adding a fade-in effect, but I can't get the button to work the way I expect. I have changed where the lastButtonState variable sits in the brackets to no avail. I'm sure this is something very simple to an experienced programmer, but I'm just learning at this point. Below if the Code:
// Used to control the warp and impulse engines
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int warpredPin = 6; // the number of the LED pin
const int warpbluePin = 5;
const int impulseredPin = 11;
const int impulsegreenPin = 10;
// Variables will change:
int ledState = HIGH; // the current state of the output pin
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
void setup() {
// initialize the LED pin as an output:
pinMode(warpredPin, OUTPUT);
pinMode(warpbluePin, OUTPUT);
pinMode(impulseredPin, OUTPUT);
pinMode(impulsegreenPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
//digitalWrite(warpbluePin, HIGH);
//digitalWrite(warpredPin, LOW);
//digitalWrite(impulseredPin, LOW);
//digitalWrite(impulsegreenPin, HIGH);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
//compare the buttonState to its previous state
if (buttonState != lastButtonState){
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(warpredPin, HIGH);
digitalWrite(warpbluePin, LOW);
digitalWrite(impulsegreenPin, LOW);
digitalWrite(impulseredPin, HIGH);
}
else {
// turn LED off:
digitalWrite(warpbluePin, HIGH);
digitalWrite(warpredPin, LOW);
digitalWrite(impulsegreenPin, HIGH);
digitalWrite(impulseredPin, LOW);
}
}
// save the current state as the last state
// for the next time through the loop
lastButtonState = buttonState;
}
Thanks in advance for the help!