
Arduino Lesson 3
Turn a LED on/off from the input from a button
Components Required
Introduction
Learning Outcomes
- Digital Read
- IF-ELSE conditions
- Variables
Theory
Methodology
Magicbit equipped with two onboard push buttons in Magicbit development board, Lets select the push button which is wired to D34. Buttons on the board are in pulled up internally (to learn more about pullups/pulldowns follow this link), which means when button is not pressed the status of the button is 1(HIGH), & when the button is pressed the status of the button is 0(LOW).
Also like in previous example we need to select an LED to indicate the change, lets select RED LED which is wired to pin D27.
First we set the input output configurations of the Button and the LED using pinMode, in this case button is an INPUT, LED is an OUTPUT. Then in the loop section we check the state of the button & store it in an int type variable called buttonState (follow this link to learn more about data types in arduino).
Then we can use the variable as the condition of the if block, and if the button is pressed, the bulb should turn on, and the button is not pressed the light should turn off.
Code
void Setup(){
pinMode(27,OUTPUT);
pinMode(34,INPUT);
}
void loop(){
int buttonState = digitalRead(34);
if(buttonState == LOW){
digitalWrite(27, HIGH);
}else{
digitalWrite(27, LOW);
}
}
Explanation
digitalRead(pin No): Reads the condition of the given pin and returns a digital value HIGH or LOW.
IF/ELSE: Used to evaluate a digital condition, we can put a digital logic condition in then parenthesis. If the condition is true, it executes the code block in the immediate curly bracket section, if the condition is false it executes the code block in the else curly bracket.
- if(condition){
- //Do if condition is true
- }else{
- //Do if condition is false}
Note: Write a code to toggle an LED in the button press. LED turns on when button pressed & released, LED turns off when button is pressed & released again. (Hint: Make use of variables to ‘remember’ the state of the button press).