Solenoid Valve Arduino: NC vs NO, Pressure, MOSFET, Irrigation
Solenoid valve Arduino guide: NC vs NO, minimum pressure, driving it with an IRLZ44N MOSFET or relay, flyback diode, drip irrigation and an ESP32 timer sketch.
Pair a solenoid valve with an Arduino and you can switch water on and off using mains pressure, without needing a pump. A solenoid valve is a valve whose coil pulls a plunger when current flows, opening or closing the path for the water. An Arduino pin can't drive that coil directly; a 12 V valve draws 0.3–0.8 A. That's why you put a MOSFET or relay in between, and always a flyback diode across the coil.
In this article you'll learn the difference between NC and NO valves, why most cheap valves need a minimum pressure and won't work with water from a tank, and the pressure and current values for each valve type. Then you'll see how to wire it with an IRLZ44N MOSFET and a relay, and why the diode is essential. Finally you'll write three complete sketches: drip irrigation based on soil moisture, a protection circuit that shuts the valve on a water leak, and a two-zone ESP32 irrigation timer.
What is a solenoid valve and how does it work?
The cylinder on top of the valve is a coil. When current flows, the coil creates a magnetic field and pulls up the iron core (plunger) inside it; when the current stops, a spring pushes the core back. In direct-acting valves this core closes the water passage itself. This design needs no pressure but is limited to a small orifice, because the coil is only strong enough to open a small hole against the pressure. In pilot-operated (diaphragm) valves the core opens only a tiny pilot hole; the water's own pressure lifts a large rubber diaphragm and opens the main path. That lets a small coil open 1/2 inch lines and larger. The price is this: if there isn't enough pressure to lift the diaphragm, the valve won't open. The vast majority of cheap plastic and brass 12 V valves on the market are of this second type.
| Feature | NC (normally closed) | NO (normally open) |
|---|---|---|
| Without power | Closed, no water flows | Open, water flows |
| With power | Opens | Closes |
| On a power cut | Water stops (fail-safe side) | Water keeps flowing |
| When is the coil on? | Only while water flows | For as long as the water must stay off |
| Typical use | Irrigation, tank filling, water changes | Cooling lines, circuits that must normally flow |
The minimum pressure rule: why won't your valve open?
The label on a pilot-operated valve usually shows a range such as 0.02–0.8 MPa. The lower limit of 0.02 MPa, or 0.2 bar, is the minimum pressure difference needed to lift the diaphragm. Thinking of pressure as a column of water makes it easier: 1 bar is about 10 metres of water, so 0.2 bar means the tank has to be at least 2 metres above the valve. A jerrycan on a table or a rain barrel 1 metre up gives only 0.1 bar; a pilot-operated valve either won't open at all or will let only a trickle through. Mains water is 2–5 bar in most homes, so there's no problem there. If you're going to irrigate by gravity from a tank, choose a direct-acting valve (marked "0 bar" or "zero pressure"), a semi-direct (assisted-lift) valve or a motorised ball valve. Don't forget the upper limit either: if your mains pressure is above the valve's maximum, fit a pressure reducer in front of it.
| Valve type | Minimum pressure | Typical current | Where is it used? |
|---|---|---|---|
| Plastic, pilot-operated 1/2" (12 V DC) | About 0.2 bar | 0.3–0.5 A | Drip irrigation on mains water, aquarium water changes |
| Brass, pilot-operated 1/2"–1" (12 V DC) | 0.2–0.5 bar | 0.4–0.8 A | Garden lines, high flow, hot water |
| Direct-acting, 2–4 mm orifice (12 V DC) | 0 bar | 0.3–1 A | Gravity flow from a tank, drinks machines |
| Semi-direct / assisted-lift (12 V DC) | 0 bar | 0.8–1.5 A | Both low- and high-pressure lines |
| Bistable (latching) valve, 9–12 V pulse | 0–0.5 bar depending on type | Only a 20–50 ms pulse | Battery-powered irrigation timers |
| Garden irrigation valve (24 V AC) | About 1–1.4 bar | 0.2–0.4 A (24 V AC) | Automatic sprinkler systems, driven by a relay |
| Motorised ball valve (alternative) | 0 bar | 0.1–0.2 A, only while moving | Main water shutoff, leak protection |
How do you drive a solenoid valve with a MOSFET?
The cleanest way to drive a 12 V DC valve is an N-channel MOSFET switching the low side. One end of the valve goes to +12 V, the other to the MOSFET's drain (D); the MOSFET's source (S) goes to GND. When the Arduino puts HIGH on the gate (G), the MOSFET conducts and current flows through the coil. The maths is simple: a coil drawing 0.5 A at 12 V has a resistance of 12 / 0.5 = 24 Ω and uses 12 × 0.5 = 6 W. Since the IRLZ44N has an on-resistance of about 0.025 Ω at a 5 V gate voltage, it dissipates 0.5² × 0.025 ≈ 6 mW; no heatsink needed. Put 220 Ω in series with the gate and 10 kΩ between gate and GND: the first limits the pin current, the second stops the valve from opening by itself while the pin floats as the Arduino boots. The ESP32's 3.3 V may not fully turn on an IRLZ44N; with an ESP32, use a MOSFET specified at a 2.5 V gate voltage, such as the AO3400 or IRLB8721. You'll find the MOSFET basics in the Arduino MOSFET guide.
| Connection | Arduino Uno | ESP32 |
|---|---|---|
| MOSFET gate (G), with a 220 Ω series resistor | D9 | GPIO 26 (zone 1), GPIO 27 (zone 2) |
| Between gate and GND | 10 kΩ pull-down resistor | 10 kΩ pull-down resistor |
| MOSFET source (S) | GND (shared with the 12 V adapter's negative) | GND (shared) |
| MOSFET drain (D) | One end of the valve | One end of the valve |
| Other end of the valve | +12 V | +12 V |
| Flyback diode 1N4007 | Cathode (striped end) to +12 V, anode to the drain | Same |
| Recommended MOSFET | IRLZ44N (logic level) | AO3400 or IRLB8721 |
| Drip irrigation: soil sensor and button | A0 and D2 | The sketch uses a timer |
| Water shutoff: water sensor, buzzer, reset button | A1, D8, D3 | Same logic can move to GPIO 34, 25, 33 |
Why is a flyback diode essential?
A coil stores energy. The moment the MOSFET switches off, the current through the coil can't stop instantly; the coil produces a reverse voltage to keep it flowing. Without a diode, that voltage can reach hundreds of volts at the MOSFET's drain and silently kill the MOSFET within the first few switching cycles or a few weeks. A diode connected in reverse across the coil (cathode to +12 V, anode to the MOSFET side) gives this current a short path and holds the voltage about 0.7 V above 12 V. A 1N4007 is enough for valves up to 1 A; for bigger coils use a 1N5408 or a fast Schottky diode. The diode has one side effect: because the current dies away more slowly, the valve closes a few tens of milliseconds later. That doesn't matter for irrigation; in applications that need fast closing, a Zener is added in series with the diode. More about diodes in the what is a diode article.

When does a relay make sense?
A relay fully isolates the valve circuit from the Arduino and can switch both DC and AC valves. You can't drive the 24 V AC valves used in garden irrigation systems with a MOSFET; a relay module is the easiest solution there. The diode on ready-made relay modules only protects the relay's own coil, not the valve's coil. So when you switch a 12 V DC valve with a relay, you still need to add a 1N4007 across the valve. A diode doesn't work on AC valves; to extend contact life you can put a varistor or an RC snubber across the valve. Relay contacts last about 100,000 switching cycles; for an irrigation system that runs twice a day, that's more than a century. For relay module wiring and active-LOW inputs, see the relay module article.

Drip irrigation example: based on soil moisture
In drip irrigation the water comes out slowly and takes time to spread through the soil. That's why the sketch uses two time limits: the valve stays open for at most 10 minutes, then it waits at least 1 hour before the next watering. This way the sensor doesn't mistake soil that hasn't soaked through yet for dry soil and open the valve again. A 2 litre per hour dripper gives about 0.33 litres in 10 minutes; if your plant needs more, lengthen the time. For calibrating the soil moisture sensor and the advantages of a capacitive sensor, have a look at the soil moisture sensor article.
- Connect the valve, filter and drip line to the tap; make sure the arrow on the valve points in the direction of flow.
- Build the MOSFET, the 220 Ω and 10 kΩ resistors and the 1N4007 diode as in the table. Power the Arduino from USB and the valve from a 12 V adapter, and join the two GNDs.
- Upload the sketch and read the soil value in the Serial Monitor. Try the sensor in dry and watered soil to set DRY_LEVEL and WET_LEVEL.
- Press the button and check that the valve opens and closes by itself after 10 minutes.
1// Selenoid vana ile damla sulama: toprak kuruysa vanayı aç, en fazla 10 dk sula, sonra 1 saat bekle
2// Drip irrigation with a solenoid valve: open when the soil is dry, water max 10 min, then wait 1 hour
3const int PIN_VALVE = 9; // IRLZ44N kapısı (220 Ω seri) / IRLZ44N gate (220 Ω series)
4const int PIN_SOIL = A0; // toprak nem sensörü analog çıkışı / soil moisture analog output
5const int PIN_BUTTON = 2; // elle sulama butonu, GND'ye / manual watering button to GND
6
7const int DRY_LEVEL = 600; // bunun üstü kuru (sensöre göre ayarla) / above this is dry (tune for your sensor)
8const int WET_LEVEL = 450; // bunun altına inince erken kapat / close early below this
9const unsigned long WATER_MS = 10UL * 60 * 1000; // en uzun sulama 10 dk / max watering 10 min
10const unsigned long SOAK_MS = 60UL * 60 * 1000; // suyun yayılması için 1 saat / 1 hour soak time
11
12bool valveOpen = false, watered = false;
13unsigned long valveStart = 0, lastWater = 0, lastPrint = 0;
14
15void setValve(bool on) {
16 digitalWrite(PIN_VALVE, on ? HIGH : LOW);
17 valveOpen = on;
18 if (on) valveStart = millis();
19 else { lastWater = millis(); watered = true; }
20 Serial.println(on ? F("Vana acik / valve open") : F("Vana kapali / valve closed"));
21}
22
23void setup() {
24 Serial.begin(9600);
25 pinMode(PIN_VALVE, OUTPUT);
26 digitalWrite(PIN_VALVE, LOW); // açılışta vana kapalı / valve closed at start-up
27 pinMode(PIN_BUTTON, INPUT_PULLUP);
28}
29
30void loop() {
31 int soil = analogRead(PIN_SOIL);
32 bool soakDone = !watered || millis() - lastWater >= SOAK_MS;
33
34 if (!valveOpen) {
35 if ((soil > DRY_LEVEL && soakDone) || digitalRead(PIN_BUTTON) == LOW) setValve(true);
36 } else if (millis() - valveStart >= WATER_MS || soil < WET_LEVEL) {
37 setValve(false); // süre doldu ya da toprak ıslandı / time is up or soil is wet
38 }
39
40 if (millis() - lastPrint >= 2000) {
41 lastPrint = millis();
42 Serial.print(F("Toprak / soil: ")); Serial.println(soil);
43 }
44}
45Water shutoff example: close the valve on a leak
A water sensor placed under a washing machine or water heater can close the valve when the floor gets wet. Using an NC valve has an advantage here: the valve is open only while it has power, so if the power fails or the circuit breaks down, the water is cut off too. The price is that the coil stays energised all day; a 6 W coil uses about 50 kWh a year and, running continuously, can heat up to 60–80 °C. So choose a valve marked 100% ED (continuous duty). If you're building permanent protection on the main supply into your home, a motorised ball valve that only draws current while it moves is a much better choice. Once the sketch detects a leak it keeps the valve closed and won't turn the water back on until the floor is dry and the reset button is pressed.
1// Su kesme: kaçak algılanınca NC vanayı kapat, alarm çal, butona basılana kadar kapalı tut
2// Water shutoff: on a leak close the NC valve, sound the alarm, stay closed until reset
3const int PIN_VALVE = 9; // NC vananın MOSFET'i: HIGH = su akar / NC valve MOSFET: HIGH = water flows
4const int PIN_LEAK = A1; // zemindeki su sensörü (analog) / water sensor on the floor (analog)
5const int PIN_BUZZER = 8; // aktif buzzer / active buzzer
6const int PIN_RESET = 3; // sıfırlama butonu, GND'ye / reset button to GND
7
8const int LEAK_LEVEL = 300; // bunun üstü ıslak zemin / above this = wet floor
9bool leakLatched = false;
10
11void setup() {
12 Serial.begin(9600);
13 pinMode(PIN_VALVE, OUTPUT);
14 pinMode(PIN_BUZZER, OUTPUT);
15 pinMode(PIN_RESET, INPUT_PULLUP);
16 digitalWrite(PIN_VALVE, HIGH); // normalde su açık / water on in normal operation
17}
18
19void loop() {
20 int wet = analogRead(PIN_LEAK);
21
22 if (!leakLatched && wet > LEAK_LEVEL) {
23 leakLatched = true;
24 digitalWrite(PIN_VALVE, LOW); // bobin bırakılır, NC vana kapanır / coil off, NC valve closes
25 Serial.println(F("KACAK! Su kesildi / LEAK! Water shut off"));
26 }
27
28 if (leakLatched) {
29 digitalWrite(PIN_BUZZER, (millis() / 300) % 2); // kesik kesik alarm / beeping alarm
30 if (digitalRead(PIN_RESET) == LOW && wet < LEAK_LEVEL) {
31 leakLatched = false; // zemin kuruysa suyu geri aç / reopen only if the floor is dry
32 digitalWrite(PIN_BUZZER, LOW);
33 digitalWrite(PIN_VALVE, HIGH);
34 Serial.println(F("Sifirlandi, su acik / reset, water on"));
35 }
36 }
37 delay(20);
38}
39Irrigation timer with an ESP32
The ESP32 gets the time from the internet via NTP, so you don't need a separate RTC module. The sketch has a small table in which each line is an irrigation program: zone, hour, minute and duration. Once a minute the sketch checks the clock, starts the matching program and closes the valve when the time is up. Zones never open together; if two valves open at once, the pressure in the line drops and pilot-operated valves may not work properly. The MAX_MINUTES limit stops a wrongly entered duration from watering the garden for hours. Open the ESP32's IP address in your phone's browser and you'll see buttons that run each zone for 5 minutes and stop everything. The time zone is set in the TZ_INFO line; for Central Europe, use the string with the daylight saving rule shown in the comment. More details in the ESP32 NTP time zone article.
1// ESP32 sulama zamanlayıcısı: NTP saati, 2 bölge, günlük programlar, telefondan elle başlatma
2// ESP32 irrigation timer: NTP time, 2 zones, daily programs, manual start from the phone
3#include <WiFi.h>
4#include <WebServer.h>
5#include <time.h>
6
7const char* WIFI_SSID = "WIFI_ADIN";
8const char* WIFI_PASS = "WIFI_SIFREN";
9const char* TZ_INFO = "<+03>-3"; // Türkiye; Orta Avrupa: "CET-1CEST,M3.5.0,M10.5.0/3" / Turkey; Central Europe: see left
10
11const int ZONE_PINS[2] = {26, 27}; // mantık seviyeli MOSFET kapıları / logic-level MOSFET gates
12const int MAX_MINUTES = 30; // güvenlik sınırı / safety limit
13
14struct Program { int zone, hour, minute, minutes; };
15Program programs[] = { // bölge, saat, dakika, süre / zone, hour, minute, duration
16 {0, 6, 0, 15},
17 {1, 6, 20, 10},
18 {0, 19, 30, 15},
19};
20const int PROGRAM_COUNT = sizeof(programs) / sizeof(programs[0]);
21
22WebServer server(80);
23int activeZone = -1;
24unsigned long zoneEnd = 0;
25int lastMinute = -1;
26
27void stopAll() {
28 for (int i = 0; i < 2; i++) digitalWrite(ZONE_PINS[i], LOW);
29 activeZone = -1;
30}
31
32void startZone(int zone, int minutes) {
33 stopAll(); // aynı anda tek bölge: basınç düşmesin / one zone at a time to keep pressure
34 minutes = constrain(minutes, 1, MAX_MINUTES);
35 digitalWrite(ZONE_PINS[zone], HIGH);
36 activeZone = zone;
37 zoneEnd = millis() + (unsigned long)minutes * 60000UL;
38 Serial.printf("Bolge %d acik, %d dk / zone %d on, %d min\n", zone + 1, minutes, zone + 1, minutes);
39}
40
41void handleRoot() {
42 struct tm t;
43 char clock[16] = "--:--";
44 if (getLocalTime(&t, 10)) strftime(clock, sizeof(clock), "%H:%M", &t);
45 String html = "<!DOCTYPE html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width'>"
46 "<title>Sulama</title></head><body style='font-family:sans-serif'><h2>Sulama " + String(clock) + "</h2>"
47 "<p>Aktif bölge: " + String(activeZone < 0 ? 0 : activeZone + 1) + "</p>"
48 "<p><a href='/run?z=0&m=5'><button>Bölge 1 - 5 dk</button></a> "
49 "<a href='/run?z=1&m=5'><button>Bölge 2 - 5 dk</button></a> "
50 "<a href='/stop'><button>Durdur</button></a></p></body></html>";
51 server.send(200, "text/html", html);
52}
53
54void handleRun() {
55 int z = server.arg("z").toInt();
56 int m = server.arg("m").toInt();
57 if (z >= 0 && z < 2) startZone(z, m);
58 server.sendHeader("Location", "/");
59 server.send(303);
60}
61
62void handleStop() {
63 stopAll();
64 server.sendHeader("Location", "/");
65 server.send(303);
66}
67
68void setup() {
69 Serial.begin(115200);
70 for (int i = 0; i < 2; i++) { pinMode(ZONE_PINS[i], OUTPUT); digitalWrite(ZONE_PINS[i], LOW); }
71
72 WiFi.mode(WIFI_STA);
73 WiFi.begin(WIFI_SSID, WIFI_PASS);
74 while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print('.'); }
75 Serial.print(F("\nIP: ")); Serial.println(WiFi.localIP());
76
77 configTzTime(TZ_INFO, "pool.ntp.org", "time.google.com");
78
79 server.on("/", handleRoot);
80 server.on("/run", handleRun);
81 server.on("/stop", handleStop);
82 server.begin();
83}
84
85void loop() {
86 server.handleClient();
87
88 if (activeZone >= 0 && (long)(millis() - zoneEnd) >= 0) stopAll(); // süre doldu / time is up
89
90 struct tm t;
91 if (!getLocalTime(&t, 10)) return; // saat henüz yok / no time yet
92 if (t.tm_min == lastMinute) return; // her dakika bir kez bak / check once per minute
93 lastMinute = t.tm_min;
94
95 for (int i = 0; i < PROGRAM_COUNT; i++) {
96 if (programs[i].hour == t.tm_hour && programs[i].minute == t.tm_min) startZone(programs[i].zone, programs[i].minutes);
97 }
98}
99Common problems and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Valve clicks but no water comes out | Pressure too low for a pilot-operated valve | Use a direct-acting or motorised valve, raise the tank |
| Valve drips when closed | Flow direction reversed or sand in the diaphragm | Fit it according to the arrow, open the valve and clean the diaphragm, add a filter |
| MOSFET died after a few days | No flyback diode, or it's reversed | Connect the 1N4007 across the valve with the cathode to +12 V |
| Valve opens for a moment when the Arduino boots | No pull-down on the gate | Add 10 kΩ between gate and GND |
| Valve opens weakly or not at all with an ESP32 | MOSFET doesn't fully turn on at 3.3 V | Use an AO3400 or IRLB8721, or add a transistor driver |
| Arduino resets when the valve closes | Shared supply and noise | Power the valve from its own adapter, add the diode, join GND at a single point |
Project ideas
- Idea: A single-valve drip irrigation system with a soil sensor for pots; the version with a Wi-Fi panel is in the ESP32 automatic watering article.
- Idea: Automate aquarium water changes; use a mini water pump to drain, a direct-acting valve to refill and a float level switch for the level.
- Idea: Add a water flow sensor after the valve to measure the water used for garden irrigation and show the litres on a display.
- Idea: Build a timer that skips watering if it has rained; combine the ESP32 sketch with a rain sensor.
- Idea: Add Telegram notifications to the leak protection circuit so a message arrives on your phone when the floor gets wet.
A solenoid valve is one of the most practical parts for connecting Arduino projects to real plumbing; choose the right valve type, wire the MOSFET and diode correctly, and it will run for years without trouble. If you want to see the parts of an irrigation circuit step by step, you can look at the circuit diagram and code of the "Smart Irrigation Station" project in the BlueGrays app, and the "Lighting 220V Bulb with Push Button" project for relay load control.
Frequently asked questions
Can a solenoid valve be connected directly to an Arduino?
No. A 12 V solenoid valve draws 0.3–0.8 A, while an Arduino pin can supply only about 20 mA. Drive the valve through a logic-level MOSFET such as the IRLZ44N or a relay, and put a flyback diode across the coil.
What is the difference between NC and NO solenoid valves?
An NC (normally closed) valve is closed without power and opens when you apply current; if the power fails, the water stops. An NO (normally open) valve is open without power and closes when you apply current. Irrigation and tank filling almost always use NC valves.
Why doesn't my solenoid valve work with a water tank?
Most cheap valves are pilot-operated and need at least 0.2 bar to open, which is about 2 metres of water height. A tank 1 metre up gives only 0.1 bar. For gravity flow from a tank, use a direct-acting valve rated for 0 bar or a motorised ball valve.
Which diode should I use for a solenoid valve?
For 12 V valves up to 1 A, a 1N4007 is enough. The diode goes in reverse across the coil: the striped end (cathode) to +12 V, the other end to the MOSFET or relay side. For larger coils you can use a 1N5408 or a Schottky diode.
Does a solenoid valve get hot if it stays on?
Yes, a continuously energised coil can reach 60–80 °C, which is normal for valves rated for continuous duty. Choose a valve marked 100% ED and mount it where air can circulate. For jobs where it has to stay open or closed for long periods, a latching valve or a motorised ball valve uses less energy.
How do I control a solenoid valve with an ESP32?
Use a MOSFET that fully turns on with the ESP32's 3.3 V output, such as the AO3400 or IRLB8721, power the valve from a 12 V adapter and join the GNDs. With a sketch that takes the time from NTP, you can set up daily watering programs and switch the valve from your phone. For 24 V AC garden valves, use a relay instead of a MOSFET.
Projects to build after reading this
See all projects
LED Control with a Push Button (Push)
Just like a doorbell: the light stays on as long as you press, and goes off when you let go.

