void setup() {
pinMode(ledPin, OUTPUT);
pinMode(switchPin, INPUT_PULLUP);
}
void loop() {
switchValue = digitalRead(switchPin);
digitalWrite(ledPin, switchValue);
delay(50);
}
</>
This is almost the same as in your first program. The
ledPin
is operated as an output pin (
OUTPUT
). Pin 9
(
switchPin
), on the other hand, is operated as an input
pin. So in the
pinMode()
instruction for
switchPin
,
instead of the value
OUTPUT
, you will use
INPUT_PULLUP
.
First, use
digitalRead(switchPin)
to read out the
current state of pin 9. If the pin is electrically connected to
a “GND” pin, it yields the value
LOW
. That means that
there is no voltage supplied. Otherwise, it yields the value
HIGH
. Save this value in the
switchValue
.
Then, write this value into the LED pin. So if pin 9 is
connected to the GND pin, it switches off the LED.
Otherwise, the LED will be switched on.
Finally,
delay(50)
will make you wait briefly before the
entire sequence repeats.
On switch
YOU WILL NEED
› KosmoDuino
› 2 male-male jumper wires
PREPARATION
Connect one jumper wire to pin 9, and the other to one of
the GND pins.
int ledPin = 13;
int switchPin = 9;
int switchValue = HIGH;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(switchPin, INPUT_PULLUP);
}
void loop() {
switchValue = digitalRead(switchPin);
if(switchValue == LOW) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
delay(50);
}
THE PROGRAM
Upload the sketch to your KosmoDuino as described on
page 10. This time, after uploading, the LED will remain
dark. It only lights up when you touch the two free jumper
wire contacts together.
THE PLAN
In the previous project, you learned how to switch off an
LED with the help of a simple switch. But what do you do if
you want it to work in reverse — in other words, to have
the LED only come on if the contact is closed? Just change
the program!
15
PROJECT 3
CodeGamer
Warning! Not suitable for children under 8 y
ears.
There is a risk of hot surfaces of compon
ents on the
PCB (printed circuit board) when differe
nt polarities
are incorrectly short-circuited or the cap
acitor is
subject to fault conditions.
CodeGamer manual inside english.indd 15
7/19/16 12:31 PM