[SOLVED] First sketch -- Push button Blinking LED -- Debouncing help!


hello everyone,

i got first arduino on friday, , i've had lot of fun blinking led in s.o.s. patterns , adding switch.  

i wrote first sketch blinks led on , off when press button, , turns off when press again.  my trouble implementing proper debounce accurate read button.  below code.  any advice appreciated.  thanks!  

code: [select]

int switchpin = 8;
int ledpin =  3;      
int ledstate = low;            
long previousmillis = 0;                  
boolean lastbutton = low;  // tracks button presses

void setup()
{
 pinmode(ledpin, output);
 pinmode(switchpin, input);  
}

void loop()
{
 if (digitalread(switchpin) == high && lastbutton == low) // if button pressed change last button value
 {
   lastbutton = high;
 }
 if (digitalread(switchpin) == high && lastbutton == high) // if button pressed change last button value
 {
  lastbutton = low;
 }
 if (lastbutton == high)  // if button "on" blink led
 {
   unsigned long currentmillis = millis();
   if(currentmillis - previousmillis > 250)  // defines veriable going true false every quarter second
   {
     previousmillis = currentmillis;  
     if (ledstate == low)  
     {
       ledstate = high;
     }
     else
     {
     ledstate = low;
     }
   }
   digitalwrite(ledpin, ledstate);
 }
 if (lastbutton == low)  // if button "off" turn led off
 {
   digitalwrite(ledpin, low);
 }
}

the cheap , cheerful 'debounce' algorithm commonly used put fixed delay after notice switch change, before try reading again.

a more sophisticated algorithm poll switch until has remained in same state defined period sure has settled before act on change. takes more code , more testing, though, , overkill applications.


Arduino Forum > Using Arduino > Project Guidance > [SOLVED] First sketch -- Push button Blinking LED -- Debouncing help!


arduino

Comments

Popular posts from this blog

Thread: PKI Client 5.00 install (for eToken Pro)

ATmega2560-Arduino Pin Mapping

Crossfader Arduino Tutorial