Share My Creation Water tank level sensor with esp8266

Water Tank Level Sensor with ESP8266
Components used
01 Flow sensor
01 Esp8266
01 Selenoid valve
01 Relay
etc.
B4R:
[
Sub Process_Globals
    Private wifi As ESP8266WiFi                     ' Comunicação wif
    Public Serial1 As Serial                        ' Comunicação serial para debug
    Public flowsensor As Pin                        ' Pino para o sensor de fluxo
    Public flow_frequency As Int                    ' Variável que armazena a frequência de fluxo (pulsos)
    Public currentTime As ULong                     ' Armazena o tempo atual em milissegundos
    Public cloopTime As ULong                       ' Armazena o tempo da última leitura
    Public liters As Float                          ' Quantidade de litros que passaram pelo sensor
    Public mililiters As Float                      ' Quantidade de mililitros que passaram pelo sensor
    Public flowRate As Float                        ' Taxa de fluxo em L/min
    Public buzzerState As Boolean                   ' Estado do buzzer (ligado/desligado)
    Public vazamento As Boolean                     ' Flag para indicar se há vazamento (True/False)
    Public Timer1 As Timer                          ' Temporizador que simula a interrupção do fluxo

    Private ESPin As D1Pins                         ' Usando Resp8266
    Private BUZZ As Pin                             ' Pino para controle do buzzer
    Private LED As Pin                              ' Pino para controle do led
    Private RELE As Pin                             ' Pino para controle do relé
    Private ssd As AdafruitSSD1306                  ' Usando display led
    Private Conte As Int = 0                        ' Contador do Buzzer
End Sub

Private Sub AppStart
    Serial1.Initialize(115200)
    Log("AppStart")
    ssd.InitializeI2C(ESPin.D6,0x3C)            'initialise SSD1306 0x78
    ssd.ClearDisplay
    ssd.GFX.SetCursor(0, 0)
    ssd.GFX.ConfigureText(2, ssd.WHITE, False)
    ssd.GFX.DrawText("Cesar Morisco").DrawText(CRLF).DrawText(CRLF)
    ssd.Display
  
    BUZZ.Initialize(ESPin.D8,BUZZ.MODE_OUTPUT)
    LED.Initialize(ESPin.D7,LED.MODE_OUTPUT)
    RELE.Initialize(ESPin.D8,RELE.MODE_OUTPUT)
  
    BUZZ.DigitalWrite(True) ' Ligar O bazzer
    Delay(200)              ' Espera 200 milisegundo
    BUZZ.DigitalWrite(False)' Desliga o bazzer
  
  
    'example of connecting to a local network
    If wifi.Connect2("SSID", "PASSWORD") Then
        Log("Connected to network")
        LED.DigitalWrite(True)
    Else
        Log("Failed to connect to network")
        LED.DigitalWrite(False)
    End If
    ' Inicializa o pino do sensor de fluxo como entrada
    flowsensor.Initialize(10, flowsensor.MODE_INPUT_PULLUP)
    flowsensor.AddListener("flow_1")                   ' Associa a função flow para simular a interrupção
  
    ' Inicializa o temporizador para executar a cada 1 segundo (1000 ms)
    Timer1.Initialize("Timer1_Tick", 1000)
    Timer1.Enabled = True                           ' Ativa o temporizador
    ' Define o tempo atual e o tempo de início da contagem
    currentTime = Millis
    cloopTime = currentTime
End Sub

' Função simulando a interrupção do fluxo. Ela incrementa a contagem de pulsos (fluxo de água).
Sub flow_1(State As Boolean)
    flow_frequency = flow_frequency + 1             ' Incrementa o contador de pulsos sempre que a função é chamada
End Sub
' Função executada pelo temporizador a cada segundo
Sub Timer1_Tick
    currentTime = Millis                            ' Obtém o tempo atual em milissegundos
    'Incrementa o contador simulado a cada tick para simular o sensor de fluxo
    ' Verifica se 1 segundo passou desde a última contagem
    If currentTime >= cloopTime + 1000 Then
        cloopTime = currentTime                     ' Atualiza o tempo de referência para a próxima contagem

        ' Ajuste: calcula a taxa de fluxo para o sensor YF-S401 > "5880"
        ' 450 pulsos por litro. Multiplicamos por 60 para obter litros por minuto
        ' Ajuste fino no fator de conversão (use 5875 em vez de 5880)
        flowRate = (flow_frequency / 5880.0)' Taxa em litros por segundo
        ' Converte a taxa de fluxo de L/min para mililitros por segundo
        ' Multiplicando por 1000 para converter litros para mililitros
        mililiters = (flowRate * 1000) ' Converte a taxa em L para mL

        ' Atualiza o total de litros que passaram pelo sensor
        liters = liters + flowRate  ' Acumula os litros
        ' Se o fluxo for zero, não reseta mais o contador de litros (mantemos o valor acumulado)
        If flowRate = 0 Then
            ' Se quiser resetar os litros, faça aqui, mas atualmente isso não está ajudando:
            ' liters = 0
        End If
        ' Atualiza o display com a quantidade de litros
        ssd.ClearDisplay
        ssd.GFX.SetCursor(2, 0)
        ssd.GFX.ConfigureText(1, ssd.WHITE, False)
        ssd.GFX.DrawText("IP:")
        ssd.GFX.DrawText(wifi.LocalIp)
      
        ssd.GFX.SetCursor(4, 18)
        ssd.GFX.ConfigureText(2, ssd.WHITE, False)
        ssd.GFX.DrawText(NumberFormat(liters, 1, 3))
        ssd.GFX.DrawText(" Litros")
        ssd.Display
        ' Mostra a quantidade de litros e mililitros no log
        Log("Litros: " , NumberFormat(liters, 1, 3))
        Log("Mililitros: " , NumberFormat(mililiters, 1, 0))
      
        ' Verifica se o limite de litros foi ultrapassado para detectar vazamento
        ' Aqui comparamos "liters > 1500", mas adicionamos uma margem para evitar problemas de arredondamento
        'If liters >= 1500 And vazamento = False Then
        If liters >= 1.0 And vazamento = False Then ' Um litros para teste
            vazamento = True
            Log("Aqui...")                      ' Sinaliza que houve vazamento
        End If
      
        ' Se houver vazamento, aciona o relé e alterna o estado do buzzer (ligando e desligando)
        If vazamento = True Then
            RELE.DigitalWrite(False)'Desligar a valvola se tiver fazamento
            Buzzz                   'Ligar o buzzer  altarnado
        Else
            BUZZ.DigitalWrite(False)'Desligar buzzer
            RELE.DigitalWrite(True) 'Ligar Valvola tem que fica aberta ate o limite programado >???
        End If
    
        ' Reseta o contador de pulsos
        flow_frequency = 0
    End If
End Sub

Sub Buzzz
    Conte = Conte + 1  ' Incrementa o contador a cada vez que a função é chamada

    If Conte <= 4 Then  ' Verifica se o contador ainda está dentro do limite de 4 acionamentos
        If Conte Mod 2 = 0 Then  ' Alterna o estado do buzzer (liga e desliga a cada chamada)
            BUZZ.DigitalWrite(False)  ' Desliga o buzzer
        Else
            BUZZ.DigitalWrite(True)   ' Liga o buzzer
        End If
    Else
        BUZZ.DigitalWrite(False)      ' Desliga o buzzer após 4 acionamentos
        Conte = 0  ' Reseta o contador para reiniciar o ciclo
    End If
End Sub
/]
 

