Go Down

Topic: Better Arduino Switch Example (Read 832 times) previous topic - next topic

tvhargon

I wrote a better toggle button script, as featured in the Switch Example. In the example page, if you press the button twice within 200ms, it won't read the second press. With the script below, you can press it as quickly as you want and it will toggle properly.

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
*
* Modified by Alex J. Humphreys
* 20 September 2010
*/

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
int beingPressed = LOW;  // checks to see if the button is held down


void setup()
{
 pinMode(inPin, INPUT);
 pinMode(outPin, OUTPUT);
}

void loop()
{
 reading = digitalRead(inPin);
 
 if(reading == HIGH && state == LOW && beingPressed == LOW){
   beingPressed = HIGH;
 state = HIGH;
 }
 
 if(reading == HIGH && state == HIGH && beingPressed == LOW){
  beingPressed = HIGH;
  state = LOW;
 }
 if (reading == LOW && beingPressed == HIGH){
 beingPressed = LOW;
 }
 
 
 
 digitalWrite(outPin, state);
 }


Groove

Why is "reading" a global?
You only ever use it inside "loop()".

"inPin" and "outPin" should have "const" qualifiers.
Per Arduino ad Astra

tvhargon

Because that's how it was in the example, and I decided to leave it.

westfw

So how does this example handle switch bounce?  As far as I can tell, a bouncing switch will look exactly the same as "pushing the button very fast", so any bounce will end up looking like a random number of pushes...  You MUST have some sort of time constant in there to prevent bounce.  (200ms may be too much.)

tvhargon

*learns what bounce means*

good point

Andy R

Mellis's code is better, because it debounces. Though adding 'counts' or double click functionality is a good idea.

Go Up