Go Down

Topic: How to make a led light stay on when press switch (Read 52276 times) previous topic - next topic

jinhui93

I wanted to make an LED come on when you press a button and stay on, then once you press the button again it goes off and stays off until you press the button again. I've tried the BUTTON tutorial in the tutorial page. However once i let go of my finger the led light goes off already.
I need to do one that can stays on when i let go of my hand.

This is the code i'm trying now but it doesn't work:

Code: [Select]
/* switch
*
* Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
* press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
* a minimum delay between toggles to debounce the circuit (i.e. to ignore
* noise). 
*
* David A. Mellis
* 21 November 2006
*/

int inPin = 2;         // the number of the input pin
int outPin = 13;       // the number of the output 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(inPin, INPUT);
  pinMode(outPin, OUTPUT);
}

void loop()
{
  reading = digitalRead(inPin);

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

    time = millis();   
  }

  digitalWrite(outPin, state);

  previous = reading;
}


i think it is something wrong with my inputs but i have no idea which one is it because the picture is too blur.
I hope someone can help!
Thanks!

larryd

Turn on the pull-up resistor on pin 2  with:
pinMode(inPin, INPUT_PULLUP);

Or, add an external 10K resistor between pin 2 and +5V.
No technical PMs.
If you are asked a question, please respond with an answer.
If you are asked for more information, please supply it.
If you need clarification, ask for help.


Vaclav


Turn on the pull-up resistor on pin 2  with:
pinMode(inPin, INPUT_PULLUP);

Or, add an external 10K resistor between pin 2 and +5V.


KISS - you have internal pullup resistor - USE it.

donwinchell

For those of you who know how to do this, this must be getting very boring. But after many hours and not finding a simple way to do this, I finally figured it out (again). Here is another version for; flip-flop, push button stay-on/stay-off Arduino sketch. wiring is in the code. It uses a function approach so you should be able to use it in different sketches. 
Code: [Select]


// Using a push button switch for stay-on/stay-off push button .
// beating a dead horse, again. Most of the real work is from other people.


int switch1 = 12; // connect a push button switch between this pin and ground
int ledpin = 13; // internal led, external LED, relay, trigger for other function, some other device, whatever.
boolean flag = true;

void setup()
{
  pinMode(ledpin,OUTPUT); // this pin controlled by flipflop() function
  pinMode (switch1,INPUT_PULLUP); // keeps pin HIGH via internal pullup resistor unless brought LOW with switch
  Serial.begin(9600); // just for debugging, not needed.
}

void loop()
{
  if (digitalRead(switch1)==LOW){ // check the state of switch1 every time we run through the main loop 
  delay(5); // I don't REALLY know why this delay helps, but it does.
      flipflop(); // hops out of main loop and runs the flipflop function
  }// end of check for button press.

  // other sketch code here

} // end of main loop.

void flipflop(){  //funtion flipflop
  flag = !flag;  // since we are here, the switch was pressed So FLIP the boolian "flag" state (we don't even care if switch was released yet)
  Serial.print("flag =   " );   Serial.println(flag);   // not needed, but may help to see what's happening.

  if (flag == HIGH){  // Use the value of the flag var to change the state of the pin
    digitalWrite(ledpin,HIGH ); // if the flag var is HIGH turn the pin on
  }
  if (flag == LOW) {
    digitalWrite(ledpin,LOW); // if the flag var is LOW turn the pin off
  }
  while(digitalRead(switch1)==LOW); // for "slow" button release, keeps us in the function until button is UN-pressed
  // If you take out this "while" the function becomes a flipflop oscillator if the button is held down.
  delay(50); // OPTIONAL - play with this value.  It is probably short enough to not cause problems. deals with very quick switch press.
}


35kkk93

For those of you who know how to do this, this must be getting very boring. But after many hours and not finding a simple way to do this, I finally figured it out (again). Here is another version for; flip-flop, push button stay-on/stay-off Arduino sketch. wiring is in the code. It uses a function approach so you should be able to use it in different sketches. 
Code: [Select]


// Using a push button switch for stay-on/stay-off push button .
// beating a dead horse, again. Most of the real work is from other people.


int switch1 = 12; // connect a push button switch between this pin and ground
int ledpin = 13; // internal led, external LED, relay, trigger for other function, some other device, whatever.
boolean flag = true;

