Example Code for Arduino-Button Control Relay

Last revision 2025/12/22

This guide offers a comprehensive walkthrough for setting up and programming an Arduino to control a relay via digital push buttons, enabling the operation of a submersible pump. It covers necessary hardware, detailed wiring diagrams, and provides sample code for seamless integration.

Hardware Preparation

Software Preparation

Wiring Diagram

Connection 1

NO and COM ports will be used in this connection. An external DC power source is required and should be selected according to the load voltage to be connected.

DFR0989-Connection 1

Description:

  • Relay: D-----to Mainboard: 8

  • Relay: VCC---to Mainboard: 5V

  • Relay: GND-----to Mainboard: GND

  • Yellow Button: D--to---Mainboard: 2

  • Yellow Button: VCC--to---Mainboard: 5V

  • Yeloow Button: GND--to---Mainboard: GND

  • Red Button: D---to---Mainboard: 3

  • Red Button: VCC---to--Mainboard: 5V

  • Red Button:GND---to--Mainboard: GND

  • Relay Module: NO--to---Pump: positive(red wire)

  • Relay Module: COM--to--3V DC Power: positive

  • 3V DC Power: Negative--to--Pump: negative(black wire)

Connection 2

This connection is simpler. The pump is directly connected to the OUT and power by VCC, no second power source required.

DFR0989-Connection 2

Description:

  • Relay: D-----to Mainboard: 8

  • Relay: VCC---to Mainboard: 5V

  • Relay: GND-----to Mainboard: GND

  • Yellow Button: D--to---Mainboard: 2

  • Yellow Button: VCC--to---Mainboard: 5V

  • Yeloow Button: GND--to---Mainboard: GND

  • Red Button: D---to---Mainboard: 3

  • Red Button: VCC---to--Mainboard: 5V

  • Red Button:GND---to--Mainboard: GND

  • Relay Module: OUT+ --to--Pump: Positive

  • Relay Module: OUT- --to--Pump: Negative

Sample Code

The sample code below is suitable for the two connections above. It realizes the function of controlling the relay's ON/PFF through two buttons. Yellow button for pulling in, red button for releasing.

int Relaypin = 8;     // Define relay pin 
int switchPin1 = 2;  // Define yellow button pin  
int switchPin2 = 3;  // Define red button pin 

void setup() { 
 pinMode(Relaypin, OUTPUT);
 pinMode(switchPin1, INPUT);  
 pinMode(switchPin2, INPUT);
}

void loop() {
  if (digitalRead(2)==1) //Determine if the yellow button is pressed 
  {
    delay(50);
    if(digitalRead(2)==1){
      digitalWrite(8, HIGH);//Set relay to high level 
    }
  }
  if (digitalRead(3)==1) //Determine if the red button is pressed 
  {
    delay(50);
    if(digitalRead(3)==1){
      digitalWrite(8, LOW);//Set relay to low level 
    }
  }
}

Result

When the yellow button is pressed, the relay is in pull-in state and the pump starts working; when the red button is pressed, the relay is in releasing state and the pump stops working.

Was this article helpful?

TOP