DIY Automatic Water Dispenser with Arduino

DIY Automatic Water Dispenser with Arduino | Kids Maker Project | MakeMindz
What are we building?

A Smart Dispenser That Knows When You're Thirsty 🚰

Have you ever seen those touchless hand-wash stations at hospitals or malls that automatically spray soap or water? We're going to build one! An ultrasonic sensor watches for your hand. The moment it gets close enough, Arduino activates a relay switch which powers a mini water pump — and water flows! No buttons, no touching, completely automatic.

The HC-SR04 sensor sees like a bat! 🦇

Bats navigate in total darkness using echolocation — they send out a sound pulse and listen for the echo. Our HC-SR04 sensor works exactly the same way! It shoots out an ultrasonic sound wave (too high-pitched for humans to hear), and when the wave bounces back from your hand, the sensor measures how long the echo took to return. The faster the echo, the closer your hand is. That's how it "sees" without eyes!

40kHz
Ultrasonic frequency
2–400cm
Detection range
±3mm
Accuracy
15cm
Our trigger distance
🌟 Real world link: Touchless faucets in airports, hospital hand sanitiser dispensers, and parking sensors in cars all use ultrasonic distance sensing. You're building the same technology used in professional products!
The chain of events

From Hand Wave to Water Flow 💧

Seven things happen in about 30 milliseconds every time you put your hand under the sensor!

1
🤚
Hand moves close
You hold your hand or cup within ~15 cm of the sensor.
2
📡
Sensor fires a pulse
Arduino sends a 10µs HIGH pulse to TRIG pin — the sensor fires an ultrasonic burst.
3
🔊
Sound bounces back
The 40kHz pulse hits your hand and reflects back to the sensor's receiver (ECHO).
4
⏱️
Time is measured
Arduino measures how many microseconds ECHO pin stays HIGH — that's the travel time.
5
🧮
Maths! Distance = time ÷ 58
Speed of sound + round trip gives: distance in cm = pulse duration ÷ 58.
6
Relay clicks ON
If distance < 15cm, Arduino sends LOW to relay IN pin, which closes the relay switch.
7
💧
Pump sprays water!
Relay completes the pump circuit — pump activates and water flows through the nozzle!
🔑 Why a relay? Arduino's pins output only 5V at 40mA — far too weak to run a water pump directly. A relay is an electrically-controlled switch: Arduino's tiny 5V signal controls a separate circuit that can switch high-power devices like motors, pumps, or lights. It's like using a small key to open a heavy door!
Shopping list

Everything You Need to Collect 🛒

8 components, all available locally or online. Total under ₹500!

🤖
Arduino UNO
The brain. Reads the sensor, calculates distance, and switches the relay on/off.
Qty: 1  |  ~₹250
📡
HC-SR04 Ultrasonic Sensor
The eyes. Has 4 pins: VCC, GND, TRIG (trigger), ECHO. Detects objects from 2–400 cm away.
Qty: 1  |  ~₹40
5V Relay Module (1-channel)
The switch. Receives a LOW signal from Arduino and closes/opens the pump's power circuit. Choose an active-LOW relay module.
Qty: 1  |  ~₹40
💧
Mini Submersible DC Pump (3–6V)
The muscle. A tiny water pump that sits inside your water container and pumps water through the tube to the nozzle.
Qty: 1  |  ~₹60
🔋
4× AA Battery Pack (6V) or USB Power Bank
Powers the pump separately from Arduino. A 4×AA pack gives 6V, enough for most mini pumps. Arduino can be USB-powered.
Qty: 1  |  ~₹30
🧵
Silicone / Rubber Tubing (5mm ID)
Carries water from the pump to the dispensing nozzle. Buy 30–50 cm length. Must fit tightly over the pump outlet nipple.
Qty: 50 cm  |  ~₹20
🧱
Breadboard + Jumper Wires
For all the control circuit connections — sensor pins, relay module, Arduino. No soldering needed!
Qty: 1 set  |  ~₹60
🪣
Small Container / Bottle
A 500ml–1L plastic bottle or container to hold the water. The pump sits inside this. Cut a hole in the lid for the pump wires and tube.
Qty: 1  |  free / ₹0
⚠️ Pump power matters! Never power the water pump from Arduino's 5V pin — it will overload the board and cause brownouts. The pump must have its own battery pack or power supply. They share only a common GND with Arduino.
Step-by-step build

