Overall code structure and virtual LED questions

Hi,

I’ve been learning a lot from the examples and posts here, I’m to the point where I’d appreciate some feedback and suggestions. Some of the code I wrote and other parts I copied from various web pages.

In my programs below, I know my brackets and formatting are not following best practices, so any suggestions or links to help me learn how to clean up the code would be great! Maybe even some C programming guides?

I’m trying to get a virtual LED to light up green when there is power and red when the power is off. (Basically using a wall wart and a UPS). In my PowerSensorStatus function, I can’t get the virtual led to light up green or red - I’d appreciate any advice on how to fix that. I’ll probably use an opto-isolator when I get it in, but in the meantime I was trying to manually set the state just to get the led to be either green or red.

I had a similar problem with LED lights for my function StillConnected

I’m using the Sparkfun ESP8266 Thing Dev



/*************************************************************
  Download latest Blynk library here:
    https://github.com/blynkkk/blynk-library/releases/latest

  Blynk is a platform with iOS and Android apps to control
  Arduino, Raspberry Pi and the likes over the Internet.
  You can easily build graphic interfaces for all your
  projects by simply dragging and dropping widgets.

    Downloads, docs, tutorials: http://www.blynk.cc
    Sketch generator:           http://examples.blynk.cc
    Blynk community:            http://community.blynk.cc
    Follow us:                  http://www.fb.com/blynkapp
                                http://twitter.com/blynk_app

  Blynk library is licensed under MIT license
  This example code is in public domain.

 *************************************************************
  This example runs directly on ESP8266 chip.

  Note: This requires ESP8266 support package:
    https://github.com/esp8266/Arduino

  Please be sure to select the right ESP8266 module
  in the Tools -> Board menu!

  Change WiFi ssid, pass, and Blynk auth token to run :)
  Feel free to apply it to any other example. It's simple!
 *************************************************************/

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial
#define DHTTYPE  DHT22 
#define DHTPIN   13
#define humidity_topic "sensor/humidity" //maybe don't need?
#define temperature_topic "sensor/temperature" //maybe dont need?


#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <DHT.h>
DHT dht(DHTPIN, DHTTYPE, 13); //  ESP8266 Temp sensor

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "XXXXXXXXXXX";
unsigned long startMillis;  //Garage door time open
unsigned long currentMillis; //set current time to variable
unsigned long period = 120000;  //3600000 milliseconds in one hour, 7200000 - 2 hours, 120000 - 2 minutes
BlynkTimer timer;

// In the app, Widget's reading frequency should be set to PUSH. This means
// that you define how often to send data to Blynk App.

 // ========{ Timer for garage door status and temp/humidity }==================

void myTimerEvent() 
{
  currentMillis = millis();  //get the current "time" moved here from loop...
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
   // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  int h = dht.readHumidity(); //changed from fload to int
  // Read temperature as Celsius (the default)
  int t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  int hif = dht.computeHeatIndex(f, h); //changed from float to int
  // Compute heat index in Celsius (isFahreheit = false)
  int hic = dht.computeHeatIndex(t, h, false); //changed from fload to int

 /* check working
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F"); */

  Serial.println(); //blank line
  Serial.print("Temperature: ");
   Serial.print(f); 
     Serial.println(); //blank line
  
  Blynk.virtualWrite(V2, f);
  Blynk.virtualWrite(V3, h);
  Blynk.virtualWrite(V4, hif);

if (f<60) {
Blynk.notify(String("Cold near Freezer : ") + f + String("°F"));
}
else {}

if (f>80) {
  Blynk.notify(String("Hot near Freezer : ") + f + String("°F"));
}
else {}

}


 // ========{ End Timer }==================