void setup()
{
  pinMode(ledpin,OUTPUT); // this pin controlled by flipflop() function
  pinMode (switch1,INPUT_PULLUP); // keeps pin HIGH via internal pullup resistor unless brought LOW with switch
  Serial.begin(9600); // just for debugging, not needed.
}

void loop()
{
  if (digitalRead(switch1)==LOW){ // check the state of switch1 every time we run through the main loop 
  delay(5); // I don't REALLY know why this delay helps, but it does.
      flipflop(); // hops out of main loop and runs the flipflop function
  }// end of check for button press.

  // other sketch code here

} // end of main loop.

void flipflop(){  //funtion flipflop
  flag = !flag;  // since we are here, the switch was pressed So FLIP the boolian "flag" state (we don't even care if switch was released yet)
  Serial.print("flag =   " );   Serial.println(flag);   // not needed, but may help to see what's happening.

  if (flag == HIGH){  // Use the value of the flag var to change the state of the pin
    digitalWrite(ledpin,HIGH ); // if the flag var is HIGH turn the pin on
  }
  if (flag == LOW) {
    digitalWrite(ledpin,LOW); // if the flag var is LOW turn the pin off
  }
  while(digitalRead(switch1)==LOW); // for "slow" button release, keeps us in the function until button is UN-pressed
  // If you take out this "while" the function becomes a flipflop oscillator if the button is held down.
  delay(50); // OPTIONAL - play with this value.  It is probably short enough to not cause problems. deals with very quick switch press.
}


dear donwinchell,

many thanks for yr explanation above. guess the delay function in the void loop, is to protect the reading value against bouncing effect. do u agree?

falsagoff

I was trying to do the same thing. I know this thread is quite old but for anyone else just like me who happened to read this thread ..  the following may help.

1) The problem is due to a phenomenon called contact bounce. You probably faced the same problem as I did; the button sometimes works and sometimes it does not.

2) Checkout http://blog.kennyrasschaert.be/blog/2014/04/01/digital-input-on-an-arduino-using-a-push-button/  for a full explanation. It is not my blog but the guy explained it very well. Thank you Kenny.

3) Checkout the example on your Arduino IDE called Debounce under Digital.


Achintya

Instead of using pull up resistors or complicating the code, try using this-

