Example Code for Arduino-Control Water Pump ON/OFF
Control the ON/OFF of a water pump using a blue button (turn on) and a red button (turn off) with the DFRobot magnetic latching relay and Arduino UNO. Users can learn how to interface the magnetic latching relay with Arduino and use pulse signals to control relay states.
Hardware Preparation
- DFRduino UNO R3 x 1
- Gravity: Digital Push Button (Red) x 1
- Gravity: Digital Push Button (Blue) x 1
- M-M/F-M/F-F Jumper wires
Software Preparation
Wiring Diagram

- Magnetic Latching Relay
- VCC to UNO 5V
- GND to UNO GND
- Pin A to UNO D3
- Pin B to UNO D2
- Magnetic Latching Relay
- Pin A to Water Pump Positive
- COM to Battery Positive
- Battery
- Negative to Water Pump Negative
- Blue Button
- Pin D to UNO D13
- Pin + to UNO 5V
- Pin - to UNO GND
- Red Button
- Pin D to UNO D4
- Pin + to UNO 5V
- Pin - to UNO GND
Sample Code
int INA = 3;
int INB = 2;
int buttonA = 13; //Set Button A as blue button, connect to Pin 13
int buttonB = 4; //Set Button B as red button, connect to Pin 4
void setup() {
pinMode(INA, OUTPUT);
pinMode(INB, OUTPUT);
pinMode(buttonA, INPUT);
pinMode(buttonB, INPUT);
}
void loop() {
if (digitalRead(buttonA) == HIGH)
{
digitalWrite(INA, HIGH);
delay(2); //2ms pulse signal
digitalWrite(INA, LOW);
}
if (digitalRead(buttonB) == HIGH)
digitalWrite(INB, HIGH);
delay(2);//2ms pulse signal
digitalWrite(INB, LOW);
}
}
Result
When the program is downloaded, press down the blue button, the water pump turns on. Press down the red button, it turns off.
Was this article helpful?
