Skip to content

Instantly share code, notes, and snippets.

@klanjabrik
Last active September 21, 2023 11:31
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save klanjabrik/367d7d370f27703425e7a77475b18b16 to your computer and use it in GitHub Desktop.
Save klanjabrik/367d7d370f27703425e7a77475b18b16 to your computer and use it in GitHub Desktop.
Measuring Water Usage with NodeMCU +WaterFlow Sensor

esp layout single

PENDAHULUAN

Internet of Things yang bisa disebut dengan IoT menjadi bagian yang penting dalam kemajuan teknologi. Contohnya adalah dengan mengirimkan data penggunaan air dari sensor ke cloud sehingga bisa dengan mudah melihat hasilnya. Untuk mengirimkan data penggunaan air dari sensor ke cloud maka dibutuhkan internet. Sehingga jika berbicara tentang IoT maka kira berbicara tidak terlepas dari 2 hal, yaitu: sensor dan internet.

PERANGKAT KERAS YANG DIBUTUHKAN

  • NodeMCU Lua WiFi (Rp85.000)
  • Water Flow Sensor (Rp70.000)
  • Lampu LED (Rp350)
  • Jumper + Breadboard (Rp36.000)
  • Kabel Power Micro USB

PERANGKAT LUNAK

PERANGKAT PENDUKUNG

Data dari sensor akan disimpan pada layanan cloud https://emoncms.org/

CARA KERJA

Setelah power dinyalakan, sistem akan mendeteksi ketersediaan koneksi WiFi dengan konfigurasi yang sebelumnya sudah dimasukkan ke dalam program. Selagi proses menghubungkan ke WiFI, lampu LED Indicator akan menyala (lihat lampiran di bawah), jika WiFi berhasil maka lampu LED Indicator akan mati.

Lampu LED Indicator akan menyala (lihat lampiran di bawah) jika ada air melewati sensor yang dilanjutkan dengan pengiriman data ke cloud.

Air yang melewati sensor akan menggerakan rotor menyebabkan adanya perputaran. Sensor ini, setiap liter air yang dialirkan per menit mengeluarkan kurang lebih 4.5 pulse, angka tersebut yang akan dijadikan kalibrasi.

MENGHUBUNGKAN WATER FLOW SENSOR DENGAN NODEMCU

Mengubungkan water flow sensor dengan NodeMCU membutuhan 3 kabel yang berasal dari sensor, yaitu:

  • Kabel kuning (signal/pulse) dihubungkan ke pin D2
  • Kabel hitam (ground) dihubungkan ke pin GND
  • Kabel merah dihubungkan ke pin 3V3

nodemcu waterflow connection

MENGHUBUNGKAN LED DENGAN NODEMCU

Menghubungkan LED dengan NodeMCU membutuhkan 2 kabel, yaitu:

  • Kabel signal dihubungkan ke pin D7
  • Kabel ground dihubungkan ke pin GND

nodemcu led connection

BENTUK AKHIR

nodemcu breadboard

