Intelligent water flow sensor project with ESP32 code example
Example: Intelligent water flow sensor with ESP32
#include <ESP8266WiFi.h> //Library can be download below
#include <WiFiClient.h> //Library can be downloaded below
#include <ESP8266WebServer.h> //Library can be downloaded below
#include <PubSubClient.h>
int sensorPin1 = 5;
//int flowPin2 = 4;
//int flowPin3 = 3;
//int flowPin4 = 2;
unsigned long flow1count = 0;
unsigned long flow2count = 0;
#define countof(a) (sizeof(a) / sizeof(a[0]))
/* Connecting to existing wifi AP Network */
//char ssid[] = "14CORE"; // your network SSID (name)
//char password[] = "we do what we must, because we can"; // your network password
/* Make you own stand alone wifi networ accesspoint*/
const char* ssid = "14CORE";
const char* password = "1234567890";
// Set your IP address for your suitable for your network IP/SEGMENT
IPAddress server(192, 168, 4, 100);
PubSubClient client(server);
String webString = "14CORE | Water Flow Sensor with ESP8266"; // String to display
// Callback function
void callback(const MQTT::Publish& pub) {
if(pub.payload_string().equals("flow1"))
{
webString = "Flow 2: " + String(flow1count/450.0) + " L"; // Arduino has a hard time with float to string
client.publish("outTopic",webString);
} else if(pub.payload_string().equals("flow2"))
{
webString = "Flow 2: " + String(flow2count/450.0) + " L";
client.publish("outTopic",webString); // send to someones browser when asked
} else
Serial.print("14CORE | Flow Sensor ")
Serial.print("Flow 1 in Liters: ");
Serial.print(flow1count/450.0);
Serial.print("\tFlow 2 in Liters: ");
Serial.print(flow2count/450.0);
Serial.print("\tFlow 1 in pulses: ");
Serial.print(flow1count);
Serial.print("\tFlow 2 in pulse: ");
Serial.println(flow2count);
delay(500);
{
}
Serial.print(pub.topic());
Serial.print(" => ");
Serial.println(pub.payload_string());
}
void setup()
{
Serial.begin(115200);
pinMode(sensorPin1, INPUT_PULLUP);
attachInterrupt(sensorPin1, flow1, CHANGE);
pinMode(flowPin2, INPUT_PULLUP);
attachInterrupt(flowPin2, flow2, CHANGE);
client.set_callback(callback);
// Connect to existing wifi network
WiFi.begin(ssid, password);
Serial.print("\n\r \n\rWorking to connect");
// Wait 5mili for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print("Connecting ")
Serial.print(".");
}
Serial.println("");
Serial.print
Serial.println("14CORE | ESP8266 Server");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (client.connect("14CORE | ESP8266 Liquid Flow Sensor")) {
client.publish("outTopic","flow boot up");
client.subscribe("inTopic");
}
}
void loop()
{
client.loop();
}
void flow1()
{
flow1count +=1;
}
void flow2()
{
flow2count +=1;
}