ReadSwitchInput Arduino Sketch

This sketch is used by Exercise: Read Switch Input.

Full Source Code

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

 1// ReadSwitchInput - read a digital input and report its value using the LED and serial monitor
 2//
 3// Copyright (c) 2016, Garth Zeglin.  All rights reserved. Licensed under the
 4// terms of the BSD 3-clause license as included in LICENSE.
 5//
 6// This program assumes that:
 7//
 8//  1. An SPST switch connected between digital pin 2 and ground, and a 10K
 9//  pullup resistor between digital pin 2 and +5V.
10//
11//  2. The serial console on the Arduino IDE is set to 9600 baud communications speed.
12// ================================================================================
13// Define constant values.
14
15// The wiring assignment.
16#define SWITCH_PIN 2
17
18// ================================================================================
19// Configure the hardware once after booting up.  This runs once after pressing
20// reset or powering up the board.
21
22void setup()
23{
24  // Initialize the serial UART at 9600 bits per second.
25  Serial.begin(9600);
26
27  // Initialize the hardware digital pin 13 as an output.  The 'OUTPUT' symbol
28  // is pre-defined by the Arduino system.
29  pinMode(LED_BUILTIN, OUTPUT);
30  
31  // Initialize the switch pin for input.
32  pinMode(SWITCH_PIN, INPUT);
33}
34
35// ================================================================================
36// Run one iteration of the main event loop.  The Arduino system will call this
37// function over and over forever.
38void loop()
39{
40  // Read the switch value.  As wired, it is 'active-low', so if the switch is
41  // open the value will be 1 (HIGH), else 0 (LOW).
42  int value = digitalRead(SWITCH_PIN);
43
44  // Output the value to the onboard LED.
45  digitalWrite(LED_BUILTIN, value);
46    
47  // Print the value out the serial port so it can be seen on the console.  This
48  // can take time, so this delay is the primary determinant of the inptu
49  // sampling rate.
50  Serial.println(value);
51}
52// ================================================================================