Page 92 - The Definitive Guide to Building Java Robots
P. 92
Preston_5564C03.fm Page 73 Wednesday, October 5, 2005 7:21 AM
CHAPTER 3 ■ MOTION 73
system will move per step defaulted to three), speed (how fast the servo will move between
steps), and the MiniSSC, which does the work.
The constructor is the JSerialPort and the move method calls separate methods to move
the horizontal and vertical control servos. The two methods horz() and vert() will look at the
current position values and then send corresponding serial signals to the SSC as long as the
positions are within the range of the pan and tilt system.
Rather than always using byte positions from 0 to 255, I added two methods horzDegree()
and vertDegree() that will convert angles from 0 to 180, and bytes from 0 to 255.
The other methods are there to move the pan and tilt mechanism in steps. This is useful if
you have a camera tracking system and you just want to move a step in a direction but don’t
know how far left, right, up, or down you want to move.
Because I want the pan and tilt to move smoothly from one position to another in the
setServoTiming() method, I perform some error checking to see if the movement rate specified
is greater than the maximum speed. For example, if the servo can move from 0 to 90 degrees in
240 milliseconds and I want it to move there in 200 milliseconds, I need to throw an exception
because the servo can not move that fast.
Also, if the step size is less than the minimum size, I need to throw an exception because
the servo can only respond to signals as fast as the serial controller can send them at a
9600-baud rate.
In the test method main(), I instantiate the PanTilt class with the StandardSerialPort
(JSerialPort), and then move left until it’s at its left limit, then right, then up, and then down.
Although throwing an exception is a rather sloppy way of coding it, I wanted to show you how
you can use the exceptions to prevent the system from hurting itself. (See Example 3-10.)
Example 3-10. PanTilt.java
package com.scottpreston.javarobot.chapter3;
import com.scottpreston.javarobot.chapter2.JSerialPort;
import com.scottpreston.javarobot.chapter2.SingleSerialPort;
public class PanTilt{
// connected to pin 6 of MinSSC-II
public static final int HORZ_SERVO = 6;
// connected to pin 7 of MinSSC-II
public static final int VERT_SERVO = 7;
private int horzPos = SSCProtocol.NEUTRAL;
private int vertPos = SSCProtocol.NEUTRAL;
// should set these to the best limits of your pan/tilt system
public static final int MAX_UP = 145;
public static final int MAX_DOWN = 45;
public static final int MAX_RIGHT = 235;
public static final int MAX_LEFT = 25;
public static final int VERT_NEUTRAL = 95;
public static final int HORZ_NEUTRAL = 140;
97022d2480fe4a63cfdfa123a6e70098