Go Down

Topic: Remember you're a button (Read 483 times) previous topic - next topic

mouldysoul

Hi,

Just having some small confusion, about how to turn an LED on with one button press and when you press the button again; turns the led off.

Instead of lighting up when held down. Surely it's something very simple!

Sorry for the extremely basic question!

tubos

Do a search for "debouncing button" to get on your way.

mouldysoul

#2
Aug 17, 2011, 09:14 pm Last Edit: Aug 17, 2011, 09:20 pm by mouldysoul Reason: 1
Thank you very very much!! :)

Erni

#3
Aug 17, 2011, 09:22 pm Last Edit: Aug 17, 2011, 09:53 pm by Erni Reason: 1
This sketch is maybe want you want, every time you push a button a LED wil turn on, and next time you push itthe LED will turn off.


There is no debouncing , and there should be

Quote

int vent=100;
const int buttonPin = 7;
int flag=0;
int buttonState = 0;   

void setup()

 pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
   pinMode(buttonPin, INPUT);
Serial.begin(9600);

 
 
void loop()

 //   digitalWrite(4, HIGH);

buttonState = digitalRead(buttonPin);
delay(vent);


  Serial.print(buttonState);
Serial.println();

   if (buttonState==HIGH){
   
     if (flag==1) {
     flag=0;
     }
     else
       {
        flag=1;
     }
  
   }

 if (flag==1){
  Serial.print("HIGH\n");
   digitalWrite(4, HIGH);

 }
 
 if (flag==0){

 digitalWrite(4, LOW);
 
  Serial.print("LOW\n");
 }





Joy

I wrote it in an easy way..
Hope this helps you.. :)

Code: [Select]
int button_pin = 11;
int led_pin = 13;
int button_state = 0;
int led_state = LOW;

void setup(){
  pinMode(button_pin, INPUT);
  pinMode(led_pin, OUTPUT);
}

void loop(){
  if(button_state == HIGH){
    led_state = !led_state;
    digitalWrite(13, led_state);
    delay(100);
  }
}

mouldysoul

Cheers for the response, really good looking code, but couldn't get the LED to come on!

dominikh


I wrote it in an easy way..
Hope this helps you.. :)


Enjoy your rapidly blinking LED. That will, as long as the button is pressed, toggle the LED every 100ms.

Go Up