Build It Step by Step! 🔨

Follow every step in order. Always disconnect power before adding or changing any wire.

1
Understand the HC-SR04 Sensor Pins
The HC-SR04 has 4 pins and two circular discs (one transmitter, one receiver). Before wiring, know what each pin does so you connect them right first time.
HC-SR04 Pin Reference
PinNameConnect toWhat it does
VCCPowerArduino 5VPowers the sensor (5V, 15mA)
GNDGroundArduino GNDNegative power connection
TRIGTriggerArduino Pin 9Send a 10µs pulse here to fire sensor
ECHOEchoArduino Pin 10Goes HIGH for the duration of the return pulse
💡 Important: TRIG is an input to the sensor (Arduino sends). ECHO is an output from the sensor (Arduino receives). Never swap them — you won't damage anything, but it simply won't work!
2
Wire the HC-SR04 to Arduino
Use 4 jumper wires to connect the sensor to the breadboard and Arduino. Keep these connections solid — a loose sensor wire is the most common reason the project doesn't work.
Sensor wiring
HC-SR04 PinWire ColorArduino Pin
VCCRed5V
GNDBlackGND
TRIGYellowDigital Pin 9
ECHOBlueDigital Pin 10
3
Understand the Relay Module
Your 5V relay module has two sections: the control side (talks to Arduino) and the load side (switches the pump). Look at your relay carefully and find these terminals.
Relay module pin map
Terminal / PinSidePurpose
VCCControl side5V power for the relay coil
GNDControl sideGround connection
INControl sideSignal from Arduino — LOW = relay ON (active-LOW!)
COMLoad sideCommon terminal — one pump wire connects here
NOLoad sideNormally Open — other pump wire connects here. Circuit closes when relay activates.
NCLoad sideNormally Closed — we don't use this pin
🔑 Active-LOW relay: Most relay modules are "active-LOW" — meaning the relay turns ON when you send LOW (0V) to the IN pin, and turns OFF with HIGH (5V). Our code uses this! Sending digitalWrite(RELAY_PIN, LOW) activates the pump.
4
Wire the Relay Module to Arduino
Connect the relay's control side to Arduino. These are low-power signal connections — just 3 wires.
Relay → Arduino connections
Relay PinWire ColorArduino
VCCRed5V
GNDBlackGND
INGreenDigital Pin 7
5
Connect the Water Pump to the Relay Load Side
The pump runs on its own battery pack (6V / 4×AA). The relay acts as the switch — it connects or disconnects the battery pack's positive terminal to the pump. This is the only part where higher current flows.
Pump power wiring (through relay)
FromToWire
Battery pack (+)Relay COM terminalRed
Relay NO terminalPump wire (+)Orange
Pump wire (–)Battery pack (–)Black
Battery pack (–)Arduino GNDBlack (shared GND!)
⚠️ Shared GND is essential! The battery pack's negative terminal MUST connect to Arduino's GND. Without a common ground, the relay signal doesn't have a reference point and the system won't work reliably.
6
Set Up the Water System
Now the fun physical build — setting up the actual water container, pump, and nozzle so water flows cleanly to where you want it!
Water system assembly

🪣 Container prep: Fill your plastic bottle or container with clean water. If using a bottle, make a small hole in the lid for the pump's wires and tube to pass through.

💧 Place the pump: Submerge the mini pump fully in the water. The pump must be completely underwater to work — it's a submersible pump! Run the wires up through the lid hole.

🧵 Attach the tube: Slide one end of the silicone tube tightly over the pump's outlet nipple. No glue needed — a snug fit holds it. Run the other end to where you want water to come out (position it over a cup or bowl).

📡 Position the sensor: Mount the HC-SR04 sensor facing downward toward where you'll place your hand/cup. Fix it 20–25 cm above the dispensing point so there's room for the cup below the 15 cm trigger zone.

