Page 76 - The Definitive Guide to Building Java Robots
P. 76
Preston_5564C03.fm Page 57 Wednesday, October 5, 2005 7:21 AM
CHAPTER 3 ■ MOTION 57
Now that I have an interface defined for all SSC communication, I’m ready to create the
base SSC class. Like Controller.java I made this class abstract because I want to write two
implementations that reuse functionality (for example, the move() method).
This class has a single field, maxPin, because I also want to differentiate how many pins
each child class of the SSC has. Depending on the servo controller you have, make sure you set
this accordingly.
The constructor takes the JSerialPort. In the move method, I add error handling to the
input parameters, throwing an exception if the parameters are out of bounds, and then create
a byte[] with the parameters before calling the execute method from the Controller parent class. In
the byte[] sent via the execute() method, I added the sync byte of 255 each time, because we
know we have to send it as part of the SSCProtocol. (See Example 3-4.)
Example 3-4. SSC.java
package com.scottpreston.javarobot.chapter3;
import com.scottpreston.javarobot.chapter2.Controller;
import com.scottpreston.javarobot.chapter2.JSerialPort;
public abstract class Ssc extends Controller implements SSCProtocol{
// maximum possible for LM32
private int maxPin = 31;
// takes JSerialPort
public Ssc(JSerialPort serialPort )throws Exception {
super(serialPort);
}
// move will send signal to pin (0-7) and pos (0-255)
public void move(int pin, int pos) throws Exception{
// keep pos in valid range
if (pos < 0 || pos >255) {
throw new Exception("Position out of range, must be ➥
between 0 and 255. Value was " + pos + ".");
}
// keep pin in valid range
if (pin < 0 || pin > maxPin) {
throw new Exception("Pin out of range, must be between 0 and "
+ maxPin + ". Value was " + pin + ".");
}
// create byte[] for commands
byte [] b = new byte[] {(byte)255,(byte)pin,(byte)pos};
// send those bytes to controller
execute(b,0);
}