Advertisement
coltonspastebin

Debounce

Dec 18th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. const int button = 12;
  2. const int led = 5;
  3. boolean lastbutton = false;
  4. boolean currentbutton = false;
  5. boolean ledOn = false;
  6.  
  7. void setup()
  8. {
  9. pinMode (button, INPUT);
  10. pinMode (led, OUTPUT);
  11. digitalWrite (led, HIGH);
  12. delay (5);
  13. Serial.begin (9600);
  14.  
  15. }
  16. boolean debounce (boolean lastbutton)
  17. {
  18. boolean currentbutton = digitalRead (button);
  19. if (lastbutton != currentbutton)//if lastbutton is different than currentbutton then delay for 5 milliseconds and read the currentbutton
  20. {
  21. delay (5);
  22. currentbutton = digitalRead (button);
  23. }
  24. return currentbutton;
  25. }
  26.  
  27. void loop()
  28. {
  29. currentbutton = debounce (lastbutton);//this makes the button act like a switch, so you don't have to keep your finger on the push button to turn on the LED
  30. if (currentbutton == true && lastbutton ==false)//if they are opposite
  31. {
  32. ledOn =! ledOn;//do the opposite of the LED therefore turning it on or off
  33. }
  34. digitalWrite (led, ledOn);
  35. lastbutton = currentbutton;//changed the lastbutton to match the currentbutton so if the currentbutton was false lastbutton will now turn to false
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement