lucasmcg

Debouncing-Two-Buttons

Nov 30th, 2021
1,066
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Define Variables
  2. const int output = 5;
  3. const int output2 = 6;
  4. const int button = 3;
  5. const int button2 = 2;
  6.  
  7. boolean lastButton = LOW;  // Contains last button state
  8. boolean currentButton = LOW; // Contains current button state
  9. boolean output_state = LOW; // Present state of output true/on false/off
  10.  
  11. boolean lastButton2 = LOW;  // Contains last button2 state
  12. boolean currentButton2 = LOW; // Contains current button2 state
  13. boolean output_state2 = LOW; // Present state of ouput2 true/on false/off
  14.  
  15. void setup()
  16. {
  17.   // Define pin types
  18.   pinMode(output, OUTPUT);
  19.   pinMode(output2, OUTPUT);
  20.   pinMode(button, INPUT);
  21.   pinMode(button2, INPUT);
  22.   }
  23.  
  24. void loop()
  25. {
  26.   // Set the current button state with the debounced value
  27.   currentButton = debounce(lastButton, button);
  28.  
  29.   if (lastButton == LOW && currentButton == HIGH) // If button was pressed
  30.   {
  31.     output_state = !output_state; // toggle the output value
  32.    }
  33.    
  34. lastButton = currentButton; // Change the state of the button
  35.  
  36. digitalWrite(output, output_state); // Set the state of the output
  37.  
  38.  
  39. // Set the current button state with the debounced value
  40.   currentButton2 = debounce(lastButton2, button2);
  41.  
  42.   if (lastButton2 == LOW && currentButton2 == HIGH) // If button2 was pressed
  43.   {
  44.     output_state2 = !output_state2; // toggle the output2 value
  45.    }
  46.    
  47. lastButton2 = currentButton2; // Change the state of the button
  48.  
  49. digitalWrite(output2, output_state2); // Set the state of the output
  50.  
  51.  
  52. }
  53.  
  54. //-------------------------------------------------------------------------------------
  55. /* Debouncing Function.
  56.  * Pass in the button number and previous state of the button as an input argumnets.
  57.  * Return as an output argument the current debounced state of the button.
  58. */
  59.  
  60. boolean debounce(boolean last, byte sw)
  61. {
  62.   boolean current = digitalRead(sw);  // Read the state of the button
  63.   if (last != current) // If values are different
  64.   {
  65.     delay(5);
  66.     current = digitalRead(sw); // Read the state of the button again
  67.   }
  68.     return current;
  69.     }
RAW Paste Data