Attachments

  • Sem título.jpg
    431.5 KB · Views: 1,039
  • PROJETO_1.PDF
    160 KB · Views: 67
Last edited:

Cableguy

Expert
Licensed User
Longtime User
Hi Cesar,

Studying the schematics, this seems to be more of a Flow Sensor/Controller than a Tank Level Sensor...
Can you confirm that, or give some explanation on how the level is sensed .... ?

Ola César,

De acordo com o esquema proposto, este parece ser mais um circuito de detecçao e contolo de fluxo, e nao de nivel de liquido dentro de um tanque.
Confirma a minha observaçao ou pode dar uma pequena explicaçao de como o nivel de liquido é detectado no tanque...?
 

Cesar_Morisco

Active Member
Licensed User
Longtime User
Hello Cableguy. All good.
And that's just like water consumption protection. I did this project for a friend who travels and forgets the tap is open when it reaches 1500 liters, turn off the seneloid that is at the street water inlet. It can also be used to sell chlorine where you can calculate a liter. A big hug
 

Cableguy

Expert
Licensed User
Longtime User
So, more of a flow controller and a full tank detector, than a level sensing, which expects the capability to detect multilevels
 

Cesar_Morisco

Active Member
Licensed User
Longtime User
This can also be used, but each sensor has to calculate liters per second
For my friend and more for the protection of an open and forgotten tap lol
 

Beja

Expert
Licensed User
Longtime User

It's good to learn from the ESP code, but for a level sensor I would use a level sensor instead of a flow sensor.. safer, because there could be a leak or anything, but a level sensor guarantees that the solenoid valve will shutoff at the right time, at the right level of the tank. there're so many level sensors commercially available. wired and wireless.
 

Cesar_Morisco

Active Member
Licensed User
Longtime User
Hi Beja, how are you?
My friend also wants to know how many liters he has already used, so for that I have to use the flow sensor
And one more protection against leaks or in case he forgets the tap open when he travels lol A hug later I'll post more details a hug
 

Beja

Expert
Licensed User
Longtime User

Hi Cesar,
If the flow sensor is installed just above the tank then that may work.
Otherwise a flow sensor will not give you accurate usages forever because leaked water are not used.. duh! Flow sensor best use is to know how much water you are drawing from the well or water source, so you can prepared for the bill. (invoice). you can use multiple sensors.. A few years ago I designed a central irrigation system for a large farm in Dubai and for that, I used pressure sensor, flow sensor, rain fall sensor and wind speed sensor. besides ph sensor and used a special vavle to release a calculated chemical to balance the pH automatically. so, one sensor only is not enough (I beleive).
 
Last edited:

Cesar_Morisco

Active Member
Licensed User
Longtime User
Of course it's not that accurate, everyone or circuit has loss of calculation and weather
To my friend he said he is satisfied hahaha
Thanks for commenting
 

Beja

Expert
Licensed User
Longtime User
Of course it's not that accurate, everyone or circuit has loss of calculation and weather
To my friend he said he is satisfied hahaha
Thanks for commenting

If a customer told you the water is wet, just put it in the dryer
btw: thanks for generously providing this useful code.. I am learning from it.
 
Last edited:
Cookies are required to use this site. You must accept them to continue using the site. Learn more…