Arduino: pushButton to switch


arduino pushbutton makit

Today we’re going to show how to use a pushButton as a switch just by programming Arduino.

PushButtons can activate an output (eg buzzer or a led) when we press them. En activity 3 section 2 (from downloads) we use File-> Examples-> Digital ->Button to turn a led on or off depending on if we’re pressing it or not. This works for a buzzer or a ring-bell, but, what if we want to use the pushButton as a switch[1]?

In order to do this, we are going to use a variable which we will toggle (from 0 to 1 and viceversa) each time we press the push button. Then we are going to use the state of that variable to turn the led on or off with an if statement.

conexión pulsador táctil arduino makitconexión pulsador arduino makit

Take a look at the code and experiment with your Humbot material.

/*---------------------------------------------------------------------------
----------- PROGRAM -----------------
-----------------------------------------------------------------------------
*/
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin

// variables will change:
int buttonState = 0; // variable for READING the pushbutton status
int variable_buttonState = 0; // variable for STORING the pushbutton status

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 the pushbutton value:
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
variable_buttonState = !variable_buttonState;
//waiting time so we're not changing state several times with only push
delay(300);
}

if (variable_buttonState == HIGH) {
// turn led on
digitalWrite(ledPin, HIGH);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}

Imagine it, design it, makit!

[1] Remember that a switch button changes its state when we press it and remains in that state until we press it again. On the other hand, push buttons only change their state while we are pressing, going back to its original state when the button is released.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.