Switch input example for Arduino

This is a simple switch input example for the Arduino Nano. The circuit diagram, photos of the breadboard circuit, and two example Arduino programs are shown below.

This version switches the LED on when the switch is pressed and switches the LED off when the switch is not pressed.

//
// Arduino switch input example
// Written by Ted Burke - 10-10-2018
//

void setup()
{
  pinMode(3, OUTPUT); // indicator LED
}

void loop()
{
  int x;

  x = digitalRead(2); // switch input
  
  if (x == 1)
  {
    digitalWrite(3, HIGH); // LED on
  }
  else
  {
    digitalWrite(3, LOW); // LED off
  }
}

This version toggles the state of the LED each time the switch is pressed.

//
// Arduino switch input example
// Written by Ted Burke - 10-10-2018
//

// This variable remembers if the LED is on or off.
// Each time the switch on D2 is pressed, this
// variable switches from 1 to 0 or vice versa.
int led_on = 0;

void setup()
{
  pinMode(3, OUTPUT); // indicator LED on D3
}

void loop()
{
  int is_pressed;

  // Read the switch input and store value in variable is_pressed
  is_pressed = digitalRead(2);
  
  if (is_pressed == 1)
  {
    // The switch is pressed so toggle the led_on variable
    led_on = 1 - led_on;

    // Wait 500ms to allow switch to be released
    delay(500);
  }

  // Set the LED pin (D3) to match the led_on variable
  digitalWrite(3, led_on);
}
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s