BLYNK
HOME       📲 GETTING STARTED       📗 DOCS       ❓HELP CENTER       👉 SKETCH BUILDER

A simple key to enable or disable the app

I need a simple key to enable or disable the app. It is a simple ultrasonic distance measurement system. But I do not want him to keep sending pulses all the time. For this I would like a simple turn on and turn off key. This seems very simple and in fact should be simple, but as I am new to this environment I am making many simple mistakes that have kept me from achieving this goal. Thanks for any help …
Thank you

Cesar

This is the code:

// This #include statement was automatically added by the Particle IDE.
#include <blynk.h>

// This #include statement was automatically added by the Particle IDE.


/*
 Ping))) Sensor
 
 This sketch reads a PING))) ultrasonic rangefinder and returns the distance
 to the closest object in range. To do this, it sends a pulse to the sensor to
 initiate a reading, then listens for a pulse to return. The length of the
 returning pulse is proportional to the distance of the object from the sensor.
 
 The circuit:
 - +V connection of the PING))) attached to +5V
 - GND connection of the PING))) attached to ground
 - SIG connection of the PING))) attached to digital pin 7
 
 created 3 Nov 2008
 by David A. Mellis
 modified 30 Aug 2011
 by Tom Igoe
 
 This example code is in the public domain.
 
 http://www.arduino.cc/en/Tutorial/Ping
 */

// this constant won't change. It's the pin number of the sensor's output:


const int pingPin = 7;
char auth[] = "";

void setup() {
     Blynk.begin(auth);
     delay(100);
    // initialize serial communication:
    Serial.begin(9600);
    
    
}
void loop() {
    Blynk.run();
    // establish variables for duration of the ping, and the distance result
    // in inches and centimeters:
    long duration, inches, cm;
    
    // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
    // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
    pinMode(pingPin, OUTPUT);
    digitalWrite(pingPin, LOW);
    delayMicroseconds(2);
    digitalWrite(pingPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(pingPin, LOW);
    
    // The same pin is used to read the signal from the PING))): a HIGH pulse
    // whose duration is the time (in microseconds) from the sending of the ping
    // to the reception of its echo off of an object.
    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin, HIGH);
    
    // convert the time into a distance
    inches = microsecondsToInches(duration);
    cm = microsecondsToCentimeters(duration);

    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
Blynk.virtualWrite(V20, cm);
    delay(100);
}

long microsecondsToInches(long microseconds) {
    // According to Parallax's datasheet for the PING))), there are 73.746
    // microseconds per inch (i.e. sound travels at 1130 feet per second).
    // This gives the distance travelled by the ping, outbound and return,
    // so we divide by 2 to get the distance of the obstacle.
    // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
    return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
    // The speed of sound is 340 m/s or 29 microseconds per centimeter.
    // The ping travels out and back, so to find the distance of the object we
    // take half of the distance travelled.
    return microseconds / 29 / 2;
}

That’s a lot of use of the word simple :stuck_out_tongue:

First, I fixed your code posting as required in the instructions…

Secondly, You shouldn’t be running all that code directly in your void loop() - Use timed function calls instead, which would also make it possible to enable/disable that function as needed via various methods, App button, Physical button, time, environmental condition, etc.

For the basics on timers, see these directions… particularly the PUSH section.

http://docs.blynk.cc/#blynk-firmware-blynktimer

Also, remember to use the search function in this forum to find info, answers, ideas, and so on… E.g. here is an example of using the Ultrasonic sensor with Blynk…

Dear Gunner,
At first thanks for your teachings, especially on the voide loop.
However, I would like to implement the code for the Paralax ultrasonic device that has only 3 terminals and not four. Also I need a version without the servo.
I already tried some variants on top of its original design but I did not succeed. Thanks if you can help me with this …

Thank you,

Cesar

Google the difference and how to adjust the code… it is NOT a Blynk specific thing.

So, remove the servo code :stuck_out_tongue_winking_eye:

Dear Gunner,
Thanks for your teachings. It is working now.
However, I would like to do the same with other kind of sensors. In this case, I have no “PingTimer” to be enable or disable. What could be used instead ?

