Hardware: NodeMCU (ESP-12E)
Platform : Android
Working on a water level indicator with a button to switch on the pump, The button can only be turned on if the PERCENTAGE is higher than 4 percent, and while the button is on and the water level reaches below 4 percent, the button should turn off the relay and also update the off position in the app.
Problem:
The button reads the on value and turns on the relay but it seems like it’s stuck in the on position and the relay also stays on…any help is appreciated.
And I’m not a programmer, just started with arduino and IOT, the attached code is an extraction of codes from different projects that people have posted on the web, I just compiled them.
/*
********************************************
14CORE ULTRASONIC DISTANCE SENSOR CODE TEST
********************************************
*/
#define trigPin 12
#define echoPin 13
#define relay 5
long duration, distance; // Duration used to calculate distance
#define BLYNK_PRINT Serial // Comment this out to disable prints and save space
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <math.h>
#include <SimpleTimer.h>
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "xxxxxxxxxxxxxxxxxxxxxxx";
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "xxxxx";
char pass[] = "xxxxxxxxxxxxxx";
SimpleTimer timer;
unsigned int notified = 0;
int percentage;
void setup()
{
Serial.begin (9600);
Blynk.begin(auth, ssid, pass);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(relay, OUTPUT);
timer.setInterval(2000, RepeatTask);
}
void RepeatTask()
{
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
Serial.println(distance);
}
BLYNK_READ(V6)
{
percentage = map(distance, 138, 7, 0, 100); //Convert distance into percentage for the guage.
Blynk.virtualWrite(6,percentage);// virtualpin 6 write percentage value
if (percentage <= 5 && notified == 0)
{
notified = 1;
//Blynk.email("xxx@email.com","PLEASE FILL THE TANK", "now");
} else if(percentage > 7)
{
notified = 0;
}
}
BLYNK_WRITE(V1) // Run this function when V1 button pressed.
{
int pinValue = param.asInt(); // Get status of V1.
if (pinValue == 1 && percentage > 4) { // If status of V1 is 1 and percentage is greater than 4
digitalWrite(relay, HIGH); // Turn on the relay
}else {
int pinValue = 0;
Blynk.virtualWrite(V1, pinValue); //Update button value to OFF
}
}
void loop() {
Blynk.run();
timer.run(); // Initiates SimpleTimer
}