Launchpad parpadea con el botón

Estoy tratando de hacer que el LED en MSP430G2 Launchpad siga parpadeando/apagado con un botón como el ejemplo de Switch ( http://www.arduino.cc/en/Tutorial/Switch ) en Arduino/Energia pero parece que me pierdo algo estúpido y no lo hago no se que...

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;
}

Parpadea una vez cuando presiono el botón. yo se que esto

digitalWrite(ledPin, HIGH);

o parte del estado se estropea. ¿Alguna ayuda? Gracias.

Su declaración else no incluye nada más allá de la línea debajo de ella sin corchetes.
Arreglé Else pero todavía parpadea una vez.
¿Dónde está el bucle?
Traté de poner un parpadeo en bucle, pero no sé cómo leer el botón dentro del bucle o qué escribir como condición de bucle.
Oh, leyendo esto de nuevo, no quieres que parpadee solo una vez, ¿quieres que siga parpadeando hasta que vuelvas a pulsar el botón? Luego intente combinar arduino.cc/en/Tutorial/BlinkWithoutDelay con el tutorial Switch, tal vez con un ciclo while o for.
Porque en este momento, su código funciona exactamente como se supone que debe hacerlo. Si el botón sube después de que hayan pasado 200 ms (0,2 s) desde la última vez que subió, entrará en la instrucción if. La primera vez, el led permanecerá apagado (Estado = ALTO al comienzo de su código). La segunda vez se encenderá, espere 0,1 s, apague, espere 0,1 s y luego encienda. La tercera vez, apagará el led. Y se repite desde la segunda vez (Presionar botón, Parpadeo 1, Permanecer encendido, Presionar botón, Apagar, etc. etc.)

Respuestas (2)

¿Es esto lo que estás tratando de lograr?

  • Presionar y soltar => El LED comienza a parpadear
  • Presionar y soltar => El LED se apaga
  • Etcétera ..

Cambié ligeramente su código para lograr eso. Definí una bandera 'parpadeo' que le dice a la rutina de parpadeo más abajo que parpadee el LED o que lo apague.

const int buttonPin = PUSH2;     // the number of the pushbutton pin
const int ledPin =  GREEN_LED;   // the number of the LED pin

boolean state = HIGH;      // the current state of the output pin
boolean blink = LOW;       // the current mode of the LED either blinking (HIGH) or off (LOW)
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 ) ) {
    blink = !blink;  // invert the current value for the blink flag
    time = millis();    
  }


  // if blink flag is HIGH then turn on and off the LED
  // if blink flag is LOW then turn off the LED
  if ( blink == HIGH ) {
    digitalWrite(ledPin, state);
    state = !state;   // invert the current state (LOW to HIGH and HIGH to LOW)
    delay(100);
  } else {
    digitalWrite(ledPin, LOW);
  }
  previous = reading;
}

La desventaja de este código es que el ciclo funciona lento debido a la demora mientras parpadea. El bucle intermitente se puede mejorar para ese comportamiento, pero introduce un mecanismo un poco más complejo:

  if ( blink == HIGH ) {
    state = ( millis() >> 8 ) & 1;
    digitalWrite(ledPin, state);
  } else {
    digitalWrite(ledPin, LOW);
  }

Aquí, el retraso se reemplaza haciendo que el estado dependa de la cantidad de milisegundos desde el inicio, dividido por 256 y verificando el bit menos significativo.

Probado en Energia con un Stellaris LaunchPad.
Solo como una nota para OP, este código es tan simple que no hay diferencia en usarlo en un MSP430G2xxx Launchpad o Stellaris LaunchPad.
¡Gracias! Eso era lo que estaba tratando de hacer, pero el bucle mejorado no funciona para mí.
@Cagurtay Tienes razón, tuve una versión anterior del bucle mejorado copiado por accidente. La línea mejorada correcta debería decirstate = (millis() >> 8 ) & 1;

Else necesita un corchete de apertura.

demás {

(Error ya corregido por OP y Pregunta, pero también debido a una interpretación diferente de cuáles son las intenciones vagas de OP (el código no funciona como está escrito frente al código que no funciona según lo previsto))

Bah... Pero todavía parpadea una vez.