Hardware Reference
In-Depth Information
void setup() {
Serial.begin(9600);
pinMode(inputSwitchPin, INPUT);
lastState = digitalRead(inputSwitchPin);
timeLastPressed = millis();
}
void loop() {
int pinState = digitalRead(inputSwitchPin);
if (pinState != lastState && millis() - timeLastPressed > debouncePeriod) {
Serial.println(pinState?"released":"pressed");
timeLastPressed = millis();
lastState = pinState;
}
}
The switch I've used here is normally open and, as the name suggests, remains open (so that no current flows
between the contacts) under normal circumstances and is closed when the switch is pressed. Some switches are
marked as normally closed, in which case you simply reverse the output in the example.
It is also possible to use analog devices, such as a light sensor, to report a digital on/off input when you're are not
concerned with the quantity involved. In this example, you might be interested in whether it is light outside but not
how bright the light was. You can amend the circuit as shown in Figure 2-3 .
+ve
R1
Pin 2
Figure 2-3. Reading the light on the Arduino
This circuit is known as a potential divider circuit , since the voltage (known formally as potential ) is divided
proportionally by the resistors placed across the supply rails. R2 is a light-dependent resistor (LDR), which has a very
high resistance (like an open switch) when it is dark but acts almost like a closed switch (that is, low resistance) when
it is light. (This is an oversimplification of the process but is enough to get things working.) The exact resistance of
the LDR under these conditions is governed by the specific LDR, and not all manufacturers or suppliers provide this
information, so you might have to experiment.
This basic circuit can be used to switch on lights when it gets dark (remembering to point the LDR away from the
light in question!) and can be used to monitor people passing by the sensor because their shadow is usually enough
to switch the LDR off. You can also get infrared transmitters and receivers that work in similar fashion, which can be
placed on either side of a doorway or front gates, so you can get forewarning when someone is approaching your house.
 
Search WWH ::




Custom Search