💡 Test the pump first! Before wiring through the relay, connect the pump directly to the battery pack briefly to confirm it works and pumps water. If it doesn't spin, check that it's fully submerged.
7
Upload the Code and Test!
Connect Arduino to your computer via USB, open Arduino IDE, paste the code from the section below, select Arduino UNO and the correct COM port, and click Upload. Then open Serial Monitor (9600 baud) to watch live distance readings!
✅ Test checklist: Serial Monitor shows distance values ✓ | Distance decreases when you move hand closer ✓ | "Hand detected! Pump ON" message appears ✓ | Pump activates when hand is within 15 cm ✓ | Pump stops when hand moves away ✓

Two Modes Explained 🎛️

🤚
Auto-Dispense Mode (default)
Pump runs as long as your hand stays within 15 cm. Remove hand → pump stops instantly. Perfect for filling glasses or washing hands.
⏱️
Timed Dispense Mode (in code)
Once hand is detected, pump runs for exactly 2 seconds then stops — even if hand stays. Great for dispensing a fixed amount of water each time.
Full wiring diagram

The Complete Circuit 🔌

Two separate power systems (logic + pump) connected through a relay switch, sharing a common ground. Study this before you wire anything!

Automatic Water Dispenser — Full Circuit Arduino UNO + HC-SR04 + Relay + Pump
Automatic Water Dispenser — Complete Circuit Diagram ARDUINO UNO 5V GND GND D9 D10 D7 MCU USB HC-SR04 TX RX VCC GND TRIG ECHO RELAY MODULE VCC GND IN COIL LED COM NO NC load terminals MINI PUMP M+ M– 4×AA BATTERY + + + + 6V+ GND WIRE LEGEND Red — 5V / power positive Black — Ground (GND) Yellow — D9 TRIG signal Cyan — D10 ECHO signal Green — D7 Relay IN Orange — Relay NO → Pump Dashed — shared 5V / GND
FromPinToPin / TerminalColor
Arduino5VHC-SR04VCCRed
ArduinoGNDHC-SR04GNDBlack
ArduinoDigital 9HC-SR04TRIGYellow
ArduinoDigital 10HC-SR04ECHOCyan / Blue
Arduino5VRelay moduleVCCRed
ArduinoGNDRelay moduleGNDBlack
ArduinoDigital 7Relay moduleIN signalGreen
Battery 6V (+)PositiveRelayCOM terminalRed (dashed)
RelayNO terminalMini PumpPositive (+)Orange
Mini PumpNegative (–)Battery 6VGND (–)Black
Battery 6VGND (–)ArduinoGND (shared!)Black (dashed)
Arduino code

The Complete Arduino Code 💻

No extra libraries needed — just paste this into Arduino IDE and upload! Every section is fully commented.

Arduino C++ — Water Dispenser v1.0
// ╔═══════════════════════════════════════════════════════════╗
// ║   DIY AUTOMATIC WATER DISPENSER — MakeMindz              ║
// ║   Sensor: HC-SR04 Ultrasonic on pins 9, 10               ║
// ║   Relay:  5V module on pin 7 (active-LOW)                ║
// ║   No external libraries needed!                          ║
// ╚═══════════════════════════════════════════════════════════╝

// ── Pin definitions ──────────────────────────────────────────
const int TRIG_PIN   = 9;    // HC-SR04 trigger — sends the pulse
const int ECHO_PIN   = 10;   // HC-SR04 echo   — receives the bounce
const int RELAY_PIN  = 7;    // Relay IN pin   — LOW = pump ON

// ── Dispenser settings ─────────────────────────────────────
//   Adjust TRIGGER_DISTANCE to change sensitivity.
//   Adjust PUMP_ON_TIME for timed-mode dispense amount.       
const int  TRIGGER_DISTANCE = 15;    // cm — hand must be closer than this
const long PUMP_ON_TIME    = 2000;   // ms — for timed mode (2 seconds)
const bool TIMED_MODE      = false;  // false = continuous, true = timed burst

// ── Internal state ────────────────────────────────────────
long pumpStartTime = 0;
bool pumpRunning   = false;

