Electronics and Communication Engineering Diploma project

Arduino Water Level Controller with Ultrasonic Sensor

An Arduino water level controller measures the water level in a tank and switches a pump on and off by itself. In this project an HC-SR04 ultrasonic sensor on the tank lid measures the distance to the water, and an Arduino Uno switches the pump through a relay module.

The pump starts at 25 % and stops at 90 %. A sensor fault or an overlong pump run stops it. The model runs on 12 V DC, so it is safe to build on a bench.

Aim of the project

To build and test a controller that measures tank level without touching the water, starts and stops a pump at two different levels (hysteresis), and shuts the pump off with a fault light if the sensor fails or the pump runs too long.

Block diagram of the Arduino water level controller

The 12 V adapter powers the Arduino and the pump circuit. The Arduino reads the sensor and drives the relay and two LEDs. The relay’s normally open (NO) contact switches 12 V to the pump, which lifts water from the sump to the overhead tank.

12 V DC adapter2 A Status LEDsGreen: pump, Red: fault Arduino Uno R3ATmega328P, 16 MHz Relay module5 V coil, 10 A contacts Pump in sump12 V DC HC-SR04 Overhead tank Trig D9, Echo D10 12 V to COM 12 V via NO contact 12 V DC D5, D6 D7 OFF 90 %ON 25 % PowerSignalWaterUltrasound
Block diagram of the Arduino water level controller: power (red), control signals (navy), sound pulses (teal) and water flow (blue).

Working principle

Measuring distance with ultrasound

The Arduino sends a 10 µs pulse to the sensor’s Trig pin. The HC-SR04 then sends out eight 40 kHz sound pulses and sets its Echo pin HIGH until the reflection comes back from the water surface. The width of the Echo pulse is the round-trip travel time of the sound.

Sound travels down and back, so the distance is half the path:

distance (cm) = echo time (µs) × 0.0343 / 2

Here 0.0343 cm/µs is the speed of sound in air at 20 °C (343 m/s). The HC-SR04 datasheet gives the same rule in short form: echo time in µs divided by 58 gives cm.

From distance to level

A full tank gives a short distance and an empty tank a long one. In the code, EMPTY_CM is the distance from the sensor to the tank bottom and FULL_CM the distance to the water at 100 %.

level (%) = (EMPTY_CM - distance) × 100 / (EMPTY_CM - FULL_CM)

Keep FULL_CM well above the sensor’s 2 cm minimum range; the default is 8 cm.

Hysteresis: two switching levels

Between 25 % and 90 % the pump keeps its last state. With one set point, surface ripples would switch it on and off rapidly and wear the relay and motor. It is the start and stop idea of a seal-in circuit in PLC ladder logic.

Driving the pump

An I/O pin is rated for 20 mA, but the relay coil needs about 70 mA (0.36 W at 5 V). The module has a transistor working as a switch to drive the coil, plus a flyback diode that clamps the voltage spike when the coil turns off.

Protection logic

A missing echo, or a distance longer than the tank, is a sensor fault. If the tank has not reached 90 % within MAX_RUN_MS, the sump is probably empty or the pipe blocked. Both stop the pump and latch the red LED until you press RESET on the Uno.

Circuit connections

FromToNote
HC-SR04 VCC, GNDUno 5V, GNDSensor supply
HC-SR04 TrigUno D910 µs trigger pulse
HC-SR04 EchoUno D10Echo pulse, 5 V logic
Relay module VCC, GNDUno 5V, GNDCoil supply
Relay module INUno D7Control input
Green LED + 220 ΩUno D5 to GNDPump running
Red LED + 220 ΩUno D6 to GNDFault
Adapter 12 VUno barrel jackArduino supply
Adapter +12 V, through fuseRelay COMPump supply
Relay NOPump +Switched 12 V
Pump -Adapter 0 VReturn

With a red LED dropping about 2 V, Ohm’s law gives (5 - 2) / 220, about 14 mA, inside the 20 mA pin rating.

Step-by-step build

  1. Fit the HC-SR04 in the middle of the tank lid, facing straight down, with holes cut for both transducers.
  2. Measure the sensor face to tank bottom distance. This is EMPTY_CM.
  3. Wire the sensor, relay module and LEDs as in the table.
  4. With the pump unpowered, upload the sketch below by USB with your EMPTY_CM.
  5. Open the Serial Monitor at 9600 baud. Move a flat board under the sensor and check the distance and the relay clicks.
  6. Put the pump in the sump and clamp the tube from its outlet to the top of the overhead tank.
  7. Wire the fuse, relay COM and NO, and the pump. Mount the electronics above the water.
  8. Power up from the 12 V adapter and run the tests below.

