Apastrix
Apastrix

Reputation: 114

How to move a robot a certain distance and still manage sensors?

I have a robot with encoder feedback, and i want to use functions that move a robot a certain distance and turn it a certain angle, so for example:

void loop(){

  if (Obstacle==false){  // if no obstacles

      forward(1000);  // move forward 1000 mm
      backward(1000); // move backward 1000 mm

      //...  
  }
}

Forward Function:

void forward(int distance){  // distance in mm

   int desiredRotationNumber= round(distance/circumference) ; 

   int desiredTicks = encoderResolution * desiredRotationNumber;

   if (counter < desiredTicks) // variable counter counts the pulses from the encoder
   {  
       analogWrite(motor,255);
   } 
   else 
   {
       analogWrite (motor,0); 
   }

}

The problem is that if i use the condition "if" my forward function will execute only once and then the program jumps to the next function, but if i use the "while loop" my move functions will execute correctly but i won't be able to manage sensors or anything.

Upvotes: 0

Views: 1778

Answers (1)

didierc
didierc

Reputation: 14730

What you probably want is to cut your moves in increments, and check the sensors in between each of these increments:

while (distance > 0 && !Obstacle){
    forward(step);
    distance-=step;
    check_sensors();
}

With multithreading, you could make those operations (moving and sensing) work asynchronously, and use some kind of event posting to warn each thread of a change. Here we're simulating that functionality by interwinding the tasks (you could also look into coroutines for a similar, yet much more effective idea).

Upvotes: 2

Related Questions