// ============= { Power Status } ================
void PowerSensorStatus() 
{

  // Insert code here to check for power outage based on a second "Wall wart"
  // power supply.   If the power fails no voltage will be seen on Digital pin 12
  // If the digitalRead is "1" ... the circuit is closed and power is on
  // If the digitalRead is "0" ... power has been lost to the unprotected
int currentState;
int priorState = currentState;
int powerStatus = digitalRead(12); //not sure, set pin 12 for read?

 if (powerStatus == 0)
  {
    // power is OFF
    // if the power is off and the current state has changed, send an alert and an email to display current powerStatus
    if (priorState != currentState)
    {
      WidgetLED led7(V7); //doesn't work ?? virtual led has no color
      Blynk.setProperty(V7, "color", "D3435C"); //red
      led7.on();  //could also use Blynk.virtualWrite(7, 1/HIGH/1023)?
      Blynk.notify("Power is OFF");
      Blynk.email("MYMAIL@gmail.com", "Subject: Power Status", "Power status has changed to OFF");
}
  }
  else
  {
    // power is ON 
    // if the power is ON and the current state has changed, send an alert and an email to display current powerStatus
    if (priorState != currentState)
    {
      WidgetLED led7(V7);
      Blynk.setProperty(V7, "color", "#23C48E"); //green
      led7.on();
      Blynk.notify("Power is ON");
      Blynk.email("MYMAIL@gmail.com", "Subject: Power Status", "Power status has changed to ON");
    
  }
  }}

// ============= { END Power Status } ================

  
// ================ { Check Connection if connected turn on Virtual LED on screen} ==================
 /* void StillConnected ()
 {
   if (Blynk.connect()) { //check to see if connected if so light led V1 in app ***********doesn't work*******
      Blynk.virtualWrite(V1, 1023);
    }
    else {
      Blynk.virtualWrite(V1,0);
    }
 } */

/*void StillConnected ()  //Still flashes virtual led even when not connected.
{
 while (Blynk.connect() == false) {
       // Wait until connected
  }
  Blynk.virtualWrite(V1, 1023);
  //Blynk.virtualWrite(V1, 0);
  }*/

 // ================ { End Check Connection } ==================

 // ========{ Garage Magnetic SW Monitoring Input }==================
void garageMagSensor ()
{
  //Serial.println(digitalRead(0)); TESTING only
  WidgetLCD lcd5(V5); //Garage door
  int garageSensorSW = digitalRead(0); // GPIO5
  int GarageOpenMinutes = (currentMillis - startMillis) / 1000 /60;
  if (garageSensorSW == LOW)
  {
    int DoorStatus = 1;
    lcd5.print(0, 0, "GARAGE IS CLOSED"); // LCD print, column 1, row 0.
   startMillis = currentMillis; //reset timer for garage open to current time
   period = 120000; // Reset the time garage door is open before push notify
   lcd5.print(0, 1, "                "); //prints spaces on second line to clear it out
  }
  else
  {
    int DoorStatus = 0;
    lcd5.print(0, 0, "GARAGE IS OPEN  "); // LCD print, column 1, row 0
 
    lcd5.print(0, 1, (String(GarageOpenMinutes) + String(" minutes"))); //used string to combine var and text
  
  }

if (currentMillis - startMillis >= period) //test if period has elapsed and push notify
{ 
 Blynk.notify(String("Garage door is open for: ") + GarageOpenMinutes + String(" minutes"));
 String EmailString;
 EmailString = String(GarageOpenMinutes) + " minutes";
 Blynk.email("MYMAIL@gmail.com", "Garage Open for",EmailString); // send email
period = period * 2; //delay next notification * 2
  Serial.print("Garage Door is open for: ");
  int GarageOpenMinutes = (currentMillis - startMillis) /1000 /60;
  Serial.print(GarageOpenMinutes);
  Serial.println(" minutes");
  
 //startMillis = millis(); //reset notify variable time
}
else
{ }

} 
//======== { End Garage magnetic sensor } ============


 // ========{ WiFi Setup }==================
void setup_wifi () 
{ 
  //delay(10);
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "DontPanic";
char pass[] = "itsonthefridge";
Serial.print("Connecting to ");
Serial.println(ssid);
Blynk.begin(auth, ssid, pass);


Blynk.notify("Freezer Thing Started");
Serial.println("Freezer Thing startup");


WidgetLCD lcd(V0);

IPAddress myip; 
   myip = WiFi.localIP();
 String fullip = String(myip[0]) + "." + myip[1] + "." + myip[2] + "." + myip[3]; 
lcd.print(0, 0, "IP Address:");
 lcd.print(0, 1, fullip); //Show IP on app V0
}  
 // ========{ End WiFi Setup }==================

 //=============={ Simple relay button }============ **Don't need GP4 works instead of virtual**
