How to run the ultrasonic sensor while the button Blynk V2 is pressed?


BLYNK_WRITE(V1)
{
  int x = param[0].asInt();
  int y = param[1].asInt();

  // Do something with x and y
  /*  Serial.print("X = ");
    Serial.print(x);
    Serial.print("; Y = ");
    Serial.println(y);*/
  if (y > 220)
    forward();
  else if (y < 35)
    backward();
  else if (x > 220)
    right();
  else if (x < 35)
    left();
  else
    Stop();
}

  int z;
   BLYNK_WRITE(V2)
{
   int z=param.asInt();
  if ( z==1 )
  {
    digitalWrite(m11, HIGH);
    digitalWrite(m12, LOW);
    digitalWrite(m21, HIGH);
    digitalWrite(m22, LOW);    
    delay(2000); //CHANGE THIS ACCORDING TO HOW THE ROBOT TURNS.
  }
   else
   {
    digitalWrite(m11, LOW);
    digitalWrite(m12, LOW);
    digitalWrite(m21, LOW);
    digitalWrite(m22, LOW);
   }
  }

void loop()
{
  Blynk.run();
  
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;

  if (z)
  {
    if (distance<20)
    {
    digitalWrite(m11, HIGH);
    digitalWrite(m12, LOW);
    digitalWrite(m21, LOW);
    digitalWrite(m22, LOW);
    delay(1000);
    digitalWrite(m11, HIGH);
    digitalWrite(m12, LOW);
    digitalWrite(m21, HIGH);
    digitalWrite(m22, LOW);   
   }
   else
   {
    z;
   }
  }
}

Hello… in answer to your titled question… First you read the prerequisite Welcome Topic…

Then go back and edit your first post to properly format your posted code…

Blynk%20-%20FTFC

Next, read the Help Files for proper ways to code with Blynk (hint, your current void loop() is bad for Blynk)…

http://help.blynk.cc/getting-started-library-auth-token-code-examples/blynk-basics/keep-your-void-loop-clean

http://help.blynk.cc/getting-started-library-auth-token-code-examples/blynk-basics/how-to-control-anything-with-blynk-app

http://help.blynk.cc/getting-started-library-auth-token-code-examples/blynk-basics/how-to-display-any-sensor-data-in-blynk-app

Then search this forum for keywords like ultrasonic… (hint I have a topic full of examples, including one for ultrasonic)…

https://community.blynk.cc/search?q=ultrasonic%20sensor

And finally, read those articles, try out the examples and have fun learning :wink:

2 Likes

:joy::joy::joy:

Well, I saw the OP was back in the forum since my post, but did nothing about fixing his post or clicking on any links.

So I formatted the post for him… was either that or delete the topic as warned in the instructions… maybe next time :wink:

1 Like

he is going to sleep until summer.
:joy::joy::joy: