Using switch buttons with Arduino

  • avatar
  • 2.2K Views
  • 3 Likes
  • 4 mins read

Let's speak now about switch buttons, the wiring and how to implement the code for this circuit elements in Arduino. Switch buttons connect two points in a circuit when you press them and maintain the state without the need to keep the button pressed. That means that logic state of the circuit change every time you press the button.

Components

arduino-nano

1x Arduino Nano (or another Arduino module)

$3.18 $2.80

Buy now

mini-breadboard

1x Mini-breadboard

$1.17

Buy now

switch-button

1x Switch button

$2.93

Buy now

dupont

Dupont wires

$1.61 $1.53

Buy now

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 switch is turned ON.

arduino_switch_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 toggle) to represent the state of the switch. The serial monitor will output that state in real time.

#define TOGGLE_PIN 4

struct toggle {
byte on = 0;
};

toggle toggle;

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

Serial.begin(115200);
}

void loop()
{
toggle.on = isToggleOn(TOGGLE_PIN);

if (toggle.on) {
Serial.println("Toggle ON");
} else {
Serial.println("Toggle OFF");
}
}

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

Note: we use toggle to define the button because switch is reserved word and may cause conflicts.

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

We never send SPAM nor unsolicited emails

0 Comments

Leave a Reply

Your email address will not be published.

Replying to the message: View original

Hey visitor! Unlock access to featured articles, remove ads and much more - it's free.