Go Down

Topic: Hi guys need some help with SwitchDebounce and StateChangedetection (Read 571 times) previous topic - next topic

LarryD

The way you have it in your schematic isn't the same as how you have it wired up!

ash901226

@PaulS:
I thought that since the nature of digitalRead() return value is between HIGH and LOW, I could use boolean.
now i know better.

@Arrch:

Code: [Select]

  if (millis()-LastDebounceTime>=10UL)
  {
    if (digitalRead(Switch) ==LOW)
    {
      LedState = !LedState;
    }
  }


Keep in mind that first if statement won't just run once. Once the switch has been LOW for more than 10 ms, it will run over and over again, toggling the LED state each iteration.


yes when you say about it, i realize that my understanding towards the program is totally false.

ash901226

Guys I got this to work, and interestingly the first time around it work only that i have press the switch twice to make it work.

Code: [Select]

uint8_t Switch = 2;
uint8_t Led =13;

boolean LedState =LOW;
int SwitchState =0;
int SwitchDebounce;
int LastSwitchState=HIGH;
int LastSwitchDebounce=LOW;

unsigned long LastDebounceTime = 0;
unsigned long DebounceDelay = 50;

void setup()
{
  pinMode(Switch,INPUT);
  digitalWrite(Switch,HIGH);
  pinMode(Led,OUTPUT);
}

void loop()
{
  int CurrentSwitch = digitalRead(Switch);
  if (CurrentSwitch != LastSwitchDebounce)
  {
    LastDebounceTime = millis();
  }
  if ((millis() - LastDebounceTime) > DebounceDelay)
  {
    SwitchDebounce = CurrentSwitch;
    SwitchState = digitalRead(Switch);
    if (SwitchState != LastSwitchState)
    {
      if (SwitchState == LOW)
      {
        LedState = !LedState;
      }
    }
    LastSwitchState=SwitchState;
  }
  digitalWrite(Led,LedState);
  LastSwitchDebounce = CurrentSwitch;
}

Hope you guys could give me some other pointer that i could use to make it more efficient?

i Saw some of the reply saying i could use a library. yes i have Debounce and Bounce library but by using the library i fail to understand how it work only that i know that it work. nothing more then some educational purpose.


HazardsMind

#8
Jan 22, 2013, 10:13 pm Last Edit: Jan 22, 2013, 10:20 pm by HazardsMind Reason: 1
Quote
I was trying to merge both the program together and i came out with this

Hint: Instead of "if (digitalRead(Switch) == LOW)" where you read the button again, why not use the same button state from the first press.

(byte or int, not boolean) SwitchState = digitalRead(Switch);

"if (SwitchState == LOW)"

Also ">=10UL" is usually just "> 50"
Created Libraries:
TFT_Extension, OneWireKeypad, SerialServo, (UPD)WiiClassicController, VWID

Arrch

Code: [Select]

    SwitchDebounce = CurrentSwitch;


This is the only time SwitchDebounce is ever used, what exactly are you using it for?

Go Up