12 September 2020

Turn a relay on and off using a push button. When using a pushbutton, you have use a library (don't reinvent the wheel) to control the push button signal. It's called a debounce, taking account in faulty signals and long button holds, still resulting in a single click. In this sample code I use acebutton library, you can find it from "Tools -> Manage Libraries..." in your Arduino code editor.

MEGA2560 - https://s.click.aliexpress.com/e/_dSHcI3D
Solderless Prototype Breadboard - https://s.click.aliexpress.com/e/_dZBtgob
Push Buttons - https://s.click.aliexpress.com/e/_dWLsiIR
Relay - https://s.click.aliexpress.com/e/_dYUsVFl
Jumper Wires - https://s.click.aliexpress.com/e/_d81TuyF

 
Source code viewer
#include <AceButton.h> using namespace ace_button;   #define RELAY_ON LOW #define RELAY_OFF HIGH   const int BUTTON_PIN = 2; const int RELAY_PIN = 3;   AceButton button(BUTTON_PIN);   void handleEvent(AceButton*, uint8_t, uint8_t);   void setup() { // Relay setup. pinMode(RELAY_PIN, OUTPUT); digitalWrite(RELAY_PIN, RELAY_OFF);   // Button setup. pinMode(BUTTON_PIN, INPUT_PULLUP); button.setEventHandler(handleEvent); }   void loop() { button.check(); }   void handleEvent(AceButton* /*button*/, uint8_t eventType, uint8_t /*buttonState*/) { switch (eventType) { case AceButton::kEventPressed: if (digitalRead(RELAY_PIN) == RELAY_ON) { digitalWrite(RELAY_PIN, RELAY_OFF); } else { digitalWrite(RELAY_PIN, RELAY_ON); } break; } }
arduino relay button