Advertisement
jmyean

Using Boolean and Debounce

Mar 28th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * Jung Min Yean
  3.  * 03/27/19
  4.  * Program about turning on and off one LED with a button
  5.  *
  6.   */
  7.  
  8.  
  9.  // Declare Constants and variables
  10. const byte Button=9;
  11. const byte LedPin=17;
  12. const byte LedPin2 = 19;
  13. int count=0;
  14. boolean currentVal;
  15. boolean lastVal; //currentVal and lastVal treats the button as a switch. It evaluates the value of the current and previous press. If different, then in is a new press.
  16.  
  17. void setup() {
  18.   pinMode(LedPin, OUTPUT); //pinMode assign mode of the pin (input or output)
  19.   pinMode(LedPin2, OUTPUT);
  20.   pinMode(Button, INPUT);
  21.   Serial.begin(9600); //activate the monitor
  22. }
  23. boolean debounce(boolean last)
  24. {
  25.   boolean current = digitalRead(Button);
  26.   if (last != current)
  27.   {
  28.     delay(5);
  29.     current = digitalRead(Button);
  30.   }
  31.   return current;
  32. }
  33. void loop()
  34. {
  35. currentVal = debounce(lastVal);      // will go and read the Button
  36. if (lastVal == LOW && currentVal == HIGH)    // Checks if the button has been pressed
  37.  {
  38.   count++;
  39.  }
  40.   if (count == 1)  
  41.   {
  42.     digitalWrite(LedPin, HIGH);
  43.     digitalWrite(LedPin2, LOW);
  44.   }
  45.   else if(count == 2)
  46.   {
  47.     digitalWrite(LedPin2, HIGH);
  48.     digitalWrite(LedPin, LOW);
  49.   }
  50.   else if(count == 3)
  51.   {
  52.     digitalWrite(LedPin, HIGH);
  53.     digitalWrite(LedPin2, HIGH);
  54.   }
  55.   else if (count ==4)
  56.   {
  57.     digitalWrite(LedPin, LOW);
  58.     digitalWrite(LedPin2, LOW);
  59.     count = 0;
  60.   }
  61.   lastVal=currentVal;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement