Arduino Push Button

Revision as of 2016-03-20T16:25:18 by Kai (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Here is an example hardware setup and the corresponding software to make the Arduino board respond to push button presses. In this example, the button presses are toggling an LED on and off.


Hardware
Arduino Micro



Software

const int pushButton = 2;
const int ledPin =  8;
int ledState = LOW;
int buttonState = LOW;
const int debug = 1;

void setup()
{
  if (debug)
  {
    Serial.begin(9600); // initializing serial communication at 9600 bits per second
  }
  pinMode(pushButton, INPUT); // making the pushbutton's pin an input pin
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  const int newButtonState = digitalRead(pushButton);
  if (newButtonState != buttonState)
  {
    if (debug)
    {
      Serial.println(newButtonState);
    }
    if (newButtonState == HIGH)
    {
      ledState = !ledState;
      digitalWrite(ledPin, ledState);
    }
  }
  buttonState = newButtonState;
  delay(1);
}