// ── setup() ───────────────────────────────────────────────
void setup() {
  Serial.begin(9600);
  Serial.println("💧 MakeMindz Water Dispenser — Ready!");
  Serial.println(TIMED_MODE
    ? "Mode: TIMED (2 second burst per detection)"
    : "Mode: CONTINUOUS (runs while hand is present)");

  pinMode(TRIG_PIN,  OUTPUT);
  pinMode(ECHO_PIN,  INPUT);
  pinMode(RELAY_PIN, OUTPUT);

  // Make sure pump is OFF at startup
  // Active-LOW relay: HIGH = off, LOW = on
  digitalWrite(RELAY_PIN, HIGH);
  delay(500);
  Serial.println("Hold your hand within 15cm to dispense water!");
}

// ── loop() ────────────────────────────────────────────────
void loop() {

  // Step 1: Measure the distance
  long distanceCm = measureDistance();

  // Step 2: Print to Serial Monitor for debugging
  Serial.print("Distance: ");
  Serial.print(distanceCm);
  Serial.print(" cm  |  Pump: ");

  // Step 3: Decide what to do based on distance
  if (distanceCm > 0 && distanceCm < TRIGGER_DISTANCE) {

    // ── Hand detected! ────────────────────────────────────
    if (TIMED_MODE) {
      // TIMED MODE: Run pump once for PUMP_ON_TIME milliseconds
      if (!pumpRunning) {
        pumpON();
        pumpStartTime = millis();
        pumpRunning = true;
      }
      // Auto-stop after PUMP_ON_TIME
      if (millis() - pumpStartTime >= PUMP_ON_TIME) {
        pumpOFF();
        pumpRunning = false;
        Serial.println("✅ Timed dispense complete!");
        delay(1000);  // Wait 1s before allowing another dispense
      }

    } else {
      // CONTINUOUS MODE: Pump stays on while hand is close
      pumpON();
      Serial.println("ON  💧");
    }

  } else {

    // ── No hand detected ──────────────────────────────────
    pumpOFF();
    pumpRunning = false;
    Serial.println("OFF ⬜");
  }

  delay(100);  // Check 10 times per second
}

// ── FUNCTION: measureDistance ──────────────────────────────
//   Sends a 10µs pulse to TRIG, measures ECHO duration,
//   converts to centimetres using speed of sound formula.     
long measureDistance() {

  // 1. Clear the trigger pin
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);

  // 2. Send a 10-microsecond HIGH pulse to fire the sensor
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // 3. Measure how long ECHO pin stays HIGH (in microseconds)
  // pulseIn() waits for the pin to go HIGH, then times it
  long duration = pulseIn(ECHO_PIN, HIGH, 30000);
  //                                         ^^^^^ timeout: 30ms

  // 4. Convert time to distance
  // Speed of sound = 343 m/s = 0.0343 cm/µs
  // Distance = (duration / 2) × 0.0343
  // Simplified: distance = duration / 58.2 ≈ duration / 58
  if (duration == 0) return 999;  // Timeout — nothing in range
  return duration / 58;
}

// ── FUNCTION: pumpON ─────────────────────────────────────
//   Active-LOW relay: send LOW signal to activate             
void pumpON() {
  digitalWrite(RELAY_PIN, LOW);   // LOW = relay energised = pump ON
}

// ── FUNCTION: pumpOFF ─────────────────────────────────────
void pumpOFF() {
  digitalWrite(RELAY_PIN, HIGH);  // HIGH = relay off = pump OFF
}

What Each Part of the Code Does 🔍

pulseIn()
The most important function
pulseIn(ECHO_PIN, HIGH) waits for the ECHO pin to go HIGH, then counts microseconds until it goes LOW again. That duration is the round-trip sound travel time. The 30000 timeout prevents the code from freezing if nothing is detected.
Distance Formula
Why divide by 58?
Sound travels 343 m/s = 0.0343 cm per microsecond. The echo is a round trip (to object AND back), so divide by 2. Combined: distance = duration × 0.0343 ÷ 2 = duration ÷ 58.2. Rounded to ÷58 for simplicity!
Active-LOW Relay
Why LOW turns pump ON?
Most relay modules use active-LOW logic for safety — the relay stays OFF by default (when signal is HIGH or unconnected). Sending LOW energises the relay coil, closing the switch. This prevents accidental pump activation on power-up!
TIMED_MODE flag
How to switch between modes
Change TIMED_MODE = false to true to switch from continuous dispensing to a fixed 2-second burst per detection. millis() tracks elapsed time without blocking the rest of the code — much better than delay(2000)!
Timeout guard
What happens when nothing is in range?
If no echo returns within 30ms, pulseIn() returns 0. We catch this with if (duration == 0) return 999 — returning a huge distance value (999 cm) that will never trigger the pump. Prevents false activations!
delayMicroseconds()
Why 10 microseconds exactly?
The HC-SR04 datasheet requires a minimum 10µs HIGH pulse on TRIG to trigger one ultrasonic burst. Too short and the sensor won't fire. We also clear the pin to LOW first with a 2µs delay to ensure a clean signal edge.
What you're really learning

