Christian Nicolaisen
Christian Nicolaisen

Reputation: 45

Sphero: How to make it move a given length

I want to make the sphero move a given amount of centimeters ahead but so far i have not managed to get anything to work properly This is the code i have now:

EditText distanceText = (EditText) findViewById(R.id.distanceText);
int inputMSec = Integer.parseInt(distanceText.getText().toString());
int time = (inputMSec - inputMSec/2);

    // The ball is given the RollCommand at half speed.
    RollCommand.sendCommand(mRobot, heading,0.5f);

    // A handler is created to delay the Stop command.
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable(){

        @Override
        public void run() {
            // Makes the ball stop
            RollCommand.sendStop(mRobot);
        }
        // The variable 'time' defines how long the ball rolls until it is told to stop.
    }, time);

Is there any other command i can send to the ball instead of RollCommand? Or can anyone find out what to do to the input from the EditText so that the distance turns out correct?

Upvotes: 3

Views: 3990

Answers (1)

Fizzy
Fizzy

Reputation: 362

There's no API command that directly provides the ability to drive a given distance. The only way I now how is with an iterative strategy using the locator, which provides position information about the ball.

Here's an overview of the strategy. Let me know if you need more details.

  1. Turn on data streaming and request locator position data. You should now have some callback giving you Sphero position ~20x a sec. The positions are (x, y) coordinates on the floor in centimeters.
  2. Record the starting position of the ball (x0, y0).
  3. At each point in time, compute the distance the ball has traveled so far using the Pythagorean theorem/distance formula.
  4. Use this to figure out how far the ball has left to go. Call this distance D.
  5. Give a roll command where the speed is computed from D.

The big question is: how do you decide what speed to command based on D? I had some success with a strategy something like this: (undoubtedly you can tune it up a lot better).

  1. If the remaining distance D > 100cm, command full speed.
  2. Between D = 10cm and D = 100cm, command power ranging from 30% to 100% (linearly).
  3. If D < 10cm, command zero speed to make Sphero stop.

This worked pretty well. It would drive, slow down, and coast the last few inches to a stop. Problems with this algorithm include:

  1. You have to tune it to prevent overshoot/undershoot.
  2. When you want to command the ball to move only very short distance it doesn't work well, so you might have to tweak it to cover those cases.

Good luck!

Upvotes: 6

Related Questions