I am trying to make LED in MSP430G2 Launchpad keep blinking / off with button like Switch example (http://www.arduino.cc/en/Tutorial/Switch) in Arduino/Energia but I seem to miss something stupid and i don't know what…
const int buttonPin = PUSH2; // the number of the pushbutton pin
const int ledPin = GREEN_LED; // the number of the LED pin
int state = HIGH; // the current state of the output pin
int reading; // the current reading from the input pin
int previous = LOW; // the previous reading from the input pin
// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0; // the last time the output pin was toggled
long debounce = 200; // the debounce time, increase if the output flickers
void setup()
{
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop()
{
reading = digitalRead(buttonPin);
// if the input just went from LOW and HIGH and we've waited long enough
// to ignore any noise on the circuit, toggle the output pin and remember
// the time
if (reading == HIGH && previous == LOW && millis() - time > debounce) {
if (state == HIGH){
state = LOW;
}
else {
state = HIGH;
digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
delay(100);
}
time = millis();
}
digitalWrite(ledPin, state);
previous = reading;
}
It blinks once when i press the button.
I know that this
digitalWrite(ledPin, HIGH);
or state part messes up.
Any help?
Thank you.
Best Answer
Is this what you are trying to accomplish?
I slightly changed your code to accomplish that. I defined a flag 'blink' that tells the blink routine further down either to blink the LED or to turn it off.
The disadvantage of this code is that the loop runs slow due to the delay while blinking. The blinker loop can be improved for that behavior, but it introduces a slightly more complex mechanism:
Here the delay is replaced by making state depend on the number of milliseconds since start, divided by 256 and checking the least significant bit.