Six Engineering Skills in One Build 🎓

This project packs in concepts used in IoT devices, medical equipment, smart home systems and industrial automation!

🦇
Ultrasonic Distance Sensing
The same echolocation technology used in robot obstacle avoidance, parking sensors, bat navigation, and submarine sonar systems.
Relay Switching
Controlling high-power loads with low-power signals — used in home automation, industrial PLCs, smart switches, and every power-control system.
⏱️
Non-Blocking Timers
Using millis() for timed events without freezing the program — the core skill behind all real-time embedded systems and multitasking microcontrollers.
🔊
Pulse Timing
Generating precise microsecond-level signals with delayMicroseconds() and pulseIn() — essential for communicating with sensors that use timing protocols.
⚙️
Dual Power Rail Design
Separating logic (5V Arduino) and load (6V pump battery) with a shared GND — the standard power architecture used in every robot, drone, and industrial controller.
🧼
Touchless Interface Design
Proximity-triggered actions without physical contact — the principle behind hospital hand sanitisers, public faucets, contactless payment readers, and gesture-controlled devices.
Safety first

Water + Electricity — Stay Safe! 🛡️

Water and electricity can be dangerous together. Follow these rules every single time!

👨‍👩‍👧
Adult present always
Build and test this project only with a parent or teacher nearby. Never handle any electrical connections alone when water is nearby.
💧🚫⚡
Keep water away from electronics
Arduino, relay module, and breadboard must NEVER get wet. Keep all electronics at least 30 cm away from the water container. Place them on a raised, dry surface.
🔌
Use only low-voltage batteries
This project uses batteries or USB power (5–6V, safe). NEVER connect to mains electricity (AC wall power at 230V India). Low-voltage DC is safe; mains AC is not for this project.
🪣
Use a leak-proof container
Seal any holes in your water container with waterproof silicone sealant. A leak onto the electronics can cause short circuits and damage the board.
🔋
Check battery connections
Make sure battery pack wires are firmly connected and insulated. Exposed wires near water can short-circuit. Use electrical tape on any bare wire ends.
🛑
Power off before any changes
Always disconnect the battery pack AND USB cable before changing any wire connection. Never rewire while power is on — even low-voltage connections can spark on short circuits.
Fix it yourself

Something Not Working? Let's Fix It! 🔧

📡
Serial Monitor shows "999" or no distance change
The sensor isn't receiving echoes. Check: (1) TRIG → Pin 9 and ECHO → Pin 10 — not swapped? (2) VCC connected to 5V? (3) Point the sensor at a solid wall within 50 cm to test — it may not detect fabric/cloth well. (4) Try adding a 10kΩ resistor between ECHO pin and GND as a pull-down.
💧
Pump doesn't turn on even when distance is correct
Check: (1) Is your relay active-LOW? Try connecting relay IN directly to GND and listen for a click — if it clicks, the relay works. (2) Battery pack connected to relay COM? (3) Pump wire connected to relay NO (Normally Open)? (4) Open Serial Monitor — does it print "Pump: ON 💧"? If yes, the code is right and the problem is wiring.
🔄
Pump turns on and off rapidly (chattering)
The distance reading is hovering right at 15 cm — the sensor is reading 14, then 16, then 14 again. Increase TRIGGER_DISTANCE to 20 cm, or add a small dead-band in the code: require distance to be <13 cm to turn ON and >18 cm to turn OFF (hysteresis). This is standard in all real sensor control systems!
💧🌊
Pump is very weak — water barely flows
Power issue! (1) Check battery pack voltage with a multimeter — 4 fresh AAs should give ~6V. Weak batteries give only 4–4.5V and cut pump power significantly. (2) Is the pump fully submerged? It must be underwater to prime. (3) Is the output tube too long or kinked? Long tubes add back-pressure. Try a shorter tube first.
😵
Arduino resets or freezes when pump activates
Voltage spike! When the pump motor starts, it draws a surge of current that briefly drops the voltage and resets Arduino. Fix: (1) Add a 100µF capacitor across the battery pack terminals (+ to +, – to –). This absorbs the startup spike. (2) Make sure the relay is properly isolating the pump from the Arduino circuit. (3) Use a flyback diode (1N4007) across the pump terminals to suppress voltage spikes.
📟
Distance reads correctly but relay doesn't click
The relay isn't receiving the signal. Check: (1) Relay IN pin connected to Arduino D7? (2) Relay VCC connected to Arduino 5V? (3) The relay coil LED — does it flash when signal is sent? (4) Add Serial.println("Sending LOW to relay") just before pumpON() to confirm code reaches that line. (5) Try a fresh relay module — coils can burn out.
Level up!

