Slow software performance when commanding motors

Anyone got any ideas why commanding motors would be slow?
I am observing long main loop times and, after profiling, a lot of the slowness seems to be due to commanding motors. It is taking what seems to be a very long time, though I’m a bit new to what times to expect (maybe this is fairly normal).

With Android Studio, I have two motors I am commanding as follows:
motor.setTargetPosition(ticks);
motor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
motor.setVelocity(speed);
Across the board, these operations are taking 4-8 ms, and sometimes around 14 ms.

Also, I have five other motors being driven with simple setPower calls. These are normally less than 1 ms, but every now and then those calls can take 4-8 ms each. When all four drivetrain motors do this, adding 24 ms to the main loop seems way out of whack.

Since multiple motors seem affected, I’m taking a wild guess that this is control/expansion hub related. I am doing Manual bulk caching (though I suppose that is primarily input related). Any thoughts anyone?
Thanks!

The first thing I’ll say is that unless you are issuing other commands elsewhere, there is no need to set the mode or set the velocity each time around the loop. In this case, the velocity is a MaxVelocity that the RUN_TO_POSITION mode will use to limit the actual power provided to the motor, based on the actual position vs the target position…

That being said, I beleive both of these commands will only forward the update to the Expansion Hub board (in the Control Hub or Expansion Hub) IF the commanded values are changing. So issuing the same command over and over again should actually be ignored.

That all being said, the times that you are seeing related to the transactions between the Android controller board, and the hardware interface board that actually controls the motors and encoders etc. The same hardware interface board exists in the Control Hub and the Expansion hub.

Each time Android talks to the hardware board, it does it over a serial bus that incurs about a 4 mS latency. Yes, that’s pretty slow, but it’s there because Phones were originally used in the robots.

So, any time you do a transaction to read or write data from/to the hardware you get this accumulating delay. So, each motor power/velocity command takes one transaction. Each single or bulk encoder read takes one transaction, each other sensor read takes one transaction (maybe two if it’s a complicated transaction) etc.

This is why output values are checked for change, and not sent if there is no change (your < 1mS times)

Unless the Hub firmware is updated, there is not much the SDK can do about these latencies.

Thank you @phil.malone. Appreciate the insight. Hopefully that gives us some things to try next season to optimize things a bit.