How do you use IF statements with Blynk?

Hi

I need help to try and understand how to use IF statements please using with Blynk, using Arduino i understand the concept and within reason i can use them fine, but with Blynk i don’t understand how to build the IF statement :frowning:

Example, i want to create an IF that says if Temp is more than Numeric Input Settings box in Blynk, that has Value of 26 fro example then run code for LED strip a certain colour? the else statements i am fine with once i understand the concept of IF using Blynk…

PS, i am not asking for anyone to do the code for me, just how the concept works in Blynk please i have tried to do this myself, and looked on google and so on, but i still can’t get this to work.

I am using NodeMCU to do this project…

PS the reason i want to use Blync is so i can remove physical buttons from my original project and then put all the part in a smaller box or tube… I am making a Spirit Box / Tube i have added the code i have done just using Arduino using Mega and this works fine… i just want to reduce the size of the box now and i think Blynk would be the perfect solution for this, and also i can get live data :slight_smile: and save the data too.

Thanks
Peter


/*
  NodeMCU has weird pin mapping.
  Pin numbers written on the board itself do not correspond to ESP8266 GPIO pin numbers. We have constants defined to make using this board easier:

  static const uint8_t D0   = 16;
  static const uint8_t D1   = 5;
  static const uint8_t D2   = 4;
  static const uint8_t D3   = 0;
  static const uint8_t D4   = 2;
  static const uint8_t D5   = 14;
  static const uint8_t D6   = 12;
  static const uint8_t D7   = 13;
  static const uint8_t D8   = 15;
  static const uint8_t D9   = 3;
  static const uint8_t D10  = 1;
  /* Comment this out to disable prints and save space */

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <DHT.h>
#include <Adafruit_NeoPixel.h>
//#include <SPI.h>

char auth[] = "---------------------------"; // Used for Blynk

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "------";
char pass[] = "--------";

#define DHTPIN D3         // What digital pin we're connected to
#define DHTTYPE DHT22     // DHT 22
#define PIN D4            // pin on the Arduino is connected to pin 3 for NeoPixels
#define LDRPin A0         // select the input pin for ldr A0
#define DELAYVAL 500      // Time (in milliseconds) to pause between pixels

Adafruit_NeoPixel strip = Adafruit_NeoPixel(12, PIN, NEO_GRB + NEO_KHZ800);

DHT dht(DHTPIN, DHTTYPE);
BlynkTimer timer;

int PlusTempNumber = 0;


BLYNK_WRITE(V90)// Numbers input box

{
  PlusTempNumber = param.asInt();
  int t = dht.readTemperature(); // or dht.readTemperature(HIGH) for Fahrenheit
  if (t >= V90) {
    for (int i = 12; i > 0; i--) {
      strip.setPixelColor(i, strip.Color(250, 0, 0)); // Red color.
      strip.show();
    }
  }
  else
  {
    for (int i = 12; i > 0; i--) {
      strip.setPixelColor(i, strip.Color(0, 0, 0)); // No color.
      strip.show();
    }
  }
}


void sendSensor()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V5, h);
  Blynk.virtualWrite(V6, t);
}


void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  dht.begin();
  strip.begin();
  strip.show();
  // Setup a function to be called every second
  timer.setInterval(1000L, sendSensor);
}

void loop()
{
  Blynk.run();
  timer.run();
}


//////////// Below Code is the what i want to reduce using Blynk i don't need help on this i have added just so you know what i want to achieve using Blynk reduce the code down //////////////////

#include <TEA5767Radio.h>
#include <Adafruit_NeoPixel.h>
#include <Button.h>
#include <Wire.h>
#include <Adafruit_MLX90614.h>= // Include IR thermometer library
Adafruit_MLX90614 mlx = Adafruit_MLX90614();
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>  // Needed by the EMIC2 library
//#include <SD.h>  // Needed by the EMIC2 library, though not utilized in this example
#include "EMIC2.h"


TEA5767Radio radio = TEA5767Radio();


#define PIXELS 572     // Number of NeoPixels
#define PIN 43         // pin on the Arduino is connected to pin 3 for NeoPixels
#define Radio 40       // Mosfet Pin
#define RX_PIN 50  // Connect SOUT pin of the Emic 2 module to the pin
#define TX_PIN 52  // Connect SIN pin of the Emic 2 module to the TX pin

EMIC2 emic;  // Creates an instance of the EMIC2 library

//---< Neo Pixels >---//
Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXELS, PIN, NEO_GRB + NEO_KHZ800);


//---< Temp Sensor >---//
// BME280 mySensor ; //Uses I2C address 0x76 (jumper closed) // temp sensor

// set the LCD address to 0x27 for a 20 chars 4 line display
LiquidCrystal_I2C lcd (0x27, 20, 4);
/*-----( Declare Variables )-----*/



