Arduino UNO R4 - Button

by DIYables in Circuits > Arduino

27 Views, 0 Favorites, 0 Comments

Arduino UNO R4 - Button

arduino-uno-r4-button-cover.jpg

This is a compact build guide. The full tutorial, with the wiring diagram and a line-by-line walkthrough of the code, is here: https://newbiely.com/tutorials/arduino-uno-r4/arduino-uno-r4-button

This build shows how to read a push button with an Arduino UNO R4. You will wire a simple button (or a button module) to a digital pin, set that pin up as an internal pull-up input, and read its state in code to detect presses and releases.

Supplies

Wiring

arduino-uno-r4-button-wiring-diagram.jpg

A push button has four pins, but they are connected together in pairs inside the button, so only two of them matter. Connect one of those two pins to GND on the Arduino UNO R4 and the other to pin 7. This works the same way for a PCB-mount (breadboard) button and for a panel-mount button, just follow the wiring diagram for the type you have.

If you use a button module instead, connect its GND pin to ground, VCC to 5V or 3.3V, and OUT to a digital input pin on the Arduino.

How It Works

Inside the button, pin A and pin B are not connected when it is released, and become connected when you press it. With pin 7 set as an internal pull-up input, the pin reads HIGH when the button is not pressed and LOW when it is pressed, since no external resistor is needed.

A button module works the other way: OUT is LOW when the button is not pressed and goes HIGH when pressed, because the module supplies its own pull configuration.

Code

The sketch sets pin 7 as an internal pull-up input with pinMode(7, INPUT_PULLUP), so no external resistor is required. It then uses digitalRead() on that pin to get the current state of the button.

A second version of the sketch builds on this to detect the press and release events instead of just the raw state, printing the result to the Serial Monitor so you can watch it happen when you press and release the button.

arduino-uno-r4-button.ino - the sketch from the tutorial, unchanged.

#define BUTTON_PIN 7 // The Arduino UNO R4 pin connected to the button

void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// initialize the pushbutton pin as a pull-up input
pinMode(BUTTON_PIN, INPUT_PULLUP);
}

void loop() {
// read the state of the switch/button:
int button_state = digitalRead(BUTTON_PIN);

// print out the button's state
Serial.println(button_state);
delay(500);
}


Things That Go Wrong

Chattering is the main issue to watch for: a single press or release can be read as multiple rapid changes because of the mechanical contact bouncing. This only matters for applications where you need an exact count of presses; for simple on/off reading it usually is not a problem.

Full Tutorial

The complete tutorial, wiring diagram and code explanation: https://newbiely.com/tutorials/arduino-uno-r4/arduino-uno-r4-button