Saturday, August 15, 2015

Easiest way to do a momentary push button for arduino

The best way to do a momentary push button involves placing a resistor between the button and ground.  But if your code is simple enough and can afford a slight delay, then you can use this method instead.

  • Simply use a 2 pin momentary push button between one GPIO pin and ground.  
  • Use the code below as an example. 
  • Define the GPIO pin and set that pin to HIGH as default.  
  • Then in the main loop, read the pin and if it detects a LOW signal, perform the action needed when the button is pushed.  
If the button is pushed, it connects connects the ground to the GPIO pin and thus that pin is grounded and furthermore the pin will read as LOW.  when released it will go back to HIGH.   

If you don't do an immediate delay after, the loop will perform that action as many times as it can while the button is pushed...and that can be a lot.  

#define button 9   // # input button (detects the button press)
void setup() {
 digitalWrite(button , HIGH);
void loop () 
  if(digitalRead(button) == LOW){ delay(500); action++;} 

No comments:

Post a Comment