Arduino code

No libraries are needed. Set RELAY_ACTIVE_LOW to match your module; many switch on when IN is LOW.

// Arduino water level controller: HC-SR04 + relay + pump
const byte TRIG_PIN  = 9;
const byte ECHO_PIN  = 10;
const byte RELAY_PIN = 7;
const byte PUMP_LED  = 5;
const byte FAULT_LED = 6;

const bool  RELAY_ACTIVE_LOW = true;   // true if the relay turns on with IN = LOW
const float EMPTY_CM  = 30.0;          // sensor face to tank bottom
const float FULL_CM   = 8.0;           // sensor face to water at 100 %
const float START_PCT = 25.0;          // pump ON at or below this level
const float STOP_PCT  = 90.0;          // pump OFF at or above this level
const unsigned long MAX_RUN_MS = 120000UL;   // 2 min, set to 1.5 x measured fill time
const unsigned long ECHO_TIMEOUT_US = 30000UL;

bool pumpOn = false;
bool fault = false;
unsigned long pumpStart = 0;

void setPump(bool on) {
  digitalWrite(RELAY_PIN, (on != RELAY_ACTIVE_LOW) ? HIGH : LOW);
  digitalWrite(PUMP_LED, on ? HIGH : LOW);
  if (on && !pumpOn) pumpStart = millis();
  pumpOn = on;
}

void stopWithFault(const char *why) {
  setPump(false);
  fault = true;
  digitalWrite(FAULT_LED, HIGH);
  Serial.print("FAULT: ");
  Serial.println(why);
}

float readOnceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long t = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
  if (t == 0) return -1.0;             // no echo
  return t * 0.0343 / 2.0;             // 343 m/s at 20 C
}

float readDistanceCm() {               // median of 5 readings
  float r[5];
  for (byte i = 0; i < 5; i++) {
    r[i] = readOnceCm();
    delay(60);                         // datasheet: cycle of 60 ms or more
  }
  for (byte i = 1; i < 5; i++) {       // insertion sort
    float k = r[i];
    int j = i - 1;
    while (j >= 0 && r[j] > k) { r[j + 1] = r[j]; j--; }
    r[j + 1] = k;
  }
  return r[2];
}

void setup() {
  digitalWrite(RELAY_PIN, RELAY_ACTIVE_LOW ? HIGH : LOW);  // relay off before output is enabled
  pinMode(RELAY_PIN, OUTPUT);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(PUMP_LED, OUTPUT);
  pinMode(FAULT_LED, OUTPUT);
  Serial.begin(9600);
  setPump(false);
}

void loop() {
  if (fault) return;                   // latched: fix the cause, then press RESET

  float d = readDistanceCm();
  if (d < 0 || d > EMPTY_CM + 10.0) {
    stopWithFault("no valid echo from sensor");
    return;
  }

  float level = (EMPTY_CM - d) * 100.0 / (EMPTY_CM - FULL_CM);
  level = constrain(level, 0.0, 100.0);

  if (!pumpOn && level <= START_PCT) setPump(true);
  else if (pumpOn && level >= STOP_PCT) setPump(false);

  if (pumpOn && millis() - pumpStart > MAX_RUN_MS) {
    stopWithFault("pump ran too long, check sump and pipe");
    return;
  }

  Serial.print("Distance cm: "); Serial.print(d, 1);
  Serial.print("   Level %: ");  Serial.print(level, 0);
  Serial.print("   Pump: ");     Serial.println(pumpOn ? "ON" : "OFF");
  delay(200);
}

Each loop uses the median of five readings, which ignores a single bad echo. A small dedicated job like this, with no operating system, is what a microcontroller rather than a microprocessor is for.

Testing and expected results

Record your own readings; every tank, sensor and pump is a little different.

TestHow to do itExpected behaviour
SupplyMultimeter on Uno 5V pin and adapterClose to 5 V and 12 V
Distance accuracyHold a board at 10, 15, 20 and 25 cm by rulerPrinted distance close to the ruler value
Level calculationFill in steps, compare with measured depthLevel rises steadily, stays 0 to 100 %
Start and stopDrain the tank slowly, then let the pump fill itPump starts at 25 %, stops at 90 %, and does not chatter in between
Pump currentPut the multimeter in series with the pump on the 10 A rangeRunning current below the fuse and adapter ratings
Sensor faultPull out the Echo wire while runningPump stops, red LED on, FAULT message printed
Dry-run timerLift the pump out of the sump while it is runningPump stops after MAX_RUN_MS with a FAULT message

Before the dry-run test, time one normal fill from 25 % to 90 % and set MAX_RUN_MS to about 1.5 times that. Note the room temperature with your results.