Using a Buzzer
Ever wondered how a doorbell or an alarm makes its sound? The Arduino makes a small buzzer beep at short intervals: beep, pause, beep, pause.

Temperature and Humidity with DHT11
How warm is your room, and is the air humid or dry? The DHT11 sensor measures temperature and humidity, and the Arduino writes the values on a two-line LCD screen, refreshing every couple of seconds.

Lighting 220V Bulb with Push Button
As long as you hold the button, a real 220-volt bulb stays lit, and it goes out the moment you let go.

Lighting 220V Bulb with Button (On-Off)
Want to switch a real household bulb on and off with a tiny button? Each time you press the button, the Arduino flips a relay and the bulb lights up; press again and it goes off.

Smart Irrigation Station
A gardener that waters your plants on its own, so they don't dry out while you're on vacation.

Real-Time Clock from the Internet via ESP32 NTP
The ESP32 connects to Wi-Fi and fetches the real time from NTP (Network Time Protocol) servers with millisecond precision. configTzTime() applies the Turkey time zone (TRT, UTC+3) automatically, and in countries with daylight saving time the DST switch is handled by a POSIX TZ string. The time is printed both to the Serial Monitor and to an optional I2C LCD.
More articles
BlueGrays app
Build this circuit step by step on your phone
Wiring diagram, code and parts list on one screen. 500+ Arduino, ESP32, ESP8266, Pico, mBot and micro:bit projects ready to build.
Scan with your phone
Point your camera at the code and your phone's app store opens.
or open the store

