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

Preston_5564C02.fm  Page 39  Wednesday, September 14, 2005  5:42 AM



                                                                     CHAPTER 2  ■  SERIAL COMMUNICATION   39



                        test1:
                          SEROUT 16,16468,["a"]
                          GOTO main
                        test2:
                          SEROUT 16,16468,["b"]
                          GOTO main
                        getCompass:
                          SEROUT 16,16468,["180"]
                          GOTO main
                            The next class will communicate with the BASIC Stamp program we just created. It has a
                        single field, the StandardSerialPort called sPort. In the constructor, we create the port with an
                        int 1 corresponding to COM1 in Windows XP. Then we set the DTR to false because having it
                        true sets the Stamp to program mode, which we don’t want. Then we pause for 125 milliseconds to
                        give the port time to respond.
                             The next method, test(), returns a string. The expected string will either be “a” or “b”
                        depending on what was sent, because the Stamp program in the previous example just knows
                        how to return those two strings.
                            We will also add the close() method to close the StandardSerialPort, sPort.
                            In the main method, we will send to the test method bytes 101 and 102. We can also catch
                        any exception that could occur by using the StandardSerialPort. (See Example 2-10.)

                        Example 2-10. StampSerialTest.Java
                        package com.scottpreston.javarobot.chapter2;


                        public class StampSerialTest {
                            private StandardSerialPort sPort;


                            public StampSerialTest() throws Exception {
                                sPort = new StandardSerialPort(1);
                                sPort.setDTR(false);
                                Utils.pause(125);

                            }

                            public String test(byte something) throws Exception {
                                byte[] a = { something };
                                sPort.write(a);
                                Utils.pause(100);
                                return sPort.readString();
                            }
                            public void close() {
                                sPort.close();
                            }
   53   54   55   56   57   58   59   60   61   62   63