Page 146 - The Definitive Guide to Building Java Robots
P. 146

Preston_5564C04.fm  Page 127  Wednesday, October 5, 2005  7:22 AM



                                                                                 CHAPTER 4  ■  SENSORS   127



                        Example 4-5. SwitchStamp.java
                        package com.scottpreston.javarobot.chapter5;

                        import com.scottpreston.javarobot.chapter2.Controller;
                        import com.scottpreston.javarobot.chapter2.JSerialPort;
                        import com.scottpreston.javarobot.chapter2.SingleSerialPort;

                        public class SwitchStamp extends Controller {

                            // commands set in basic stmap program
                            public static final int CMD_INIT = 100;
                            public static final int CMD_SINGLE = 101;
                            public static final int CMD_MULTI = 102;
                            // sensors
                            public static final int SINGLE_LINE_SENSOR1 = 0;
                            public static final int SINGLR_LINE_SENSOR2 = 1;
                            public static final int PROXIMITY_SENSOR = 2;


                            public SwitchStamp(JSerialPort sPort) throws Exception{
                                super(sPort);
                            }

                            public boolean getSingle() throws Exception{
                                // read single reading
                                String h = execute(new byte[] {CMD_INIT,CMD_SINGLE},25);
                                if (h.equalsIgnoreCase("1")) {
                                    return true;
                                } else {
                                    return false;
                                }
                            }

                            public String getMulti() throws Exception {
                                String r = execute(new byte[] {CMD_INIT,CMD_SINGLE},25);
                                String[] r2 = r.split("~");
                                String readings = "";
                                for (int i = 0; i < r2.length; i++) {
                                    // convert each byte to char which I append to create single number
                                    readings = readings + (char) new Integer(r2[i]).intValue();
                                }
                                return readings;
                            }
   141   142   143   144   145   146   147   148   149   150   151