Moving without waiting, and stopping for an obstacle

While moveDist() runs, the program stands still. Commands ending in Async start the movement and return at once: the robot drives while the program reads sensors.

The second half of the lesson needs an ultrasonic distance sensor connected to ports P6 (trig) and P7 (echo).

Blocking and async commands

moveDist(50, 500)programrobotcallwaitsnext linemovingmoveDistAsync(50, 500)programrobotcallyour code keeps runningmovingtime
A blocking command holds the program until the movement ends. An async one only starts it.

Every movement command has an async twin: moveDist() and moveDistAsync(), rotate() and rotateAsync(), moveTo() and moveToAsync(). Three helpers go with them:

  • isMoving() — is the robot moving right now;
  • waitMove() — wait for the movement to end;
  • stop() — interrupt the movement.

Steps

  1. Show progress while moving

    robot.moveDistAsync(50, 800);
    while (robot.isMoving()) {
      robot.displayPrint("Dist", robot.getDistance());
      delay(100);
    }
    robot.displayClear();

    The robot drives while the loop puts the distance travelled on the screen ten times a second.

  2. Guard against getting stuck

    robot.moveDistAsync(50, 800);
    if (!robot.waitMove(5000)) {   // not there after 5 seconds?
      robot.stop(HARD);
      robot.displayPrint("STUCK!");
    }

    waitMove() with a number waits no longer than that many milliseconds and returns false if the robot still has not arrived.

  3. Remember: one command at a time

    There is no command queue. A new movement command cancels the current one.

    robot.moveDistAsync(50, 500);
    robot.rotateAsync(50, 90);   // cancels the line above: the robot only turns

    To run both, put robot.waitMove(); between them.

  4. Read the distance sensor

    UniDev module;
    
    int dist = module.ultraSonic(P6, P7);   // millimetres; 0 means "no echo"

    The sensor measures from 20 to 4000 mm. Zero is not “an obstacle right in front” but no answer at all, so it is always checked separately.

  5. Put the obstacle stop together

    #include <UNI.h>
    
    UniBase robot("UNI");
    UniDev module;
    
    const int OBSTACLE_MM = 150;   // stop distance
    const int TARGET_MM   = 1500;  // total travel distance
    const int FINISH_MM   = 5;     // closer than this to the goal counts as arrived
    
    void setup() {
      robot.begin();
      robot.resetDistance();
    }
    
    void loop() {
      // Goal reached — stay stopped. A move ends with a small residual to the goal,
      // so the remainder is compared with a margin rather than with zero:
      // otherwise the robot would keep "finishing" the last millimetre forever
      int remaining = TARGET_MM - (int)robot.getDistance();
      if (remaining <= FINISH_MM) {
        robot.displayPrint("DONE");
        delay(500);
        return;
      }
    
      int dist = module.ultraSonic(P6, P7);
      bool blocked = (dist > 0 && dist < OBSTACLE_MM);
    
      if (blocked) {
        if (robot.isMoving()) {
          robot.stop(HARD);
          robot.displayPrint("Obstacle", dist);
        }
      } else {
        if (!robot.isMoving()) {
          // Drive the rest of the way asynchronously while still watching the sensor
          robot.moveDistAsync(50, remaining);
          robot.displayClear();
        }
      }
    
      delay(50);
    }

    Twenty times a second the loop reads the sensor. With an obstacle it stops the robot; with a clear path and a standing robot it sends it off to cover the rest.

Finished sketches: File › Examples › UNI › AsyncMovement and ObstacleStop. The code is on the Examples page.

What should happen

1Hand closer than 15 cm — stop, the screen shows Obstacle and the distancehand< 15 cmObstacle1402Hand removed — it drives onstoodthe screen is backto X, Y and Angle3After 1.5 m — stop, the screen shows DONEDONE050 cm1 m1.5 m
The robot drives forward. A hand closer than 15 cm stops it, and the screen shows Obstacle and the distance in millimetres. Take the hand away and it drives on, with the coordinates back on the screen. After 1.5 m in all it stops and shows DONE.

Try changing it

  • Raise the stopping distance to 300 mm.
  • Blink the LED while the robot drives: robot.blinkLED(100) starts blinking, robot.blinkLED(0) stops it.
  • Go around the obstacle instead of waiting: a 90° turn, an arc, and back on course.
  • Light the stop with the light ring: module.pixelsAll(255, 0, 0).

If it does not work

  • The sensor always returns 0. Check that trig goes to P6 and echo to P7. The DistanceSensors example prints the readings to the Serial Monitor — a handy way to check the wiring.
  • The robot ignores the obstacle. Make sure the condition contains dist > 0 and that the obstacle reflects sound: soft fabric and slanted surfaces return a poor echo.
  • Only the last of two commands runs. Async commands need waitMove() between them — see Movement and Commands.
  • Light ring effects stop the sensor loop. They block the program for their whole duration — see Behavior and Blocking.