Page 141 - The Definitive Guide to Building Java Robots
P. 141
Preston_5564C04.fm Page 122 Wednesday, October 5, 2005 7:22 AM
122 CHAPTER 4 ■ SENSORS
Sometimes you may not want to use the stamp class for access but instead create a class
you can use to access just the compass by itself. In this case, the final example in this section
does just that.
Code Objective
The objective of this example is to model a compass with a separate class.
Code Discussion
The class is very simple. The constructor takes JSerialPort, which is used to construct the
CompassClass in Example 4-2. Then the getHeading() method just calls the getHeading()
method in the CompassStamp class by passing the CMD_DEVANTECH parameter. (See
Example 4-3.)
Example 4-3. Compass.java
package com.scottpreston.javarobot.chapter5;
import com.scottpreston.javarobot.chapter2.JSerialPort;
import com.scottpreston.javarobot.chapter2.SingleSerialPort;
public class Compass{
private CompassStamp cStamp;
public Compass(JSerialPort sPort) throws Exception{
cStamp = new CompassStamp(sPort);
}
public int getHeading() throws Exception{
return cStamp.getHeading(CompassStamp.CMD_DEVANTECH);
}
public static void main(String[] args) throws Exception{
try {
// since i am testing at my desk and not on my robot
Compass compass = new Compass(SingleSerialPort.getInstance(1));
System.out.println("Compass Heading = " + compass.getHeading());
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
97022d2480fe4a63cfdfa123a6e70098