#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL65FgFnLyj"
#define BLYNK_TEMPLATE_NAME "UTS WSN"
#define BLYNK_AUTH_TOKEN "NSLTW5IYGXpdFVAkJ3-AN3HGcCo8q-jt"
#include <BlynkSimpleEsp32.h>
BlynkTimer timer;
#include <Wire.h>
#include <WiFi.h>
#include <WiFiClient.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASS ""
// Pin connected to the flow sensor
const int flowSensorPin = 34;
// Variables to measure flow rate
volatile int pulseCount = 0;
double flowRate = 0.0;
unsigned long lastTime = 0;
// Interrupt service routine for counting pulses
void IRAM_ATTR pulseCounter() {
pulseCount++;
}
void setup(void) {
// Initialize serial communication at 115200 baud rate
Serial.begin(115200);
Serial.println("Program dimulai...");
// Set up the flow sensor pin
pinMode(flowSensorPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(flowSensorPin), pulseCounter, FALLING);
// Initialize variables
pulseCount = 0;
flowRate = 0.0;
lastTime = millis();
// Connect to Blynk
Blynk.begin(BLYNK_AUTH_TOKEN, WIFI_SSID, WIFI_PASS);
// Set a timer to call the sendData function every second
timer.setInterval(1000L, sendDataToBlynk);
}
void loop(void) {
Blynk.run();
timer.run();
if (millis() - lastTime >= 1000) {
int pinRead0 = analogRead(A0); // Read from analog pin A0 on ESP8266
double pVolt0 = pinRead0 / 1024.0 * 3.3; // Convert the ADC value to voltage (ESP8266 uses 3.3V reference)
double persenCahaya = (pinRead0 / 1023.0) * 100; // Convert the ADC value to a percentage
Serial.print("Nilai ADC: ");
Serial.print(pinRead0); // Menulis nilai ADC yang dibaca
Serial.print(" -> Tegangan: ");
Serial.print(pVolt0); // Menulis nilai konversi Volt melalui komunikasi serial
Serial.print(" V -> Intensitas Cahaya: ");
Serial.print(persenCahaya); // Menulis nilai persen intensitas cahaya
Serial.print(" lx");
Serial.println();
// Calculate flow rate in liters/minute
float pulseFrequency = pulseCount;
flowRate = pulseFrequency / 7.5; // YF-S201: 1 liter/min = 7.5 Hz
pulseCount = 0;
// Print the flow rate and total volume to the Serial Monitor
Serial.print("Flow rate: ");
Serial.print(flowRate);
Serial.println();
lastTime = millis();
}
}
void sendDataToBlynk() {
int pinRead0 = analogRead(A0); // Read from analog pin A0 on ESP8266
double pVolt0 = (pinRead0 / 1024.0) * 3.3; // Convert the ADC value to voltage (ESP8266 uses 3.3V reference)
double persenCahaya = (pinRead0 / 1023.0) * 100;
float pulseFrequency = pulseCount;
flowRate = pulseFrequency / 7.5; // YF-S201: 1 liter/min = 7.5 Hz
pulseCount = 0;
// Send the data to Blynk virtual pins
Blynk.virtualWrite(V0, pinRead0); // Send the ADC value to Virtual Pin V0
Blynk.virtualWrite(V1, pVolt0); // Send the voltage value to Virtual Pin V1
Blynk.virtualWrite(V2, persenCahaya); // Send the light intensity percentage to Virtual Pin V2
// Send flow sensor data to Blynk virtual pins
Blynk.virtualWrite(V3, flowRate); // Send the flow rate to Virtual Pin V3
}