06
When you press the switch, the bright LED will immediately light up, and the LED will go out when
you press the switch again to make the switch button pop up.
What will you see
1. Declare the LED and switch pins, and the “switchstate” variable to store the state of the button
2. Setup the LED as output and switch as input.
3. Read the state of the switch.
4. If the switch is pressed(HIGH), turn the LED on.
5. If the switch is pressed again and switch button is pop up(LOW), turn the LED off.
Code overview
Code usage
A variable is a placeholder for a value that may change in your code.
V
ariables must be introduced or "declared" before using variables.
Here, we declare two variables that define which ports of the base shield
the module should connect to and a variable called ‘switchState’
of type int(integer) and assign it a value of 0 to record the status of
the switch. Don't forget that variable names are case-sensitive!
Input or Output
Before using one of the digital pins, you need to tell
Arduino
whether it is an input (INPUT) or an output (OUTPUT).
W
e use a built-in "function" called pinMode() to make the pin
corresponding to the led as an output and switch as an input.
Digital Input
W
e use the digitalRead() function to read the value on a digital pin.
Check to see if an input pin is reading HIGH(5V) or LOW(0V).
Returns
TRUE(1) or
F
ALSE(0) depending on the reading.
If/else Statements
The if / else statement allows your code to make corresponding choices
for different results, running a set of code when the logical statement in
parentheses is true, and another set of code when the logical statement is
false. For example, if the switch is pressed, the LED will light on and when
the switch is pressed a second time and the switch button is pop up,
the LED will light off.
This is another logical operato
r
.
The "equal" symbol (==) can be confusing.
The two equal signs are equal to ask: “The two values are equal
to each other? “On the other hand, if you want to compare two values,
don't forget to add a second equal sign, because if it's just a "=",
it's an assignment method.
Is equal to
When you're using a pin as an OUTPUT, you can command it to be
HIGH (output 5 volts) or LOW (output 0 volts). When you set it to HIGH,
for digital output modules, it means work. When you set it to LO
W
,
for digital output modules, it means don't work. For example, the led will
light on(work) when it is set to HIGH and it will light off(don't work)
when it is set to LO
W
.
Digital Output
Integer
V
ariables
Содержание Crowtail Deluxe Kit
Страница 47: ......