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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | // 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.
Serial.begin(9600);
// Initialize the hardware digital pin 13 as an output. The 'OUTPUT' symbol
// is pre-defined by the Arduino system.
pinMode(LED_BUILTIN, OUTPUT);
// Initialize the switch pin for input.
pinMode(SWITCH_PIN, 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.
Serial.println(value);
}
// ================================================================================
|