9
Create and run this Arduino program
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println(digitalRead(3));
delay(250);
}
Open the Serial Monitor window. When the switch is open, you should see a train of 1's on the
screen. When closed, the 1's change to 0's. On the hardware side, when the switch is open, no
current flows through the resistor. When no current flows through a resistor, there is no voltage
drop across the resistor, which means the voltage on each side is the same. In your circuit, when
the switch is open, pin 3 is at 5 volts which the computer reads as a 1 state. When the switch is
closed, pin 3 is directly connected to ground, which is at 0 volts. The computer reads this as a 0
state.
Now try this program which is an example of how you can have the computer sit and wait for a
sensor to change state.
void setup()
{
Serial.begin(9600);
}
void loop()
{
while (digitalRead(3) == HIGH)
;
Serial.println("Somebody closed the switch!");
10K
PIN 3
+5 V
Gnd
10K
PIN 3
+5 V
Gnd