ESP32 MicroPython Water Sensor

This guide will show you how to use a water sensor with ESP32 and MicroPython to detect water leaks, measure rainfall, check if a tank is overflowed, or monitor water levels. In detail, we will learn.

ESP32 MicroPython and water sensor module

Hardware Preparation

1×ESP-WROOM-32 Dev Module
1×USB Cable Type-C
1×Water level sensor
1×Jumper Wires
1×Breadboard
1×(Recommended) Screw Terminal Expansion Board for ESP32

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of Water Level Sensor

Water Level Sensor Pinout

The water level sensor has three pins:

  • S (Signal) pin: Analog output. Connect to ESP32's analog input.
  • + (VCC) pin: Provides power to the sensor. Use between 3.3V and 5V.
  • - (GND) pin: Ground connection.
water sensor pinout

※ NOTE THAT:

The signal from the sensor changes when the voltage at its VCC pin is adjusted.

How Water Level Sensor Works

The sensor is made up of ten copper wires that you can see. Five of these wires are for power, and the other five are for sensing. They're arranged in a pattern, with one sensor wire between every two power wires. Normally, these wires don't touch, but when the sensor is in water, the water acts as a bridge between them.

Think of the wires like a special kind of knob that changes its resistance based on how much water is around it.

  • The higher the water level, the lower the resistance.
  • More water means better conductivity, which means lower resistance.
  • Less water means poorer conductivity, which means higher resistance.

The sensor uses this resistance to create an output voltage. By measuring this voltage, we can figure out how high the water level is.

Wiring Diagram

Connect the sensor’s VCC pin to the 5V pin on the ESP32 and the GND pin to the GND pin on the ESP32 to power it. It’s not a good idea to keep the sensor powered on in a wet environment, as this can quickly damage it and shorten its lifespan. To avoid this, only power the sensor when you need to check its data. Connect the sensor’s VCC pin to a digital pin on the ESP32. To read the sensor, set the ESP32 pin to HIGH, and after reading, set it to LOW.

  • How to connect ESP32 and water sensor using breadboard
The wiring diagram between ESP32 MicroPython Water Sensor

This image is created using Fritzing. Click to enlarge image

How to connect ESP32 and water sensor

ESP32 MicroPython Code - Reading Value from Water Sensor

""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-water-sensor """ from machine import Pin, ADC import time POWER_PIN = 17 # The ESP32 pin GPIO17 connected to the VCC pin of water sensor SIGNAL_PIN = 36 # The ESP32 pin GPIO36 (ADC0) connected to the S pin of water sensor # Setup power pin power = Pin(POWER_PIN, Pin.OUT) power.value(0) # Initially turn off the sensor # Setup ADC for reading the water sensor signal = ADC(Pin(SIGNAL_PIN)) # Set the ADC width (resolution) to 12 bits signal.width(ADC.WIDTH_12BIT) # Set the attenuation to 11 dB, allowing input range up to ~3.3V signal.atten(ADC.ATTN_11DB) while True: power.value(1) # Power on the sensor time.sleep(0.01) # Wait 10ms for sensor to stabilize value = signal.read() # Read the analog value (0-4095 range on ESP32) power.value(0) # Power off the sensor print("Sensor value:", value) # Print the value time.sleep(1) # Wait for a second before next read

Detailed Instructions

Here’s instructions on how to set up and run your MicroPython code on the ESP32 using Thonny IDE:

  • Make sure Thonny IDE is installed on your computer.
  • Confirm that MicroPython firmware is loaded on your ESP32 board.
  • If this is your first time using an ESP32 with MicroPython, check out the ESP32 MicroPython Getting Started guide for step-by-step instructions.
  • Connect the ESP32 board to the water sensor according to the provided diagram.
  • Connect the ESP32 board to your computer with a USB cable.
  • Open Thonny IDE on your computer.
  • In Thonny IDE, go to Tools Options.
  • Under the Interpreter tab, choose MicroPython (ESP32) from the dropdown menu.
  • Make sure the correct port is selected. Thonny IDE usually detects it automatically, but you might need to select it manually (like COM12 on Windows or /dev/ttyACM0 on Linux).
  • Copy the provided MicroPython code and paste it into Thonny's editor.
  • Save the code to your ESP32 by:
    • Clicking the Save button or pressing Ctrl+S.
    • In the save dialog, choose MicroPython device.
    • Name the file main.py.
  • Click the green Run button (or press F5) to execute the script.
  • Slowly put the sensor into a glass of water.
  • Check out the message in the Shell at the bottom of Thonny.
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot Sensor value: 0 Sensor value: 0 Sensor value: 99 Sensor value: 387 Sensor value: 1135 Sensor value: 1711 Sensor value: 1737 Sensor value: 1763 Sensor value: 1819 Sensor value: 1865 Sensor value: 2082 Sensor value: 2111 Sensor value: 2210
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡

※ NOTE THAT:

Don't fully submerge the sensor; only let the visible parts of the electronic board touch the water. Be careful when installing it.

※ NOTE THAT:

This tutorial demonstrates how to use the adc.read() function to read values from an ADC (Analog-to-Digital Converter) connected to a water sensor. The ESP32's ADC is suitable for projects that do not require high precision. However, if your project needs accurate measurements, keep the following in mind:

  • The ESP32 ADC is not perfectly accurate and may require calibration for precise results. Each ESP32 board may vary slightly, so calibration is necessary for each individual board.
  • Calibration can be challenging, especially for beginners, and might not always yield the exact results you desire.

For projects requiring high precision, consider using an external ADC (e.g., ADS1115) with the ESP32 or opt for an Arduino, which has a more reliable ADC. If you still wish to calibrate the ESP32 ADC, refer to the ESP32 ADC Calibration Driver.

How To Detect Water Leakage

To check for water leaks, rain, or overflowing tanks, we compare the reading to a preset limit. This limit is set during the calibration part of this tutorial. The ESP32 MicroPython code below shows how to detect water leaks.

""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-water-sensor """ from machine import Pin, ADC import time POWER_PIN = 17 # The ESP32 pin GPIO17 connected to the VCC pin of water sensor SIGNAL_PIN = 26 # The ESP32 pin GPIO36 (ADC0) connected to the S pin of water sensor THRESHOLD = 1000 # Setup the power pin power = Pin(POWER_PIN, Pin.OUT) power.value(0) # Initially turn off the sensor # Setup ADC for reading the water sensor signal = ADC(Pin(SIGNAL_PIN)) # Set the ADC width (resolution) to 12 bits signal.width(ADC.WIDTH_12BIT) # Set the attenuation to 11 dB, allowing input range up to ~3.3V signal.atten(ADC.ATTN_11DB) # Initialize the power pin to off power.value(0) while True: power.value(1) # Turn on power to the sensor time.sleep_ms(10) # Short delay to allow sensor to stabilize value = signal.read() # Read the analog value from sensor power.value(0) # Turn off power to the sensor if value > THRESHOLD: # Check if the water level exceeds the threshold print("Water detected") time.sleep(1) # Delay for a second before the next reading

