toggle led

i need a sample program for led to toggle, if i press a push button led must on and if i again press the same push button led must get off and wise versa. pls tel me the logic

raman00084:
i need a sample program for led to toggle, if i press a push button led must on and if i again press the same push button led must get off and wise versa. pls tel me the logic

You need to detect the time at which the switch goes from HIGH to LOW or LOW to HIGH. This is known as the the signal edge. The StateChangeDetection example demonstrates this. From there, toggling the LEDs is simple:

digitalWrite(ledPin, !digitalRead(ledPin));

@Arrch

digitalWrite(ledPin, !digitalRead(ledPin));

How does this work if the ledPin is set as an output? You make the pin an output, to set the LED on/off and then(in that same line) your going to read the pin's state without changing its mode? How does that work.

If this is true, then why bother needing pinMode, if digitalWrite sets the pin as an output and digitalRead makes it an input.

HazardsMind:
How does this work if the ledPin is set as an output? You make the pin an output, to set the LED on/off and then(in that same line) your going to read the pin's state without changing its mode? How does that work.

You're not "making the pin an output" in this line of code. You're setting the bit in PORTX to either 1 or 0. Its a memory location (I think. It's memory mapped I/O, right?), so you can read it back.

If this is true, then why bother needing pinMode, if digitalWrite sets the pin as an output and digitalRead makes it an input.

... They don't. digitalWrite sets the bit and digitalRead returns the bit. pinMode is what affects the DDRX port.

raman00084:
i need a sample program for led to toggle, if i press a push button led must on and if i again press the same push button led must get off and wise versa. pls tel me the logic

You can try something like below:

//zoomkat LED button toggle test 11-08-2012

int button = 5; //button pin, connect to ground as button
int press = 0;
boolean toggle = true;

void setup()
{
  pinMode(13, OUTPUT); //LED on pin 13
  pinMode(button, INPUT); //arduino monitor pin state
  digitalWrite(5, HIGH); //enable pullups to make pin 5 high
}

void loop()
{
  press = digitalRead(button);
  if (press == LOW)
  {
    if(toggle)
    {
      digitalWrite(13, HIGH);   // set the LED on
      toggle = !toggle;
    }
    else
    {
      digitalWrite(13, LOW);    // set the LED off
      toggle = !toggle;
    }
  }
  delay(500);  //delay for debounce
}

You're not "making the pin an output" in this line of code. You're setting the bit in PORTX to either 1 or 0. Its a memory location (I think. It's memory mapped I/O, right?), so you can read it back.

Ok, That makes more sense.