EXPLANATION
Let’s just take a look at the
loop()
function, because that’s the only
place where anything was changed relative to the “off switch” program.
void loop() {
switchValue = digitalRead(switchPin);
if(switchValue == LOW) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
delay(50);
}
Just as with the “off switch,” you start by reading out the
switchPin
and saving the current value, i.e.,
HIGH
or
LOW
in the
switchValue
variable.
But you do not want to write the read value into the LED
pin — just the opposite: When
switchValue
has the
value of
LOW
, you want to switch on the LED
(
digitalWrite(ledPin, HIGH)
); otherwise, you want to
switch off the LED (
digitalWrite(ledPin, LOW)
).
In the program text, you express that with
if(...){...} else{...}
. Note the “if” and “else.” You
guessed it — this lets you use the program to respond to
different conditions.
The condition to which you are responding here is
switchValue == LOW
. You can understand that as a
question: “Is the switch value equal to LOW?” You can
evaluate the answer to that with the
if()
instruction: If
the
switchValue
is equal to
LOW
(
if(switchValue == LOW)
), the program code in the first
pair of curly brackets is carried out:
digitalWrite(ledPin, HIGH)
. The LED is switched on.
Otherwise (
else
) the part in the second pair of curly
brackets is carried out:
digitalWrite(ledPin, LOW)
. The
LED is switched off.
Finally,
delay(50)
will make you wait briefly before the
entire sequence repeats.
</>
!
JUMPER WIRES
Jumper wires serve as an easy way to connect electronic
components to each other. In this experiment kit, you will
find two different types:
male-male and male-female.
They really are called that! “Male-male” means that there
is a wire on both ends. While “male-female,” on the other
hand, there is a wire on one end and a socket on the other.
Jumper wires are sometimes also called patch cables.
»
Female End«
»
Male End«
16
PROJECT 3
CodeGamer manual inside english.indd 16
7/19/16 12:31 PM