How To Measure The Water Level

To break down the highest water level into different stages and identify the current stage, follow the method in the code below. Keep in mind that the highest water level corresponds to the sensor being fully submerged in the water. This code splits the full height into 4 stages.

""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-water-sensor """ from machine import Pin, ADC import time POWER_PIN = 17 # The ESP32 pin GPIO17 connected to the VCC pin of water sensor SIGNAL_PIN = 26 # The ESP32 pin GPIO36 (ADC0) connected to the S pin of water sensor SENSOR_MIN = 0 SENSOR_MAX = 2088 # Setup the power pin power = Pin(POWER_PIN, Pin.OUT) # Setup ADC for reading the water sensor signal = ADC(Pin(SIGNAL_PIN)) # Set the ADC width (resolution) to 12 bits signal.width(ADC.WIDTH_12BIT) # Set the attenuation to 11 dB, allowing input range up to ~3.3V signal.atten(ADC.ATTN_11DB) # Function to map the sensor value from one range to another def map_value(x, in_min, in_max, out_min, out_max): return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min power.value(0) # Initially turn off the sensor while True: power.value(1) # Activate the sensor time.sleep_ms(10) # Wait for the sensor to stabilize value = signal.read() # Read the sensor output power.value(0) # Deactivate the sensor # Map the value to a 0-4 scale, adjusting for 16-bit ADC value level = map_value(value, SENSOR_MIN, SENSOR_MAX * 4095, 0, 4) # Print the water level print("Water level:", level) time.sleep(1) # Delay for one second before repeating

※ NOTE THAT:

  • SENSOR_MIN and SENSOR_MAX are set during calibration.
  • The mapping method explained may not be super precise, but it’s good enough for most uses. For better accuracy, measure the threshold values for each level as explained in the calibration section.

Water Level Sensor Calibration

The sensor’s output depends on both the water level and its conductivity. Pure water doesn’t conduct electricity, but water with minerals and impurities does. The more conductive the water, the more sensitive the sensor becomes. Additionally, the output can change based on the voltage supplied to the sensor's VCC pin.

For accurate readings from the water sensor, it’s best to calibrate it for the specific type of water you plan to monitor. Before setting a threshold to trigger an action, you should test the actual value the sensor reads.

How to perform the test:

  • Use the sketch above to read the sensor's value.
  • Dip the sensor into the water at the level where you want to set the threshold.
  • Write down the value shown in the Shell at the bottom of Thonny.
  • Use this value as the threshold to trigger an action.
  • You might need to try this test a few times to get it right.

The test can also help you find:

  • The SENSOR_MIN value, when the sensor isn’t in water.
  • The SENSOR_MAX value, when the sensor is fully submerged.
  • A threshold value to detect water leaks.
  • Threshold values for different levels on your scale.

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!