Arduino Sketch ReadSwitchInput

This sketch is used by Exercise: Read Switch Input.

Full Source Code

The full code is all in one file ReadSwitchInput.ino.

// ReadSwitchInput - read a digital input and report its value using the LED and serial monitor
// Copyright (c) 2016, Garth Zeglin.  All rights reserved. Licensed under the
// terms of the BSD 3-clause license as included in LICENSE.
// This program assumes that:
//  1. An SPST switch connected between digital pin 2 and ground, and a 10K
//  pullup resistor between digital pin 2 and +5V.
//  2. The serial console on the Arduino IDE is set to 9600 baud communications speed.
// ================================================================================
// Define constant values.

// The wiring assignment.
#define SWITCH_PIN 2

// ================================================================================
// Configure the hardware once after booting up.  This runs once after pressing
// reset or powering up the board.

void setup()
  // Initialize the serial UART at 9600 bits per second.

  // Initialize the hardware digital pin 13 as an output.  The 'OUTPUT' symbol
  // is pre-defined by the Arduino system.
  // Initialize the switch pin for input.

// ================================================================================
// Run one iteration of the main event loop.  The Arduino system will call this
// function over and over forever.
void loop()
  // Read the switch value.  As wired, it is 'active-low', so if the switch is
  // open the value will be 1 (HIGH), else 0 (LOW).
  int value = digitalRead(SWITCH_PIN);

  // Output the value to the onboard LED.
  digitalWrite(LED_BUILTIN, value);
  // Print the value out the serial port so it can be seen on the console.  This
  // can take time, so this delay is the primary determinant of the inptu
  // sampling rate.
// ================================================================================

Source: Arduino Sketch ReadSwitchInput

About The Author

Scroll to Top