Running DC motor while checking the distance using ultrasonic sensor

Hello there,

What am actually doing is to make the ultrasonci sensor to check the distance once the progame is excuted to allow the motors to run if the condtion i made is true. I was able to do that using the attahced codes. What am trying to do i to keep checking the distance while the robot is navigating without the need of stoping the robot for a while. Meaning that the ultrasonci should stop the robot once the distance is less than 50cm. So my question is , is it possible to run two two functions at once which are driving the motors and keep checking the distance? Thanks in advnace.

if(voice ==  "*go" && FrontSensor1 > 50 )
  {
    Forward();

  }
  
  else
  {
    Stop();
  
   }
   }

is it possible to run two two functions at once

No. It IS possible for Forward() to measure distance, and take appropriate action if the distance goes below some threshold. Be aware, if you do this, that Forward() is no longer an appropriate name for the function.

It is better, however, to separate the "get moving" functionality from the "pick a direction" functionality.

Once you have decided that Forward() is the correct way to go, let the robot keep going that way until some other part of the code decides that a new direction is in order.

If you want help with snippets of code, you are going to get snippets of answers.

Please see http://snippets-r-us.com/

I am going to guess that the variable voice has been declared of type String, but

Usually, you cannot do things simultaneously, but

Hi,

It is certainly not the best way to solve your problem, but personaly I would use something like that:

void loop() 
    {
      PWM_Mode();
        delay(50);

      if(voice ==  "*go" && FrontSensor1 > 50 )
        { Forward();}
      else
        { Stop();   }
    }

void PWM_Mode()                                           
    {                 
        digitalWrite(URTRIG, LOW);    // a low pull on pin COMP/TRIG  triggering a sensor reading 
        delayMicroseconds(2); 
 
        digitalWrite(URTRIG, HIGH);                            // reading Pin PWM will output pulses 
        delayMicroseconds(10); 
          
        unsigned long DistanceMeasured=pulseIn(URPWM,LOW); 
        
        if(DistanceMeasured>=50000)                            // the reading is invalid.
          {  Serial.print("Invalid"); 
            FrontSensor1=1000;    //just to have a max value
          }     
        else                                                   // every 50us low level stands for 1cm
          {    FrontSensor1=DistanceMeasured/50; 
               Serial.print(FrontSensor1);             
          } 
        
     }

I hope that it can help you.