digitalWrite(pin_number, !(digitalRead(pin_number));

This is exactly what the flipflop function you made does.

Redloup

i would like to know how to push a button to start a loop that goes for a certain time and then stops till you push the button again?

Wawa

i would like to know how to push a button to start a loop that goes for a certain time and then stops till you push the button again?
I see you have already created a thread for this.
Not a great idea to spread the same problem across several threads.
This made me delete a post I made here.
Leo..


myflightdeck

#11
Oct 23, 2018, 08:58 pm Last Edit: Oct 23, 2018, 08:59 pm by myflightdeck
Can someone explain how I can add multiple switches and LED's using the code below?  Maybe post an example of the code. I need to use this on 13 momentary switches that have LED's associated with them when they are pushed.





For those of you who know how to do this, this must be getting very boring. But after many hours and not finding a simple way to do this, I finally figured it out (again). Here is another version for; flip-flop, push button stay-on/stay-off Arduino sketch. wiring is in the code. It uses a function approach so you should be able to use it in different sketches. 
Code: [Select]


// Using a push button switch for stay-on/stay-off push button .
// beating a dead horse, again. Most of the real work is from other people.


int switch1 = 12; // connect a push button switch between this pin and ground
int ledpin = 13; // internal led, external LED, relay, trigger for other function, some other device, whatever.
boolean flag = true;

void setup()
{
  pinMode(ledpin,OUTPUT); // this pin controlled by flipflop() function
  pinMode (switch1,INPUT_PULLUP); // keeps pin HIGH via internal pullup resistor unless brought LOW with switch
  Serial.begin(9600); // just for debugging, not needed.
}

void loop()
{
  if (digitalRead(switch1)==LOW){ // check the state of switch1 every time we run through the main loop 
  delay(5); // I don't REALLY know why this delay helps, but it does.
      flipflop(); // hops out of main loop and runs the flipflop function
  }// end of check for button press.

  // other sketch code here

} // end of main loop.

void flipflop(){  //funtion flipflop
  flag = !flag;  // since we are here, the switch was pressed So FLIP the boolian "flag" state (we don't even care if switch was released yet)
  Serial.print("flag =   " );   Serial.println(flag);   // not needed, but may help to see what's happening.

  if (flag == HIGH){  // Use the value of the flag var to change the state of the pin
    digitalWrite(ledpin,HIGH ); // if the flag var is HIGH turn the pin on
  }
  if (flag == LOW) {
    digitalWrite(ledpin,LOW); // if the flag var is LOW turn the pin off
  }
  while(digitalRead(switch1)==LOW); // for "slow" button release, keeps us in the function until button is UN-pressed
  // If you take out this "while" the function becomes a flipflop oscillator if the button is held down.
  delay(50); // OPTIONAL - play with this value.  It is probably short enough to not cause problems. deals with very quick switch press.
}



Grumpy_Mike

Quote
Can someone explain how I can add multiple switches and LED's using the code below?
FFS this thread started in 2013.
Please read this:-
How to use this forum

Paul__B

OK, here's some baseline code:
Code: [Select]

//Radio Buttons 22

const int redledPin = 11;   //LED Pin #
const int greenledPin = 13;
const int redbutton = 2;    //button Pin #
const int greenbutton = 3;

char redbuttonstate = 0;
char greenbuttonstate = 0;

unsigned long redbuttoncount = 0;  //button debounce timer
unsigned long greenbuttoncount = 0;

//"marker" chooses which counter to check
// by Paul___B of Arduino Forum

boolean timeout(unsigned long *marker, unsigned long interval) {
  if (millis() - *marker >= interval) {
    *marker += interval;    //move on ready for next interval
    return true;
  }
  else return false;
}

//Deal with a button read; true if button pressed and debounce is a new event
//Uses reading of button input, debounce store, state store and debounce interval.
//by Paul___B of Arduino Forum
boolean buttondown(char button, unsigned long *marker, char *buttonstate, unsigned long interval) {
  switch (*buttonstate) {                                 //odd states if was presses, >= 2 if debounce in progress
    case 0: //button up so far,
      if (button == HIGH) return false;                     //nothing happening!
      else {
        *buttonstate = 2;                                   // record that is now pressed
        *marker = millis();                                 // note when was pressed
        return false;                                       //and move on
      }

    case 1:   //button down so far,
      if (button == LOW) return false;               // noting happening!
      *buttonstate = 3;                              //record that is now released
      *marker = millis();                            //note when was released
      return false;                                  // and move on

    case 2:                                        //button was up, now down.
      if (button == HIGH) {
        *buttonstate = 0;                          // jackpot! update the state
        return true;                              //because we have the desired event!
      }
      else
        return false;                                    //not done yet; just move on

    case 3: // button was down mow up
      if (button == LOW) {
        *buttonstate = 1;                               //no, not debounced; revert the state
        return false;                                   // false alarm!
      }
      else {
        if (millis() - *marker >= interval) {
          *buttonstate = 0;                             //debounced; update state
          return false;                                 // but not the event we want
        }
        else
          return false;                                   //not done yet; just move on
      }
    default:                                        //error; recover anyway
      {
        *buttonstate = 0;
        return false;                                  // definitly false!

      }
  }
}

void setup() {
  pinMode(redledPin, OUTPUT);
  pinMode(greenledPin, OUTPUT);
  pinMode(redbutton, INPUT);
  pinMode(greenbutton, INPUT);
  digitalWrite (redledPin, LOW);
  digitalWrite (greenledPin, LOW);

  pinMode(redbutton, INPUT);
  digitalWrite(redbutton, HIGH);      //enable pullup resistor

  pinMode(greenbutton, INPUT);
  digitalWrite(greenbutton, HIGH);    //enable pullup resistor
}

void loop() {
  // Toggle LED if button is debounced
  if (buttondown(digitalRead(redbutton), &redbuttoncount, &redbuttonstate, 10UL )) {
    if (digitalRead(redledPin))
      digitalWrite (redledPin, LOW); else
      digitalWrite (redledPin, HIGH);
  }

  // Toggle LED if button is debounced
  if (buttondown(digitalRead(greenbutton), &greenbuttoncount, &greenbuttonstate, 10UL )) {
    if (digitalRead(greenledPin))
      digitalWrite (greenledPin, LOW); else
      digitalWrite (greenledPin, HIGH);
  }
}

So what do you do with it for 13 buttons?

Well, take everything that refers to "redled" or "redbutton" and make copies of it with another "led" and "button" name or number such as "led3" and "button3" (if you run out of colours).  But for 13 of them you are going to run out of pins first unless you use a mega2560.  There are however ways of fixing that using shift registers.

Go Up