Dual Purpose button issue...

I can't seem to get my code to work. I want to use a single button to turn an led on when pressed, have it stay on, then turn it off when it is pressed again. The code I'm using is this:

//define my input and outputs
int led = 7;
int buttonPin = 2;

void setup() {
  //set the function of my button and led pins
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(led, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  //detect the output state of the led pin
  int state = digitalRead(7);
  //if the led is off and the button is pressed,
  //turn the led on
  if (state == LOW && digitalRead(buttonPin) == LOW){
   digitalWrite(led, HIGH);
}
//if the led is on and the button is pressed,
//turn the led off
 else if (state == HIGH && digitalRead(buttonPin) == LOW){
    digitalWrite(led, LOW);
  }
}

What I'm getting is partial success. Sometimes it acts like a momentary switch, turning back off when the button is released. Sometimes when the button is released it goes to a higher output state and the led gets brighter. I don't see a problem with my syntax, and I don't see a problem with my logic either...

Look at the debounce example in the IDE for some hints how to do this.

See https://www.arduino.cc/en/Tutorial/Debounce

I would do something such as

//define my input and outputs
int led = 7;
int buttonPin = 2;
int lightStatus = 0;

void setup() {
  //set the function of my button and led pins
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(led, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  //detect the output state of the led pin
  int state = digitalRead(7);
  //if the led is off and the button is pressed,
  //turn the led on
  if (lightStatus == 0 && state == LOW && digitalRead(buttonPin) == LOW){
   digitalWrite(led, HIGH);
   lightStatus = 1;
}
//if the led is on and the button is pressed,
//turn the led off
 else if (lightStatus == 1 && state == HIGH && digitalRead(buttonPin) == LOW){
    digitalWrite(led, LOW);
  }
}

But I haven't learned the "debounce" method larryd mentioned. Might be better than mine in the long run.

Headed over there right now larryd! :)

EDIT: Shoot yeah! I'm new to the arduino. Had not read up on debounce even though I had seen it mentioned a few times here on the forums. That looks like the way to go! Will free up some script space for certain.

Excuse me ..... Have some code to rewrite!