LED + button - mako

Mako
Mako
nome
Go to content
Arduino > Tutorials
Turn on a LED using a pushbutton
Let's continue with the second step of the Tutorial section. In this part of the tutorial you'll use a pushbutton to turn a LED on and off.
A button is a mechanical device that closes a circuit when pressed.
The purpose of the pushbutton is to connect two parts of the circuit together, so a pair of pins are superfluous and serve for better stability.
You can still use the LED_BUILIN at pin 13, or use other LEDs.




const byte PUSHBUTTON_PIN = 2;
const byte LED_PIN= 13;
byte PushButtonState = 0;

void setup(){
pinMode(LED_PIN, OUTPUT);
pinMode(PUSHBUTTON_PIN, OUTPUT);
}
void loop();
PushButtonState = digitalWrite(PUSHBUTTON_PIN);
if (PushButtonState == HIGH) {
digitalWrite(LED_PIN, HIGH);
}
else {
digitalWrite(LED_PIN, LOW);
}
delay (10);
}
Sketch analysis
Two new statement are introduced in this sketch: if and else. Their role is very intuitive: if this happens, do that, on the other hand (else) do this.
Furthermore, PushButtonState = 0 are declared (read the guide for the differences between byte/int/const...). Buttons have two states, 0 and 1. 0 when not pressed, 1 when pressed. Declare 0, the button normally is not pressed.
PushButtonState = digitalWrite(PUSHBUTTON_PIN):  assigns the value read by digitalWrite to the PushButtonState variable.
==: use it when you want a variable to be equal to a value.

There are no reviews yet.
0
0
0
0
0

Back to content