Water level Controller using Esp32,Micropython and Home Assistant




Micropython

Micropython is an open-source implementation of the Python programming language that is designed run on microcontrollers and other small devices. It was created in order to make it easier for developersto program these types of devices and to allow them to take advantage of the simplicity and power of the Python language.

One of the main benefits of using Micropython is its small size and low resource requirements. Because it is designed to run on small devices with limited processing power and memory, micro python is able to run efficiently and quickly even on devices with very limited hardware resources. This makes it an ideal choice for a wide range of applications, including Internet of Things (IoT) devices, sensors, and other types of embedded systems.


Micropython is becoming popular nowadays. It uses python as the programming language for working with microcontrollers. It has support for Esp32,ESP8266,CC3200,STM 32,Raspberry Pi and PI boards etc.
It is a very fast to operate and very easy to handle. The developer can use the various libraries made available if the Micropython community.How to set up micropython with esp32 Board is explained in the you tube Video here.


MQTT

The MQ telemetry tranport protocal is a wireless protocol used for Internet of things. It is one the popular proto cols used in IOT. It is very lightweight used for distributing the telemetry information across the constrained devices. This protocol uses Publish subscribe topology. The network of Mqtt consists of at least a Publisher node, broker and Subscriber node. The data or information is published by the publisher over certain topic to the broker.The subscriber which is subscribed to the topic of the publisher received the message. This is the brief working of the Mqtt. This protocol is used in automotive automotive, telecommunication, manufacturing, oil, agriculture and gas industries to distribute the information gathered from the sensors.

Home Assistant is a free platform where you can integrate your Devices and monitor the data and control the operations.The Home assistant can also be integrated with Alexa and Google Assistant.The Windows portable version of Home Assistant is suitable for PC and Laptops. It is a very lightweight version.This HAAS WP can be downloaded from this link and watch this video to know how to download and use it.


Implement water level controller with ESP 32 ,micropython esp32 and Home Assistant 

Hardware Setup  






                                                                             Water Tank Levels

                                      Basic Setup for Simulation for Water Level Controller





                       
 

                                                  Practical Setup for Water Level Controller


Sensors

We can use sensors of following types

1]Electrodes as  per the type of Water (Fresh or Salty etc.). For this you can get more information here and  check the section related to Electrodes.
2]SS Contact type Water Level Sensors
3]Reed Switch Water Level Sensors
4]Float Water Level Sensors



Micro python Coding

The Thonny Ide can be used for to writing code. The Thonny Ide can be downloaded from here.

Importing the following Libraries

import network
import time
from umqtt.simple import MQTTClient
import machine 


Gpio Pins of ESP32 used 

Low Level Sensor - GPIO 5

Middle Level Sensor - GPIO 18

High Level Sensor  - GPIO 19

Led or Pump Status - GPIO 2


Code Functionality

First wi-fi connection is established by using the network functions. After this,Mqtt connection is established. The level sensors input are monitored continuously. When Water tank is dry as per the level sensor inputs then the Pump is turned on. When Water level touches High level sensor then the Pump is turned off.

The level status and Pump status is conveyed to Broker or Home Assistant by using publishing the message over MQTT channel.

Code Snippet


Setting UP Home Assistant

Locate the config folder where the Home Assistant Wp files are stored and open configutaion.yaml file and copy the following code.

sensor:
  - platform: mqtt
    name: "testtasmota_LowLevel"
    unique_id: "wri1"
    value_template: "{{ value_json.Switch1 }}"
    state_topic: "tele/tswitch/SENSOR"
    

  - platform: mqtt
    name: "testtasmota_MidLevel"
    unique_id: "wri2"
    value_template: "{{ value_json.Switch2 }}"
    state_topic: "tele/tswitch/SENSOR"  

  
  - platform: mqtt
    name: "testtasmota_HighLevel"
    unique_id: "wri3"
    value_template: "{{ value_json.Switch3 }}"
    state_topic: "tele/tswitch/SENSOR"


Save the file and run haas windows command script file.

Log in to the Home Assistant,Add Mqtt integration and search the Mqtt .