Thanks,

Cesar

Put a button (configured as switch) in your blynk app, having configured the pin as V0 or whatever you wants…

Create a global boolean variable in your program named like RunMyCode or anything else and sync this var with the app button… and the magic will be done.

#include ...
bool RunMyApp=false;
....
BLYNK_CONNECTED() // Every time we connect to the cloud.
{
    Blynk.syncVirtual(V0);
}
BLYNK_WRITE(V0)
{
    RunMyApp=param.asInt();
}
void RunApp()
{
....
}
void setup()
{
    ...
    Blynk.begin(Blynk_auth,ssid,pass);
    ...
}
void loop()
{
    Blynk.run();
    if (RunMyApp) RunApp();
}

Sorry for my ignorance but could you explain me more deep the segment:

void RunApp()
{

}

This is really new for me…

Thanks,

Cesar

I am not sure if I understood correctly about void RunApp. Supposing that would be a generic designation, I am trying the following example for a IR thermometer no contact. This is not working…
However, if RunApp would be some specific command I don`t know How to use this correctly. Could you explain me better…
Thank you

I tried this code:

@langoni please repost your code with proper formatting, i fixed your first post, but can only remove any further unformatted code.

Blynk - FTFC

As for your uncertainty about void RunApp() it is just a basic Arduino loop/function, it could be named almost anything.

It is NOT a Blynk specific process, so if you are unfamiliar with basic Arduino code I recommend searching online for some Arduino programming sites.

More information here…

https://www.arduino.cc/reference/en/language/variables/data-types/void/

https://www.arduino.cc/en/Reference/FunctionDeclaration

You ask about a simple key for enable/disable your app… I wrote you a simple solution… I wrote RunApp but it could be DoThis, or Supercalifragilistoespialidoso() the name doesn’t matter…

3 Likes

This is my test code, including the suggestion from Trystan. Obviously I am doing some thing wrong but It is not clear to me. My experience wit Particle, Arduino Codes and Blynk is less than 6 months. I am trying to learn the logic of the matter. Thanks for any help.


// This #include statement was automatically added by the Particle IDE.
    #include <blynk.h>
    #include <Adafruit_MLX90614.h>
    
                                                                bool RunMyApp=false;
    
    Adafruit_MLX90614 mlx = Adafruit_MLX90614();
    char eventinfo[64];
    int publishdelay = 60 * 1000;
    char auth[] = "c52e71e46b9441ab9fb8467b56676c20";
   
                                                                
                                                                BLYNK_CONNECTED() // Every time we connect to the cloud.
                                                                {
                                                                Blynk.syncVirtual(V0);
                                                                }
                                                                BLYNK_WRITE(V0)
                                                                {
                                                                RunMyApp=param.asInt();
                                                                }
                                 
    void InitializeMLX90614(){
    if (!mlx.begin()) {
    Serial.println("Could not find a valid MLX90614 sensor, check wiring!");
    while (1) {}
     }
 }
    void Publish(char* szEventInfo){
    Spark.publish("IR_Thermometer", szEventInfo);
 }   
    // Publish Temperature
    void PublishMLX90614Info(){
    float objectT = mlx.readObjectTempC(); // Get updated object temperature
    float ambientT = mlx.readAmbientTempC();// Get updated ambient temperature
    sprintf(eventinfo, "TempObject=%.2f|°C", objectT);
    Publish(eventinfo);
    sprintf(eventinfo, "TempAmbient=%.2f|°C", ambientT);
    Publish(eventinfo);
    Blynk.virtualWrite(V11, objectT);
    Blynk.virtualWrite(V12, ambientT);
 }
    // Initialize applicaiton
    void InitializeApplication(){
    Serial.begin(9600);
    pinMode(D7, OUTPUT);
 }
    // Blink LED and wait for some time
    void BlinkLED(){
    digitalWrite(D7, HIGH);
    delay(500);
    digitalWrite(D7, LOW);
    delay(500);
    delay(publishdelay);
 }
    void setup() {
    InitializeApplication();
    Serial.println("Initializing sensor...");
    InitializeMLX90614();
    Blynk.begin(auth);    
    delay(2000);
    if(!mlx.begin()){
    String errorMessage;
    errorMessage = "Not found";
    Spark.publish("MLX90614 Error", errorMessage);
    }
}
    void loop() {
    Blynk.run(); 
    
                                                                  if (RunMyApp)  InitializeMLX90614();
    
    PublishMLX90614Info();
    delay(2000);
}

try this…

#include <blynk.h>
#include <Adafruit_MLX90614.h>
#include <Tasker.h> //you can find it at arduino library's gestor
bool RunMyApp=false;

Adafruit_MLX90614 mlx = Adafruit_MLX90614();
char eventinfo[64];
int publishdelay = 60 * 1000;
char auth[] = "**********"; //don't share your authcode so easily...
Tasker task(true);

BLYNK_CONNECTED() // Every time we connect to the cloud.
{
  Blynk.syncVirtual(V0);
}
BLYNK_WRITE(V0)
{
  RunMyApp=param.asInt();
  if (RunMyApp) task.setInterval(PublishMLX90614Info,2000L);// will publish every 2 seconds
  else task.cancel(PublishMLX90614Info);//will cancel the timer
}

void InitializeMLX90614()
{
  if (!mlx.begin())
  {
    Serial.println("Could not find a valid MLX90614 sensor, check wiring!");
    while (1) {};
  }
}
void Publish(char* szEventInfo)
{
  Spark.publish("IR_Thermometer", szEventInfo);
}   
// Publish Temperature
void PublishMLX90614Info()
{
  float objectT = mlx.readObjectTempC(); // Get updated object temperature
  float ambientT = mlx.readAmbientTempC();// Get updated ambient temperature
  sprintf(eventinfo, "TempObject=%.2f|°C", objectT);
  Publish(eventinfo);
  sprintf(eventinfo, "TempAmbient=%.2f|°C", ambientT);
  Publish(eventinfo);
  Blynk.virtualWrite(V11, objectT);
  Blynk.virtualWrite(V12, ambientT);
}
// Initialize applicaiton
// Blink LED and wait for some time
void BlinkLED()//this function isn't called in your code
{
  digitalWrite(D7, HIGH);
  delay(500);
  digitalWrite(D7, LOW);
  delay(500);
  delay(publishdelay);
}
void setup()
{
  Serial.begin(9600);
  pinMode(D7, OUTPUT);
  Serial.println("Initializing sensor...");
  InitializeMLX90614();//<-- at this line if you get a !mlx.begin() the program exectution will stop and never will do the next line...
  Blynk.begin(auth);    
  //delay(2000);//try to avoid use of long delays....
  /*
  if(!mlx.begin())//<- this never will be executed due to it's checked before at InitializeMLX90614 and this condition only will be checked if mlx.begin()==true... 
  {
    String errorMessage;
    errorMessage = "Not found";
    Spark.publish("MLX90614 Error", errorMessage);
  }*/
}
void loop()
{
  Blynk.run(); 
  task.loop();
//  if (RunMyApp)  InitializeMLX90614(); //this is incorrect, run app is to publish info not to reinit the MLX each time...
//    if (RunMyApp)  PublishMLX90614Info(); //it should be some like this, but this not is the best way to do it...
  //delay(2000); do not use delays at loop, use timers instead, a perfect solution is use the Tasker.h library
}

If you need to execute mlx.begin() each time you post the sensor values, say it and i’ll change the code… i don’t know this sensor…

The code is working. All previous and current observations make sense now completely. I have only two questions to finish this topic:

1- Why,

void loop(){
Blynk.run();
 (RunMyApp) PublishMLX90614Info ();
}

would not be good away ? I have tested this option and this worked

2- What is the difference between execute mlx.begin () each time or not?

Thank you so much for spending your time and patience on teaching, I really appreciate it.

this will publish dozens of times per second


I don’t know this sensor …

Some sensors needs to be initialized each time it will be used… others don’t needs this and with only one initialization is done…

1 Like

Perfect… thank you.