Buttons are used as two different ways, Like as a “Switch” or “Push Button”. Switch is like the button that you are used in your home to operate home appliances. It allows user to change the setting between two states. A Push Button is used to shorts the circuit when it is pressed. It is used in many circuits to trigger the systems.
Components :
- Arduino Uno
- Jumper wires
- 1K Ohm resistor
- Buttons
- Bread Board
Push Button as Pull-down :
Code :
const int buttonPin = 2; // the number for pushButton pi
const int ledPin = 13; // the number for LED
int buttonState = 0;
void setup() {
// initialize the LED pin as an output
pinMode(ledPin, OUTPUT);
// initialize the pushButton pin as an Input
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of pushButton value:
buttonState = digitalRead(buttonPin);
// check if the pushButton is presses. If it is
if(buttonState == HIGH){
// turn LED on:
digitalWrite(ledPin,HIGH);
}else{
// turn LED off:
digitalWrite(ledPin,LOW);
}
}
Push Button as Input_Pullup :
In this method, we set the button as INPUT_PULLUP in void setup that means the initial state of button is HIGH. When we push the button, the state will change from HIGH to LOW. This method is much efficient and easy to use. But it totally depends on you which method you want to use.
Code :
const int buttonPin = 2; // the number for pushButton pi
const int ledPin = 13; // the number for LED
int buttonState = 0;
void setup() {
// initialize the LED pin as an output
pinMode(ledPin, OUTPUT);
// initialize the pushButton pin as an Input
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
// read the state of pushButton value:
buttonState = digitalRead(buttonPin);
// check if the pushButton is presses. If it is
if(buttonState == LOW){
// turn LED on:
digitalWrite(ledPin,HIGH);
}else{
// turn LED off:
digitalWrite(ledPin,LOW);
}
}
Push button as a switch :
The circuit diagram should be same. We can do changes in our code. Here is the code :
bool flag = false, State=false;
int ledPin=13;
void setup()
{
Serial.begin(9600);
pinMode(2, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop()
{
if (digitalRead(2) == LOW && flag == false)
{
Serial.println("ON");
flag = true;
State = !State;
if(State==true)
digitalWrite(ledPin, HIGH);
else
digitalWrite(ledPin, LOW);
}
else if (digitalRead(2) == HIGH && flag == true)
{
flag = false;
}
}
Good day! I just want to offer you a big thumbs up for your excellent information you have got here on this post. Ill be coming back to your blog for more soon.