Example Code for Arduino-Solenoid Valve Control

Last revision 2025/12/23

This tutorial will show you how to drive the solenoid valve to open or close through a relay under the control of UNO mainboard.

Hardware Preparation

  • DFRduino UNO R3 x 1
  • Solenoid Valve DN15 x 1
  • Gravity: Digital 5A Relay Module(Arduino Compatible) x 1
  • PC x 1
  • Dupont lines x n

Software Preparation

Wiring Diagram

  • Pin definitions of the connecting terminal of the relay module:

    • NC: normally closed terminal
    • NO: normally open terminal
    • N/A: not available
    • COM: common terminal
  • Connect the control terminal of the relay module to Arduino: green wire goes to the digital pin 3; red wire to 5V pin; black wire to GND;

  • Connect the connecting terminal of the relay module to external power supply and solenoid valve: COM port goes to the positive pole of external power supply; NO port to red wire of the solenoid valve; NC port to blue wire of the valve;

  • Connect the yellow wire of solenoid valve to the negative pole of the external power.

There is an open/close indicator on the solenoid valve: it displays | when the valve is closed, and — when the valve is open.

The circle at the right-lower corner of the solenoid valve is an Off/On switch, pull it out gently and then we can close or open the valve manually.

FIT0616 FIT0617.Solenoid Valve-DN15 Connection Diagram

Sample Code

Install the Arduino IDE software.

Open the compiling environment of the Arduino IDE, and upload the following codes:

`/***************************************************
Digital Relay Module  (Arduino & Raspberry Pi compatible)
 
***************************************************/
/***************************************************
//Arduino Sample Code //www.DFRobot.com 
//Last modified on 24th January 2019 by WWZ 
//This code has been updated to work with the sample code provided in the Wiki 
****************************************************/ 
/***********Notice and Trouble shooting***************
1.Beware of electric shock and burn out the circuit board.
2.The input voltage of this module is 2.8~5.5V.              
****************************************************/                      //All the above instructions are based on Digital Relay Module

const int RelayPin = 3;                   
       
void setup() {
   Serial.begin(9600);   
  pinMode(RelayPin, OUTPUT);
} 
void loop() {
  if(Serial.read()=='o'){

     digitalWrite(RelayPin, HIGH);   //Turn on  
     Serial.println("open");
     delay(100);
  }
   if(Serial.read()=='f'){

     digitalWrite(RelayPin, LOW);   //Turn off   
     Serial.println("close");
     delay(100);
  }
}`

Result

Input "o" in the Arduino IDE serial monitor input field, then an "open" will be displayed on its display interface, and the solenoid valve is open; Input "f", it will diaplay "close" and the valve will be closed.

Was this article helpful?

TOP