Using push buttons with Arduino

  • avatar
  • 1.3K Views
  • 1 Like
  • 4 mins read

Today we are going to speak about push buttons, the wiring and how to implement the code for this circuit elements in Arduino. Push buttons connect two points in a circuit when you press them. That means that logic state of the circuit change when you press and keep pressed the button.

Components

arduino-nano

1x Arduino Nano (or another Arduino module)

Available on: Ebay | Banggood | Aliexpress

mini-breadboard

1x Mini-breadboard

Available on: Ebay | Banggood | Aliexpress

push-button

1x Push button

Available on: Ebay | Banggood | Aliexpress

dupont

Dupont wires

Available on: Ebay | Banggood | Aliexpress

Wiring schema

This example demonstrates the use of a button with Arduino Nano using internal pull-up resistor. That means that we will have a default HIGH value and LOW value when the button is pressed.

arduino_push_button.png

Note: the button pin can be connected to Arduino Nano D4 or any other digital input pin.

Arduino code

We've defined a struct (called button) to represent the state of the button. The serial monitor will output that state in real time.

#define BUTTON_PIN 4

struct button {
byte pressed = 0;
};

button button;

void setup()
{
pinMode(BUTTON_PIN, INPUT_PULLUP);

Serial.begin(115200);
}

void loop()
{
button.pressed = isButtonPressed(BUTTON_PIN);

if (button.pressed) {
Serial.println("Button pressed");
} else {
Serial.println("Button not pressed");
}
}

bool isButtonPressed(int pin)
{
return digitalRead(pin) == 0;
}

Credits

Official GitHub: https://github.com/hibit-dev/buttons

 Join Our Monthly Newsletter

Get the latest news and popular articles to your inbox every month

0 Comments

Leave a Reply

Your email address will not be published.

Replying to message:

Hey visitor! Register your account and get access to featured articles and more - it's free.