Hardware Reference
In-Depth Information
Reading Digital Inputs
These are the simplest circuit to build, because they consist of a single resistor and switch combination, as shown
in Figure 2-2 .
+ve
R1
Pin 2
Figure 2-2. Reading a digital switch on the Arduino
In this configuration, pin 2 is used as an example and reports a 1 (high) voltage to the Arduino at all times the
switch is open. This is because of the “pull-up” resistor, R1. Without it, the pin is effectively disconnected, so its voltage
may fluctuate to any value between 0 and 5v, causing false readings. (Most of the time, however, it will float up to 1.)
When the switch is closed, the pin is connected directly to the 0v ground rail, causing a 0 to be read. The Arduino code
then watches for this change as follows:
int inputSwitchPin = 2;
int lastState = HIGH;
void setup() {
Serial.begin(9600);
pinMode(inputSwitchPin, INPUT);
}
void loop() {
int pinState = digitalRead(inputSwitchPin);
if (pinState != lastState) {
Serial.println(pinState?"released":"pressed");
lastState = pinState;
}
}
This will work in some situations but not all, because hardware isn't that simple! Switches, being mechanical beasts,
have a tendency to “bounce” between on and off a few times when they're pressed. If this switch were connected to a
light, you probably wouldn't see it switch on and off, however, because the time involved is measured in milliseconds.
But a computer is fast enough to spot it, so you need to program the code to ignore any state changes that occur within,
say, 100 ms of each other.
int inputSwitchPin = 2;
int lastState;
long timeLastPressed;
long debouncePeriod = 100;
 
Search WWH ::




Custom Search