/* BLYNK_WRITE(V7) ***************** potentially caused a hang on startup, maybe because not declaired as void?? *************
{
 if (param.asInt() == 0) 
// if (param.asInt())
  {   
   digitalWrite(4, LOW); //GPI4
   Serial.print("LOW");
  } 
  else 
  {
  digitalWrite(4, HIGH); // GPI4
  Serial.print("HIGH");
  }
} */
//================{ End Simple relay button }=====================

//============ { Setup } =======================
void setup() { 
  // put your setup code here, to run once:
 // Debug console
  Serial.begin(9600);
  setup_wifi();
  //Blynk.syncAll(); //******what does this do?*******
 
// Setup a function to be called every x seconds
  timer.setInterval(15000L, myTimerEvent); //temp, humidity, heat index
  timer.setInterval(5000L, garageMagSensor); //check garage door status
  timer.setInterval(5000L, PowerSensorStatus); //check to see if power is on
  //timer.setInterval(500L, StillConnected); //check to see if still connected in app

pinMode(0,INPUT_PULLUP); //Garage Door mag sensor INPUT_PULLUP Keep on GP0! Maybe because of analog?
pinMode(12,INPUT); //Testing only, no led light on V7? not working PowerSensorStatus
/* Relay commands 
digitalWrite(4,HIGH); //Trying to set state of relay so it does not trigger on boot
//pinMode(4, HIGH); //Trying to set state of relay so it does not trigger on boot
pinMode(4,OUTPUT); //Garage door relay
End Relay commands  */ 
//delay(4000);
  
  /* Blynk.email("MYMAIL@gmail.com", "Subject: Alert Freezer Monitor Start", "Monitor for freezer started"); // send email */

} 
//============ { End Setup } =======================

//============== { Loop } ==========================
void loop() { 
    // put your main code here, to run repeatedly:
Blynk.run();
timer.run(); // Initiates BlynkTimer



} 

// ============== { End Loop } ==================== 



I’m looking at your code on my phone, so far from ideal, but I’d try writing a 255 (maximum brightness) to the virtual LED, as you may be changing its colour but if it’s not turned on the you won’t see the result.

Pete.

1 Like

Thank you, Pete for taking a look. I’ll try that out.

In case anyone else comes across this thread, I fixed the code. It was a problem with my if statements and I needed to make this a global variable:
int priorState = digitalRead(12); //setup variable for PowerSensorStatus (notify flag)
at the top of the program.

// ============= { Power Status } ================
void PowerSensorStatus() 
{

  // Insert code here to check for power outage based on a second "Wall wart"
  // power supply.   If the power fails no voltage will be seen on Digital pin 12
  // If the digitalRead is "1" ... the circuit is closed and power is on
  // If the digitalRead is "0" ... power has been lost to the unprotected
int powerStatus = digitalRead(12); //not sure, set pin 12 for read?
int currentState = powerStatus;
//int priorState = digitalRead(12); //trying as global var to set once in setup
 Serial.print("PowerStatus= ");
 Serial.println(powerStatus);

 if (powerStatus == 0)
  {
    //Serial.println("PowerStatus loop power is off");
    // power is OFF
    WidgetLED led7(V7); //doesn't work ?? virtual led has no color
      Blynk.setProperty(V7, "color", "#D3435C"); //red
      led7.on();  //could also use Blynk.virtualWrite(V7, 1/HIGH/1023)?
      led7.setValue(255);
         // if the power is off and the current state has changed, send an alert and an email to display current powerStatus
            if (priorState != currentState)
           {
              Blynk.notify("Power is OFF");
              // Blynk.email("me@gmail.com", "Subject: Power Status", "Power status has changed to OFF");
             priorState = currentState;
           }
  }
  else {}

if (powerStatus == 1)
  {
     //Serial.println("PowerStatus loop power is on");
    // power is ON 
      WidgetLED led7(V7);
      Blynk.setProperty(V7, "color", "#23C48E"); //green
      led7.on();
      led7.setValue(255);
      // if the power is ON and the current state has changed, send an alert and an email to display current powerStatus
            if (priorState != currentState)
          {
           Blynk.notify("Power is ON");
           //  Blynk.email("me@gmail.com", "Subject: Power Status", "Power status has changed to ON");
            priorState = currentState;
          }
  }
  else {}
    
}

// ============= { END Power Status } ================

I’m sure it could be cleaned up some, but it seems to be working!