Page 105 - The Definitive Guide to Building Java Robots
P. 105
Preston_5564C03.fm Page 86 Wednesday, October 5, 2005 7:21 AM
86 CHAPTER 3 ■ MOTION
Code Discussion
To make things easier, I’m going to create a data structure called a ServoPosition, which I’ll
store in a list of commands. Though I could have used a second array, this seemed more readable.
(See Example 3-13.)
Example 3-13. ServoPosition.java
package com.scottpreston.javarobot.chapter3;
public class ServoPosition {
public int pin;
public int pos;
public ServoPosition (int pin, int pos) throws Exception{
if (pos > 255 || pos < 0) {
throw new Exception("Position out of range, 0-255 only.");
}
this.pin = pin;
this.pos = pos;
}
}
In MiniSscGM, I have two ArrayLists as fields. The first ArrayList commands will store all
the commands as a list of ServoPositions. The second will store all the servos as defined by their
current positions.
The constructor takes the JSerialPort and calls createServos(). This method just creates a
new ServoPosition and adds it to the ArrayList.
The sscCmd() method, required from the GroupMoveProtocol interface will just call the
move method of the same name and parameters.
The cmd() method adds servo positions to the ArrayList until the move() method is called
since move() is where all the action takes place.
In move(), the first thing we need to do is get the maximum difference between servo positions
in the command. This number will determine the step size for each duration. So if the total
move is 1000 milliseconds and the move size is 100 positions, I could tell the servo to move one
position every 10 milliseconds if both the protocol and servo were fast enough.
Next in move(), we need to determine the total number of steps based on the minimum
step size. Since the minimum size is 3, we would have a total of 33 steps in the command, each
of them taking (1000/33) = 30.
The last part of the move() method is incrementing the position, moving the servo, and
then pausing the program before it makes it’s next step. (See Example 3-14.)