Safety notes

  • Build and test on 12 V DC only. Never connect a mains pump to the breadboard or a relay module.
  • A house pump needs a contactor and motor starter with overload protection, wired by a qualified electrician. The relay’s 10 A rating is for resistive loads, and a motor draws much more current at start. See how a centrifugal pump works.
  • Keep the electronics above the water line, in a box.
  • Fit the fuse close to the adapter. Keep the dry-run timer enabled.
  • Unplug the adapter before changing any wiring.

Viva questions and answers

1. Why is the echo time divided by two? The Echo pulse covers the trip down and back, so the distance is half the path.

2. Why can’t the Arduino pin drive the relay coil directly? The coil needs about 70 mA and a pin is rated for 20 mA. A transistor on the module switches the coil.

3. What is the purpose of the flyback diode across the relay coil? At turn-off the coil inductance keeps the current flowing and makes a voltage spike. The diode gives that current a path and protects the transistor.

4. What is hysteresis in this controller and why is it needed? Separate start and stop levels, here 25 % and 90 %, so ripples cannot switch the pump rapidly.

5. What is the minimum range of the HC-SR04, and how does it affect installation? 2 cm, so the full level must stay well below the sensor. FULL_CM is 8 cm here.

6. Why does the code use a median filter instead of an average? An average is pulled by one false echo; the median of five ignores it.

7. What happens if the sensor cable breaks? pulseIn() times out and returns 0. The code stops the pump, lights the red LED and waits for a reset.

8. How does air temperature affect the reading? Sound speed rises about 0.6 m/s per °C. The code assumes 343 m/s (20 °C), so readings drift slightly at other temperatures.

Components required

ComponentSpecificationQty
Arduino Uno R3ATmega328P, 16 MHz, 5 V logic, 7 to 12 V recommended input, 14 digital I/O, 6 analog inputs, 32 KB flash1
HC-SR04 ultrasonic sensor5 V DC, 15 mA, 40 kHz, range 2 to 400 cm, 15 degree measuring angle, 10 µs trigger pulse1
Single-channel relay module5 V coil (SRD-05VDC-SL-C type), contacts 10 A 250 VAC and 10 A 30 VDC, on-board driver transistor and flyback diode1
DC water pump12 V DC mini submersible pump, running current below the adapter and fuse rating1
DC power adapter12 V DC, 2 A, 2.1 mm barrel plug, centre positive1
Fuse with inline holderGlass fuse rated just above the pump running current, in the 12 V pump line1
LED, 5 mmOne green (pump running), one red (fault)2
Resistor220 Ω, 0.25 W, LED current limiting2
Plastic containersAbout 30 cm deep, one as the overhead tank and one as the sump2
TubingSilicone or PVC tube to fit the pump outlet, about 1 m1
Breadboard and jumper wiresHalf-size breadboard, male to male and male to female jumpers1
USB cableUSB A to B, for programming and the Serial Monitor1

Frequently asked questions

Can I use this controller for the overhead tank at home?

Not as built. The model switches a 12 V DC pump. A house pump runs on mains and must be switched by a contactor with motor overload protection, fitted by a qualified electrician. The relay module would then only switch the contactor coil, and the electronics must sit in a closed, dry enclosure.

Why use an ultrasonic sensor instead of float switches?

An ultrasonic sensor gives a continuous level reading with no moving parts in the water, so you can set the start and stop levels in code. Float switches are simpler and very reliable but give only fixed on or off points. Many field controllers use float switches for exactly that reason.

Why does my distance reading jump around?

The usual causes are echoes from the tank wall, ripples on the water surface, or a sensor that is not square to the surface. The HC-SR04 beam spreads at about 15 degrees, so mount it near the middle of the lid, pointing straight down, and keep the median filter in the code.

References

  1. Arduino, Arduino UNO R3 product documentation and technical specifications
  2. Microchip Technology, ATmega328P datasheet
  3. ElecFreaks, HC-SR04 Ultrasonic Ranging Module user guide
  4. Songle Relay, SRD series miniature relay datasheet (SRD-05VDC-SL-C)
  5. M. Margolis, B. Jepson and N. R. Weldin, Arduino Cookbook, 3rd ed., O'Reilly Media, 2020
  6. D. Halliday, R. Resnick and J. Walker, Fundamentals of Physics, 10th ed., Wiley (speed of sound in air)

Get one engineering email a week

New articles, worked examples and study notes every week. Free, no spam, unsubscribe any time.

Santaji Gadepatil
Founder and Editor, B.E. Electronics and Telecommunication Engineering

Electronics and Telecommunication engineer working in industrial instrumentation and automation. Writes the Electronics Engineering articles on Zenta Engineering. Editorial policy.