Main push button article: Using push buttons with Arduino
Main switch button article: Using switch buttons with Arduino
Let's 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. Switch buttons instead 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.
Wiring schemaThis 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 turned ON.
Note: the button pin can be connected to Arduino Nano D4 or any other digital input pin.
Arduino code for push buttonWe'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;
}
Arduino code for switch buttonWe'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.
Comments
Please log in or sign up to comment.