1 .Add Entities  like Water Pump and Water Tank clicking on the add cards to the Dashboard of Home Assistant.

Code for the Water level Controller
       
import network
import time
from umqtt.simple import MQTTClient
import machine 

WiFi_SSID = ""  #Wfif SSID
WiFi_PASS = ""  #WIFI PASSWORD

SERVER = "broker.hivemq.com"//you can try for other brokers like test.mosquito.org
PORT = 1883
CLIENT_ID = "Esp32Mlc"

#create topic to publish the message about Tank Level
topicOutTankLevel = "WaterTank/level" 

#create topic to publish the message about Pump Status
topicOutPump = "WaterTank/Pump/Status" 


#define Port Pins for wire sensors
LOW_EVEL = 18
MID_EVEL = 5
HIGH_EVEL = 19

#Current Level of Tank
levelStatus ="Empty"

#Pump operation Flag
fpump = "OFF"

#Set Tank level Sensors pins as input  
lowlevel = machine.Pin(LOW_EVEL, machine.Pin.IN, machine.Pin.PULL_UP)
midlevel = machine.Pin(MID_EVEL, machine.Pin.IN, machine.Pin.PULL_UP)
highlevel = machine.Pin(HIGH_EVEL, machine.Pin.IN, machine.Pin.PULL_UP)

#Set GPIO pin 2 as output
PUMP = machine.Pin(2, machine.Pin.OUT)
PUMP.value(0)

#check low level input
def senLowLevel():
    
    #flag shwoing tank level status
    ftanklevel = False
    
    if(lowlevel.value() == 0):
       
       time.sleep(1)
       
       if(lowlevel.value() == 0): 
           ftanklevel = True
           
    elif(lowlevel.value() == 1):
        
        time.sleep(1)
        
        if(lowlevel.value() == 1):
            ftanklevel = False
    
    return ftanklevel


#check mid level input
def senMidLevel():
    
    ftanklevel = False
   
    if(midlevel.value() == 0):
       
       time.sleep(1)
       
       if(midlevel.value() == 0): 
           ftanklevel = True
           
    elif(midlevel.value() == 1):
        
        time.sleep(1)
        
        if(midlevel.value() == 1):
            ftanklevel = False
    
    return ftanklevel


#check High level input
def senHighLevel():
    
    ftanklevel = False
   
    if(highlevel.value() == 0):
       
       time.sleep(1)
       
       if(highlevel.value() == 0): 
           ftanklevel = True
           
    elif(highlevel.value() == 1):
        
        time.sleep(1)
        
        if(highlevel.value() == 1):
            ftanklevel = False
    
    return ftanklevel



def wifi_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(WiFi_SSID, WiFi_PASS)
        while not wlan.isconnected():
            pass
    print("Connected to Wifi Router")
    
   
    
#connect esp32 to wifi
wifi_connect()

#create a client and connect to the mqtt broker
client = MQTTClient(CLIENT_ID, SERVER,PORT)

#Connect clint with Broker
client.connect()


print("Mqtt connected")
    
while True:
    
    #check level Sensor inputs
    
    if ((senHighLevel() == True)):
        
        levelStatus = "Full"
    
    elif ((senMidLevel() == True) ):   
        
        levelStatus = "MidLevel"
        
    elif ((senLowLevel() == True) ):
        
        levelStatus = "LowLevel"
    
    else:
        
        levelStatus = "Empty"
        
        
    if ((levelStatus == "Empty") ):
        
        #When Tank Empty Turn the PUMP on
        fpump = "ON"
        PUMP.value(1)
        
     
    elif (levelStatus == "Full") :
         
         #When Tank is full Trun PUMP Off
         fpump = "OFF"
         PUMP.value(0)
         
     
             
    #Publish the level status and pump status to HAAS
    client.publish(topicOutTankLevel, levelStatus )
    client.publish(topicOutPump, fpump ) 
    
    print(levelStatus)
    print(fpump)
    
    #Check any message arrived
    client.check_msg()
    
    time.sleep(2)

 


For other Details Watch YouTube Video here.





Post a Comment

Previous Post Next Post