With a virtual pin I want to command a digital output connected to a relay that turns a light on. When I power the board for the first time, I have to select/press the digital pin on the app where the relay is connected, then the virtual pin works fine.
In app I have two buttons: Virtual pin and Digital Pin. For the Virtual pin to work, I must press one time the digital pin, then it works OK until I power off /on the board.
Can´t find the reason why it doesn’t work from the start without pressing the digital app pin… Serial print says the virtual pin is ok, ldr values are ok…
Code explanation:
Garage light that turns on IF it is dark and door opens OR app virtual pin is enabled.
Light turns of IF it is dark (dont matter if door is open, its daytime) AND virtual pin is not selected (manual override).
Hysteresis is implemented to avoid an unstable relay switch.
The respective function is “lampadagaragem()”
Code:
#define BLYNK_PRINT Serial // Comment this out to disable prints and save space
#include <SPI.h>
#include <Ethernet.h>
#include <BlynkSimpleEthernet.h>
#include <avr/wdt.h> // required for watchdog timer
//counters
int i = 0;
int a = 0;
int onoff = 0;
int estadogaragem = 0;
int sensorpinogaragem = 11;
int luzgaragem = 0;
int releluz = 2;
int luminosidade = 0;
int pinoldr = 0;
int hysteresis = 20;
char auth[] = "xxx";
void heartbeatgaragem()
{
onoff = !onoff;
if (onoff == HIGH)
{
Blynk.virtualWrite(5, 1023);
}
else
{
Blynk.virtualWrite(5, 0);
}
}
BLYNK_WRITE(V8)
{
luzgaragem = param.asInt();
}
void lampadagaragem ()
{
luminosidade = analogRead(pinoldr);
if (((luminosidade >= (380 + hysteresis)) && (estadogaragem == HIGH)) || (luzgaragem == HIGH)) //if ldr value is high and door is open OR virtual pin is ON
{
digitalWrite(releluz, HIGH); //relay turns light ON
}
else if ((luminosidade < (380 - hysteresis)) && (luzgaragem == LOW)) //if ldr value is low AND virtual pin is LOW light turns OFF
{
digitalWrite(releluz, LOW);
}
else //light turns off otherwise
{
digitalWrite(releluz, LOW);
}
}
void estadoatual()
{
wdt_reset();
estadogaragem = digitalRead (sensorpinogaragem);
if (estadogaragem == HIGH)
{
Blynk.virtualWrite(2, 1023);
}
else
{
Blynk.virtualWrite(2, 0);
}
}
void setup()
{
pinMode (sensorpinogaragem, INPUT);
pinMode (releluz, OUTPUT);
pinMode (pinoldr, INPUT);
Serial.begin(9600);
wdt_enable(WDTO_8S); //turns on watchdog timer with 8 second countdoor. Sketch requires wtd_reset() to reset this, else a reboot is forced
Blynk.begin(auth);
}
void loop()
{
wdt_reset(); //reset the watchdog timer in any normal op that may take time.
Blynk.run();
i++;
a++;
if (a >= 10000)
{
heartbeatgaragem();
a = 0;
}
if (i >= 5000)
{
estadoatual();
lampadagaragem();
i = 0;
}
}