Project 3: On Switch - Thames & Kosmos Code Gamer Experiment Manual

Coding workshop ? game with kosmobits
Table of Contents

Advertisement

PROJECT 3
This is almost the same as in your first program. The
is operated as an output pin (
ledPin
(
), on the other hand, is operated as an input
switchPin
pin. So in the
pinMode()
instead of the value
OUTPUT
First, use
digitalRead(switchPin)
current state of pin 9. If the pin is electrically connected to
a "GND" pin, it yields the value
there is no voltage supplied. Otherwise, it yields the value
. Save this value in the
HIGH
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,
will make you wait briefly before the
delay(50)
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.
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.
CodeGamer manual inside english.indd 15
). Pin 9
OUTPUT
instruction for
,
switchPin
, you will use
INPUT_PULLUP
to read out the
. That means that
LOW
.
switchValue
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(switchPin, INPUT_PULLUP);
}
.
void loop() {
switchValue = digitalRead(switchPin);
digitalWrite(ledPin, switchValue);
delay(50);
}
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!
THE PROGRAM
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);
}
CodeGamer
</>
15
7/19/16 12:31 PM

Advertisement

Table of Contents
loading

Table of Contents