Arduino Mega - Water/Liquid Valve
In this guide, we will learn how to control the flow of liquids such as water, beer, and oil using an Arduino Mega and a solenoid valve. We will cover:
- How to connect a solenoid valve to an Arduino Mega
- How to program Arduino Mega to control the valve

Hardware Preparation
| 1 | × | Arduino Mega | |
| 1 | × | USB 2.0 cable type A/B (for USB-A PC) | |
| 1 | × | USB 2.0 cable type C/B (for USB-C PC) | |
| 1 | × | Relay | |
| 1 | × | Liquid Solenoid Valve | |
| 1 | × | 12V Power Adapter | |
| 1 | × | DC Power Jack | |
| 1 | × | Jumper Wires |
Or you can buy the following kits:
| 1 | × | DIYables Sensor Kit (30 sensors/displays) | |
| 1 | × | DIYables Sensor Kit (18 sensors/displays) |
Additionally, some of these links are for products from our own brand, DIYables .
Overview of Water/Liquid Valve
Pinout

A solenoid valve usually has two ports.
- Connect the red wire to the +12V DC power supply.
- Connect the black wire to the ground (GND) terminal of the DC power supply.
How Water/Liquid Valve works
Normally the valve is closed. When you connect 12V DC to the two terminals, the valve opens and water or other liquids can flow through.
※ NOTE THAT:
Some valves have a seal inside and need a minimum pressure to open after you apply 12 V DC. This pressure can come from the liquid flow. Also, some valves let liquid flow in only one direction.
How to Control Water/Liquid Solenoid Valve
The valve opens when it gets 12V. To control the valve, you need a relay between the Arduino Mega and the valve. The Arduino Mega uses the relay to turn on the solenoid valve. If you don’t know how a relay works, what its pins do, or how to program it, you should read the Arduino Mega - Relay tutorial.
Wiring Diagram

This image is created using Fritzing. Click to enlarge image
Arduino Mega Code
This code will turn the water valve on for five seconds, then turn it off for five seconds.
Detailed Instructions
Follow these steps one by one:
- Connect the Arduino Mega to the water valve as shown in the diagram.
- Connect the Arduino Mega to your computer with a USB cable.
- Open the Arduino IDE on your computer.
- Choose the correct board (Arduino Mega) and the COM port.
- Copy the code and paste it into the Arduino IDE.
- Click the Upload button in the Arduino IDE to send the code to the Arduino Mega.
- Watch the water flow.
Code Explanation
The explanation is in the comments of the Arduino code I provided.