/* * Assignment: Homework 2 - ESP32 Input & Output & Analog with Blynk
* Name: Yan Lin Tun
* ID: 6530092
* [cite: 2, 4]
*/
#define BLYNK_TEMPLATE_ID "TMPL6AcgGNKyX"
#define BLYNK_TEMPLATE_NAME "Hw2ESP32"
#define BLYNK_AUTH_TOKEN "Zk_WnzvYc7gjDUWDxSh4tnvkCATJLoW"
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <TaskScheduler.h>
// User-selected GPIO pins based on your Wokwi diagram [cite: 115, 116, 117]
const int ledPin = 0; // LED1 [cite: 115]
const int sw1Pin = 1; // SW1 [cite: 116]
const int sw2Pin = 2; // SW2 [cite: 116]
const int analogPin = 3; // POT (ADC0 / VP pin) [cite: 117]
// Filtering Variables (Your original logic)
int val = 0;
const int windowSize = 5;
float readings[windowSize];
int indexCount = 0;
bool bufferFull = false;
void t1Callback();
Task t1(1000, TASK_FOREVER, &t1Callback);
Scheduler runner;
// This function runs when the Blynk App "LED" button (V3) is toggled [cite: 114, 132]
BLYNK_WRITE(V3) {
int pinValue = param.asInt();
digitalWrite(ledPin, pinValue);
}
void setup() {
Serial.begin(115200);
// Pin Configuration [cite: 115, 116]
pinMode(ledPin, OUTPUT);
pinMode(sw1Pin, INPUT_PULLUP);
pinMode(sw2Pin, INPUT_PULLUP);
// Initialize Blynk with Wokwi's virtual WiFi [cite: 118, 119]
Blynk.begin(BLYNK_AUTH_TOKEN, "Wokwi-GUEST", "");
// Scheduler Setup
runner.init();
runner.addTask(t1);
t1.enable();
// Clear filter data [cite: 121]
for (int i = 0; i < windowSize; i++) readings[i] = 0.0;
}
void loop() {
Blynk.run(); // Process Blynk events
runner.execute(); // Process Scheduler tasks
}
void t1Callback() {
// 1. Read Analog and Filter (Soil Moisture logic) [cite: 121]
val = analogRead(analogPin);
// Map 12-bit ADC (0-4095) to 0-100% for the Blynk Gauge [cite: 121, 122]
float moisture = (float)val * 100.0 / 4095.0;
readings[indexCount] = moisture;
indexCount++;
if (indexCount >= windowSize) {
indexCount = 0;
bufferFull = true;
}
float filteredMoisture = getMovingAverage();
// Send filtered value to Blynk "Soil Moisture" Gauge (V2) [cite: 122, 137]
Blynk.virtualWrite(V2, filteredMoisture);
// 2. Send Switch Status to Blynk (V0 and V1) [cite: 123, 135, 136]
// INPUT_PULLUP is LOW when pressed, so we invert it for Blynk LED widgets
Blynk.virtualWrite(V0, !digitalRead(sw1Pin));
Blynk.virtualWrite(V1, !digitalRead(sw2Pin));
// Debugging to Serial Monitor
Serial.print("Raw: ");
Serial.print(val);
Serial.print(" | Filtered Moisture: ");
Serial.println(filteredMoisture);
}
// Your Moving Average function [cite: 121]
float getMovingAverage() {
float sum = 0;
int count = bufferFull ? windowSize : indexCount;
for (int i = 0; i < count; i++) {
sum += readings[i];
}
return (count > 0) ? sum / count : 0;
}