// Credit:
// - https://diyhacking.com/arduino-flow-rate-sensor
// - http://www.instructables.com/id/Flowmeter-NodeMcu-Counting-Litres/
#include <Arduino.h>
#include <EEPROM.h>
#define USE_SERIAL Serial
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
// Variable init
const int buttonPin = D2; // variable for D2 pin
const int ledPin = D7;
char push_data[200]; //string used to send info to the server ThingSpeak
int addr = 0; //endereço eeprom
byte sensorInterrupt = 0; // 0 = digital pin 2
// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 4.5;
volatile byte pulseCount;
float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;
unsigned long oldTime;
//SSID and PASSWORD for the AP (swap the XXXXX for real ssid and password )
const char * ssid = "<NETWORK_NAME>";
const char * password = "<NETWORK_PASSWORD>";
//HTTP client init
HTTPClient http;
void setup() {
Serial.begin(115200); // Start the Serial communication to send messages to the computer
delay(10);
Serial.println('\n');
startWIFI();
// Initialization of the variable “buttonPin” as INPUT (D2 pin)
pinMode(buttonPin, INPUT);
// Two types of blinking
// 1: Connecting to Wifi
// 2: Push data to the cloud
pinMode(ledPin, OUTPUT);
pulseCount = 0;
flowRate = 0.0;
flowMilliLitres = 0;
totalMilliLitres = 0;
oldTime = 0;
digitalWrite(buttonPin, HIGH);
attachInterrupt(digitalPinToInterrupt(buttonPin), pulseCounter, RISING);
}
void loop() {
if (WiFi.status() == WL_CONNECTED && (millis() - oldTime) > 1000) // Only process counters once per second
{
// Disable the interrupt while calculating flow rate and sending the value to
// the host
detachInterrupt(sensorInterrupt);
// Because this loop may not complete in exactly 1 second intervals we calculate
// the number of milliseconds that have passed since the last execution and use
// that to scale the output. We also apply the calibrationFactor to scale the output
// based on the number of pulses per second per units of measure (litres/minute in
// this case) coming from the sensor.
flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;
// Note the time this processing pass was executed. Note that because we've
// disabled interrupts the millis() function won't actually be incrementing right
// at this point, but it will still return the value it was set to just before
// interrupts went away.
oldTime = millis();
// Divide the flow rate in litres/minute by 60 to determine how many litres have
// passed through the sensor in this 1 second interval, then multiply by 1000 to
// convert to millilitres.
flowMilliLitres = (flowRate / 60) * 1000;
// Add the millilitres passed in this second to the cumulative total
totalMilliLitres += flowMilliLitres;
unsigned int frac;
// Print the flow rate for this second in litres / minute
Serial.print("Flow rate: ");
Serial.print(int(flowRate)); // Print the integer part of the variable
Serial.print("."); // Print the decimal point
// Determine the fractional part. The 10 multiplier gives us 1 decimal place.
frac = (flowRate - int(flowRate)) * 10;
Serial.print(frac, DEC); // Print the fractional part of the variable
Serial.print("L/min");
// Print the number of litres flowed in this second
Serial.print(" Current Liquid Flowing: "); // Output separator
Serial.print(flowMilliLitres);
Serial.print("mL/Sec");
// Print the cumulative total of litres flowed since starting
Serial.print(" Output Liquid Quantity: "); // Output separator
Serial.print(totalMilliLitres);
Serial.println("mL");
if (flowRate > 0) {
digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
delay(100);
// Replace <YOUR_API_KEY> with your EmonCMS API Key
sprintf(push_data, "http://emoncms.org/input/post?json={frac:%d.%d,flowml:%d,totalml:%d}&node=Penampung2&apikey=<YOUR_API_KEY>", int(flowRate), int(frac), flowMilliLitres, totalMilliLitres);
Serial.printf("%s\n", push_data);
http.begin(push_data);
digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW
delay(100);
int httpCode = http.GET();
// httpCode_code will be a negative number if there is an error
Serial.print(httpCode);
if (httpCode > 0) {
digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
delay(100);
// file found at server
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.print(" ");
Serial.print(payload);
}
digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW
delay(100);
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
// Reset the pulse counter so we can start incrementing again
pulseCount = 0;
// Enable the interrupt again now that we've finished sending output
attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
} else if (WiFi.status() != WL_CONNECTED) {
startWIFI();
}
}
/*
Insterrupt Service Routine
*/
void pulseCounter() {
// Increment the pulse counter
pulseCount++;
}
void startWIFI(void) {
digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
delay(100);
WiFi.begin(ssid, password); // Connect to the network
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println(" ...");
oldTime = 0;
int i = 0;
digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW
delay(100);
while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
delay(2000);
Serial.print(++i);
Serial.print('.');
digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW
delay(100);
}
delay(2000);
Serial.print('\n');
Serial.print("Connection established!");
Serial.print("IP address:\t");
Serial.print(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
}
@Chester547
Copy link

Hello, maybe you can help me, please I need to measure the flow with the same sensor and nodeMCU, but I need to receive the data by serial monitor, I have tried several methods but I have not obtained any results, maybe you can help me?

@gururajksa
Copy link

Hi, i have uploaded the sketch and done the SSID/Password changes. The code is uploaded on to NodeMCU Arduino D1 board.
I am getting the flow on the Serial Monitor but i wanted date and time stamp along with the flow inputs. Can i get the sketch to have Date and time included?
Also on to which cloud http is the data sending, where do I specify the same?

@inyilis
Copy link

inyilis commented Nov 25, 2019

halo, saya ingin tanya bagaimana caranya untuk mendapatkan nilai kalibrasi sensor Water Flow Sensor? terimaksih.

@klanjabrik
Copy link
Author

halo, saya ingin tanya bagaimana caranya untuk mendapatkan nilai kalibrasi sensor Water Flow Sensor? terimaksih.

Kalibrasi didapatkan dari percobaan sebelumnya, jika dirasa sudah pas maka diambil angka tersebut.

@inyilis
Copy link

inyilis commented Nov 25, 2019

Saya masih belum mengerti, saya mencoba menampilkan pulseCount++ itu keluar 67 per/s. jadi nilai kalibrasinya berapa?

@klanjabrik
Copy link
Author

Saya masih belum mengerti, saya mencoba menampilkan pulseCount++ itu keluar 67 per/s. jadi nilai kalibrasinya berapa?

Nilai kalibrasi ada di static variabel berikut => float calibrationFactor = 4.5; (https://gist.github.com/klanjabrik/367d7d370f27703425e7a77475b18b16#file-waterflow-ino-L20)

@devjoshi3008
Copy link

When I upload this code, serial monitor shows "ISR not in IRAM" error. How can I resolve this error??

@Chester547
Copy link

Halo, mungkin Anda bisa membantu saya, tolong saya perlu mengukur aliran dengan sensor yang sama dan simpul MCU, tapi saya perlu menerima data dengan monitor serial, saya sudah mencoba beberapa metode tetapi saya belum mendapatkan hasil apa pun, mungkin saya bisa membantu?

@ranrinc
Copy link

ranrinc commented May 15, 2020

apakah kita bisa mendapatkan data secara local tanpa harus upload ke website lain? kalau ya ada caranya?

@sandikodev
Copy link

sandikodev commented Oct 15, 2020

Connection established!IP address:      192.168.2.202ISR not in IRAM!

User exception (panic/abort/assert)
                                   --------------- CUT HERE FOR EXCEPTION DECODER ---------------

Abort called

>>>stack>>>

ctx: cont
sp: 3ffffef0 end: 3fffffc0 offset: 0000
3ffffef0:  feefef00 feefeffe feefeffe 00000100  
3fffff00:  000000fe 00000000 00000000 00000000  
3fffff10:  00000000 00000000 00000000 00ff0000  
3fffff20:  5ffffe00 5ffffe00 0000000a 00000000  
3fffff30:  00000001 00000004 3ffee5f4 40205b8e  
3fffff40:  40100506 3ffee5f4 3ffe8648 40205ba0  
3fffff50:  40201cd8 3fffff80 3ffee5f4 402060ae  
3fffff60:  00000000 00000002 3ffee5f4 402078d2  
3fffff70:  3ffee5be 00000002 3ffee5f4 3ffee670  
3fffff80:  3fffdad0 00000000 3ffee5f4 40206160  
3fffff90:  3fffdad0 00000000 3ffee5f4 402011b5  
3fffffa0:  feefeffe feefeffe 3ffee630 4020579c  
3fffffb0:  feefeffe feefeffe 3ffe84f0 40100e45  
<<<stack<<<

--------------- CUT HERE FOR EXCEPTION DECODER ---------------

When I upload this code, serial monitor shows "ISR not in IRAM" error. How can I resolve this error??

anywhoelse
it might can resolve what you guys missing is,

void ICACHE_RAM_ATTR pulseCounter();

void setup() {
/*
   Insterrupt Service Routine
 */
void pulseCounter() {
        // Increment the pulse counter
        pulseCount++;
}

void startWIFI(void) {

@mbharti321
Copy link

Connection established!IP address:      192.168.2.202ISR not in IRAM!

User exception (panic/abort/assert)
                                   --------------- CUT HERE FOR EXCEPTION DECODER ---------------

Abort called

>>>stack>>>

ctx: cont
sp: 3ffffef0 end: 3fffffc0 offset: 0000
3ffffef0:  feefef00 feefeffe feefeffe 00000100  
3fffff00:  000000fe 00000000 00000000 00000000  
3fffff10:  00000000 00000000 00000000 00ff0000  
3fffff20:  5ffffe00 5ffffe00 0000000a 00000000  
3fffff30:  00000001 00000004 3ffee5f4 40205b8e  
3fffff40:  40100506 3ffee5f4 3ffe8648 40205ba0  
3fffff50:  40201cd8 3fffff80 3ffee5f4 402060ae  
3fffff60:  00000000 00000002 3ffee5f4 402078d2  
3fffff70:  3ffee5be 00000002 3ffee5f4 3ffee670  
3fffff80:  3fffdad0 00000000 3ffee5f4 40206160  
3fffff90:  3fffdad0 00000000 3ffee5f4 402011b5  
3fffffa0:  feefeffe feefeffe 3ffee630 4020579c  
3fffffb0:  feefeffe feefeffe 3ffe84f0 40100e45  
<<<stack<<<

--------------- CUT HERE FOR EXCEPTION DECODER ---------------

When I upload this code, the serial monitor shows "ISR not in IRAM" error. How can I resolve this error ??

anywhoelse
it might can resolve what you guys missing is,

void ICACHE_RAM_ATTR pulseCounter();

void setup() {
/*
   Insterrupt Service Routine
 */
void pulseCounter() {
        // Increment the pulse counter
        pulseCount++;
}

void startWIFI(void) {

Change your code acording to the included link code:
refrence code

@hattaamirudin
Copy link

hattaamirudin commented Jun 25, 2023

why can't my waterflow read
`// Inisialisasi pin sensor water flow
const int flowPin = 2; // Pin sensor water flow terhubung ke pin digital 2

// Variabel global
volatile int pulseCount; // Jumlah pulse dari sensor
float flowRate; // Debit air dalam liter per menit
unsigned int flowMilliLitres; // Total volume air yang telah mengalir dalam mililiter
unsigned long totalMilliLitres; // Total volume air yang telah mengalir dalam mililiter (total akumulasi)

unsigned long oldTime; // Waktu terakhir ketika pulse terdeteksi

// Variabel untuk kalibrasi
float calibrationFactor = 4.5; // Faktor kalibrasi
void ICACHE_RAM_ATTR pulseCounter();
void setup() {
// Mengaktifkan serial communication
Serial.begin(9600);

// Mengatur pin sensor water flow sebagai input dan mengaktifkan pull-up resistor internal
pinMode(flowPin, INPUT_PULLUP);

// Reset semua variabel
pulseCount = 0;
flowRate = 0.0;
flowMilliLitres = 0;
totalMilliLitres = 0;
oldTime = 0;

// Menginisialisasi interrupt
attachInterrupt(digitalPinToInterrupt(flowPin), pulseCounter, FALLING);
}

void loop() {
unsigned long currentTime = millis();

// Menghitung selang waktu sejak deteksi pulse terakhir
unsigned long elapsedTime = currentTime - oldTime;

// Mengupdate waktu terakhir ketika pulse terdeteksi
oldTime = currentTime;

// Menghitung debit air dalam liter per menit
flowRate = ((1000.0 / elapsedTime) * pulseCount) / calibrationFactor;

// Menghitung volume air yang telah mengalir dalam mililiter
flowMilliLitres = (flowRate / 60) * 1000;

// Mengakumulasi total volume air yang telah mengalir
totalMilliLitres += flowMilliLitres;

// Mengatur ulang jumlah pulse
pulseCount = 0;

// Menampilkan hasil ke Serial Monitor
Serial.print("Debit Air: ");
Serial.print(flowRate);
Serial.print(" L/min | Total Volume Air: ");
Serial.print(totalMilliLitres);
Serial.println(" mL");

delay(5000);
}

void pulseCounter() {
// Meningkatkan jumlah pulse
pulseCount++;
}
`

water

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment