In this lesson we’re going to let a LED flashing with a button.
For that do we need:
- 1 Arduino
- 1 Breadboard
- 1 LED
- 1 220Ω Resistor
- 1 10kΩ Resistor
- 1 Button
- 7 Wires
Let’s start with the program code.
We have to tell the Arduino, where the LED and the Button have been connected. We do that with the command pinMode()
in the setup()
method. We have to declare the method like the lesson before. But now we need this method twice, because we also have an input pin. For our lessons we want to use pin 2 as OUTPUT and pin 3 as INPUT.
Now we switch to the loop()
method. We use for the switch the if-method. But to know, if the button is pressed, we have to read the button value.
We do that with digitalRead()
. This method returns HIGH for a pressed button and LOW for a non pressed button.
You use the if-method like this:
if(condition)
{
//program code
}
else
{
//program code
}
You have to replace condition with your condition. In our lesson it’s digitalRead(3) == HIGH
. The two equal signs are important, otherwise it won’t work.
To switch the LED on an off you also have to use the method from the last lesson.
Now we combine these methods in order control the LED with a button.
void setup() { pinMode(2, OUTPUT); //Set Digital I/O 2 as output pinMode(3, INPUT); //Set Digital I/O 3 as input } void loop() { if(digitalRead(3) == HIGH) { digitalWrite(2, HIGH); //Set Digital I/O 2 to ON } else { digitalWrite(2, LOW); //Set Digital I/O 2 to OFF } }
To see, what your code is doing, you have to build your circuit. Do it according to the following scheme:
⇐ Lesson #1 | Lesson #3 ⇒ |