// const int chipSelect = 4;

Button TempButton1(44); // Used to Higher Temp Connect your button between pin number and GND
Button TempButton2(45); // Used to Lower Temp Connect your button between pin number and GND

Button RadioButton1(46); // Used to Higher FRSpeedScan Connect your button between pin number and GND
Button RadioButton2(47); // Used to Lower FRSpeedScan Connect your button between pin number and GND


const int SensorsPinArray[4] = {35, 37, 39, 41}; // Sensor PIN array
int PlusAlarmTemp =  80; // starting default set point for temp adjustments
int MinusAlarmTemp = 60; // starting default set point for temp adjustments
int FRSpeed = 100;       // FRSpeedScan default speed
int sensorPin = A1;      // select the input pin for ldr
int sensorValue = 0;     // variable to store the value coming from the sensor



void setup() {


  Serial.begin(9600); // Used to enable Print data to serial port 9600 is port speed
  for (int i = 0 ; i < 4 ; ++i) {
    int Sensor = (digitalRead(SensorsPinArray[i]));
  }
  pinMode(SensorsPinArray[4], INPUT);
  emic.begin(RX_PIN, TX_PIN);
  emic.setRate(180);
  emic.setVolume(40);
  emic.setVoice(2);  // Sets the voice (9 choices: 0 - 8)
  TempButton1.begin(); // Used to Higher Temp
  TempButton2.begin(); // Used to Lower Temp
  RadioButton1.begin(); // Used to Higher FRSpeedScan
  RadioButton2.begin(); // Used to Lower FRSpeedScan
  lcd.init(); // initialize the lcd
  lcd.backlight(); //Backlight ON if under program control
  pinMode(Radio, OUTPUT); // Radio control pin as output
  digitalWrite(Radio, HIGH); // Turn the radio On
  //pinMode(SensorPins, INPUT);
  strip.begin(); // Neo Pixels Begin
  strip.setBrightness(3); // Brightness control for Neo Pixels
  strip.clear();
  Wire.begin();
  mlx.begin(); // MLX90614 IR thermometer Begin
  // mySensor.setI2CAddress(0x76); //Connect I2C sensor
  // mySensor.beginI2C();
  lcd.init(); // initialize the lcd
  lcd.backlight(); //Backlight ON if under program control
}


void SetTempPlus() //---< Set Plus Temp Start >---//
{
  if (TempButton1.pressed())
    PlusAlarmTemp = PlusAlarmTemp - 1; //Raise PlusAlarmTempHi by one
}
//---< Set Temp Plus End >---//

void SetTempMinus() //---< Set Minus Temp Start >---//
{
  if (TempButton2.pressed())
    MinusAlarmTemp = MinusAlarmTemp + 1; //Lower PlusAlarmTempLow by one
}
//---< Set Temp Minus End >---//


void FRSpeedScan() //---< Set FR Speed Scan Start >---//
{
  if (RadioButton1.pressed())
    FRSpeed = FRSpeed + 40; //Raise PlusAlarmTempHi

  if (RadioButton2.pressed())
    FRSpeed = FRSpeed - 20; //Lower PlusAlarmTempLow
}

//---< Set FR Speed Scan End  >---//

void MovementPixels() //---< Start Used for all movement sensors >---//
{
  for (int i = 563; i > 0; i--) {
    strip.setPixelColor(i, strip.Color(230, 80, 0)); // minus color.
  }
}//---< Start Used for all movement sensors >---//

void allpixels_off() //---< Turns All Pixels Off Actions >---//
{
  for (int i = PIXELS; i > 0; i--) {
    strip.setPixelColor(i, strip.Color(0, 0 , 0)); // minus color.
  }
}
//---< Turns All Pixels Off Actions End >---//


void TempDataPlusReading() //---< Plus Temperature Actions >---//
{

  int Temp = mlx.readObjectTempF();
  lcd.setCursor(1, 0); //Start at character 1 on line 0
  lcd.print("TEMP ");
  lcd.setCursor(6, 0); //Start at character 6 on line 0
  lcd.print(mlx.readObjectTempF(), 0);
  lcd.setCursor(1, 1); //Start at character 1 on line 1
  lcd.print("SET TEMP  +  ");
  lcd.setCursor(14, 1); //Start at character 14 on line 1
  lcd.print(PlusAlarmTemp);
  lcd.setCursor(1, 3); //Start at character 1 on line 3
  lcd.print("SET FREQ ");
  lcd.setCursor(13, 3); //Start at character 13 on line 3
  lcd.print(FRSpeed);

  if (Temp >= PlusAlarmTemp)
  {
    ForwardFrequency();
    digitalWrite(Radio, LOW);  // Turn the radio pin LOW
    delay(50);
    digitalWrite(Radio, HIGH); // Turn the radio pin HIGH
  }
  if (Temp >= PlusAlarmTemp)
  {
    for (int i = 572; i > 0; i--) {
      strip.setPixelColor(i, strip.Color(150, 0, 0)); // minus color.
      strip.show(); // This sends the updated pixel color to the hardware.
    }
    emic.speak("Warning High Temperature Change");
    allpixels_off();
  }
}
//---< Plus Temperature Actions End >---//