Make It Even Smarter 🚀

Once your basic dispenser works perfectly, try these exciting upgrades!

📊
Water Level Monitor
Add a second HC-SR04 inside the tank pointing down at the water. When water drops below 5 cm, an LED or buzzer alerts you to refill!
📺
LCD Display
Add a 16×2 LCD screen showing "Place cup to dispense", current distance, water level percentage, and how many cups have been served!
🌡️
Water Temperature Sensor
Add a DS18B20 waterproof temperature sensor in the tank to display hot/cold water temperature on the LCD. Perfect for a smart chai dispenser!
📱
IoT Water Counter
Add ESP8266 WiFi and log every dispense to a Google Sheet or Blynk dashboard. Track daily water consumption from your phone!
🔊
Sound + Light Feedback
Add a buzzer that beeps once when dispensing starts and twice when complete. Add blue LEDs around the nozzle that glow while water flows — looks amazing in the dark!
Plant Auto-Waterer
Replace the ultrasonic sensor with a soil moisture sensor! Now the pump waters your plants automatically when the soil gets too dry. Same relay + pump circuit!
💧 You Built a Touchless Smart Dispenser!

Ultrasonic sensing, relay switching, dual power rails, and non-blocking timers — you just built something that belongs in a smart home catalogue. What will you make next?

⚡ MakeMindz

Sparking curiosity, one circuit at a time — from Coimbatore to the world.

© 2025 MakeMindz · makemindz.com · Educational maker content for kids everywhere

Comments

Product Cards
Buddy Bot eBook
⭐ New 2026 Release
Build Your
Own Robot!
3D design, wiring &
Arduino coding.
Young inventors love it!
🖨️
3D Print
All parts
Wire it
Circuit guide
💻
Code it
Arduino IDE
🤖
Watch it
Walk & react
📋 Your Details
Enter your name
Valid 10-digit no.
Enter a valid email
Special Website Offer
₹499 300
🌍 International: $5 USD
One-time · Instant digital delivery
🔒 Secured by Razorpay · Your data is safe
📄 Download Free Sample Copy
🔒 Secured by Razorpay · Your data is safe
🍓
Raspberry Pi Pico Mastery
21 Projects
⚡ Launch Price — 80% OFF
Learn Pico
Build 21 Projects!
MicroPython · Wokwi
IoT · Certificate
Perfect for beginners!
🖥️
Wokwi
No hardware
🐍
MicroPy
From zero
🔨
21 Projects
IoT + sensors
📄
Certificate
Verified cert
📋 Your Details
Enter your name
Valid 10-digit no.
Enter a valid email
Special Launch Offer
₹999 200 80% OFF
🌍 International: $5 USD
One-time · Lifetime access · No subscription
🔒 Secured by Razorpay · UPI · Cards · NetBanking
🎉

You're in!

Payment successful! Your Buddy Bot eBook is ready. Time to build!

📖 Access Your eBook Now
🎉

Enrolled!

Payment successful! Lifetime access to all 21 Pico Projects is yours!

🍓 Go to My Course