Raspberry Pi - Water/Liquid Valve
This tutorial instructs you how to use a Raspberry Pi and a solenoid valve to control the flow of liquids such as water, beer, and oil. The same principles apply to controlling gas flow.
Hardware Preparation
Or you can buy the following sensor 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
The Water/Liquid Valve Pinout
A Solenoid Valve generally has two terminals:
- The Positive (+) pin (red) should be connected to 12V of a DC power supply
- The Negative (-) pin (black or other) should be connected to the GND of a DC power supply
How Water/Liquid Valve works
Typically, the valve is shut. When 12V DC is supplied to the two terminals, the valve opens and water/liquid can pass through.
※ NOTE THAT:
- A gasket arrangement is present inside, thus requiring a minimum pressure to open the valve after 12V DC is applied. This pressure can be generated by liquid flow.
How to Control Water/Liquid Solenoid Valve using Raspberry Pi
If the valve is supplied with 12V, it will open. In order to control the valve, a relay needs to be used between Raspberry Pi and the valve. Raspberry Pi can manage the solenoid valve through the relay.
If you are not familiar with the relay (pinout, how it works, how to program, etc.), then check out the Raspberry Pi - Relay tutorial for more information.
Wiring Diagram
This image is created using Fritzing. Click to enlarge image
Raspberry Pi Code for Controlling Liquid Valve
The code below turns the water valve ON and OFF every five seconds.
Detailed Instructions
- Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
- Make sure your Raspberry Pi is connected to the same local network as your PC.
- Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
- If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
- Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
- Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
- Create a Python script file valve.py and add the following code:
- Save the file and run the Python script by executing the following command in the terminal:
- Check out the water flow.
The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.
Code Explanation
Check out the line-by-line explanation contained in the comments of the source code!