void TempDataMinusReading() //---< Temperature Actions >---//
{

  int Temp = mlx.readObjectTempF();
  lcd.setCursor(1, 2); //Start at character 1 on line 2
  lcd.print("SET TEMP  -  ");
  lcd.setCursor(14 , 2); //Start at character 14 on line 2
  lcd.print(MinusAlarmTemp);


  if (Temp <=  MinusAlarmTemp)
  {
    ReverseFrequency();
    digitalWrite(Radio, LOW); // Turn the MOSFET Switch OFF
    delay(50);
    digitalWrite(Radio, HIGH); // Turn the MOSFET Switch On
  }

  if (Temp <= MinusAlarmTemp)
  {
    for (int i = 572; i > 0; i--) {
      strip.setPixelColor(i, strip.Color(0, 0, 150)); // minus color.
      strip.show(); // This sends the updated pixel color to the hardware.
    }
  }
}

void LdrSensor() // ---< LDR sensor start >---//
{
  sensorValue = analogRead(sensorPin); // read the value from the sensor:
  lcd.setCursor(9, 0); //Start at character 1 on line 0
  lcd.print("LGT ");
  lcd.setCursor(13, 0); //Start at character 6 on line 0
  lcd.print(sensorValue); //prints the values coming from the sensor on the screen

  if (sensorValue > 400)
  {
    emic.speak("Warning ambient light detected");
  }

  /*
    if (sensorValue < 700) //setting a threshold value
    {
    LdrReverseFrequency();
    digitalWrite(Radio, LOW); // Turn the MOSFET Switch OFF
    delay(50);
    digitalWrite(Radio, HIGH); // Turn the MOSFET Switch On
    allpixels_off();
    }
  */
}
// ---< LDR sensor end >---//

void ForwardFrequency() //---< Sweep FM Range Forward Actions >---//
{
  int threshold = 1008;
  for ( int i = 810 ; i < 1008 ; i++) {
    float Frequency = i / 10.0 ;
    radio.setFrequency(Frequency); // pick your own frequency
    lcd.setCursor(13 , 3); //Start at character 10 on line 1
    lcd.print(Frequency);
    delay(FRSpeed);
  }
}
//---< Sweep FM Range Forward Actions End  >---//

void ReverseFrequency() // Radio sweep FM range reverse//
{
  int threshold = 1007;
  for ( int i = 1008 ; i >= 850 ; i-- ) {
    float Frequency = i / 10.0 ;
    radio.setFrequency(Frequency); // pick your own frequency
    lcd.setCursor(13  , 3); //Start at character 10 on line 1
    lcd.println(Frequency);
    delay(FRSpeed);
  }
}
//--- Radio sweep FM range reverse End ---//



void CapSensordataAll()  //--- All Sensors PIN array start---//
{

  for (int i = 0 ; i < 4 ; ++i) {
    int RfSensors = (digitalRead(SensorsPinArray[i]));

    if (RfSensors == HIGH) {
      MovementPixels();
    }

    else {
        allpixels_off();
      }
    }
  } 

//--- All Sensors PIN array end---//


void LdrReverseFrequency() // Ldr sweep FM range reverse//
{
  sensorValue = analogRead(sensorPin); // read the value from the sensor:

}
//--- Ldr sweep FM range reverse End ---//

void loop() {

  strip.show();             // This sends the updated pixel color to the hardware.
  SetTempPlus();            // Set Temp Plus Void
  SetTempMinus();           // Set Temp Minus Void
  FRSpeedScan();            // FR Speed Scan Void
  TempDataPlusReading();    // Plus Temp Data void
  TempDataMinusReading();   // Minus Temp Dat Void
  CapSensordataAll();
  LdrSensor();              // LDR Sensor Void
  //FrontSensor();            // Front Sensor affect all Orange pixels when HIGH
  //BackSensor();             // Back Sensor affect all Yellow pixels when HIGH
  //LeftSensor();             // Left Sensor affect all Pink pixels when HIGH
  //RightSensor();            // Right Sensor affect all Cyan pixels when HIGH
} 

Okay, you’ve obviously not understood the significance of this line of code:

It gets the value from the numeric input widget and saves it in the variable PlusTempNumber, which then allows you to use that variable in your if comparison, like this:

if (t >= PlusTempNumber) { 

However, there is a potential flaw in the structure of your code. The BLYNK_WRITE(V90) callback function only runs when the value of the numeric input widget changes, or when you use the Blynk.syncVirtual(V90) command - more on that later.

I’m assuming that you want to set the value in the app once, then have the NodeMCU use this value and continuously do the comparison with your readings from the DHT sensor?

If this is the case then the V90 callback should just be this:

BLYNK_WRITE(V90)// Numbers input box
{
  PlusTempNumber = param.asInt();
}

And the rest of the code in your current V90 callback should be moved to a function which you call with a timer - say every 10 seconds.

Now, back to the Blynk.syncVirtual(V90) command…
When your device boots-up the value of PlusTempNumber will be zero. You’ll probably want to get the latest value from the Blynk app (actually from the Blynk server).
Also, if the NodeMCU loses connectivity with the Blynk server for any reason, and the value of the numeric input widget changes during this time, then that change won’t be reflected in the NodeMCU’s sketch, as that change will be missed by the device.

To get around both of the issues we use another callback called BLYNK_CONNECTED, which is automatically triggered when the NodeMCU connects to the Blynk server - either for the first time at boot-up, or subsequently after loss of connectivity.

Your BLYNK_CONNECTED would look like this:

BLYNK_CONNECTED
{
  Blynk.syncVirtual(V90);
}

Pete.

Why would if statements be different for Blynk? We are still using C language. So if statements are as C language dictates

Hi Peter

Just letting you know it works fine now as far as i can see, also i didn’t realize how the functions where called using Blynk… I only realized when you said use a timer so i would have never got it to work either way ? or would it… Is the Timer used like when you put a function in the loop of arduino?

new code below

/*
  NodeMCU has weird pin mapping.
  Pin numbers written on the board itself do not correspond to ESP8266 GPIO pin numbers. We have constants defined to make using this board easier:

  static const uint8_t D0   = 16;
  static const uint8_t D1   = 5;
  static const uint8_t D2   = 4;
  static const uint8_t D3   = 0;
  static const uint8_t D4   = 2;
  static const uint8_t D5   = 14;
  static const uint8_t D6   = 12;
  static const uint8_t D7   = 13;
  static const uint8_t D8   = 15;
  static const uint8_t D9   = 3;
  static const uint8_t D10  = 1;
  /* Comment this out to disable prints and save space */

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <DHT.h>
#include <Adafruit_NeoPixel.h>

char auth[] = "---"; // Used for Blynk

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "---";
char pass[] = "----";

#define DHTPIN D3         // What digital pin we're connected to
#define DHTTYPE DHT22     // DHT 22
#define PIN D4            // pin on the Arduino is connected to pin 3 for NeoPixels
#define LDRPin A0         // select the input pin for ldr A0

Adafruit_NeoPixel strip = Adafruit_NeoPixel(12, PIN, NEO_GRB + NEO_KHZ800);

DHT dht(DHTPIN, DHTTYPE);
BlynkTimer timer;

int PlusTempNumber = 0; 

BLYNK_CONNECTED() {
  Blynk.syncVirtual(V90);
}

BLYNK_WRITE(V90)// Numbers input box
{
  PlusTempNumber = param.asInt();
}

void PlusTemp()
{
  int t = dht.readTemperature(); // or dht.readTemperature(HIGH) for Fahrenheit
  if (t > PlusTempNumber) {
    for (int i = 12; i > 0; i--) {
      strip.setPixelColor(i, strip.Color(250, 0, 0)); // Red color.
      strip.show();
    }
  }
  else
  {
    for (int i = 12; i > 0; i--) {
      strip.setPixelColor(i, strip.Color(0, 0, 0)); // No color.
      strip.show();
    }
  }
}

void sendSensor()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V5, h);
  Blynk.virtualWrite(V6, t);
}


void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  dht.begin();
  strip.begin();
  strip.setBrightness(3); // Brightness control for Neo Pixels
  strip.show();
  timer.setInterval(1000L, sendSensor);
  timer.setInterval(3000L, PlusTemp);
}

void loop()
{
  Blynk.run();
  timer.run();
}

Basically, Yes.
With ‘lazy’ C++ programming, if you want to do just one thing every 10 seconds then you can put the code in the void loop and stick a delay(10000) at the end.
Unfortunately, this stops (blocks) code execution entirely for 10 seconds, which isn’t good for Blynk, as the Blynk library needs to be constantly talking to the server in the background.

BTW, I fixed your code formatting in your second post, as you used the wrong symbol at the beginning and end.

Pete.

Hi Pete

BTW thank you for your help, I spent all day trying to get the IF to work and i wouldnt have worked it out without your help so thanks.

Peter

1 Like

Yep, the BLYNK_WRITE and param.asInt (or asFloat, asString) functions aren’t exactly intuitive, but very powerful once you’ve figured them out.

Give os a shout if you get stuck again, a few pointers in the right direction can save a lot of frustration.

Pete.