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

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



                 118    CHAPTER 4  ■  SENSORS



                              ' north east
                              IF east = 1 AND north = 1THEN
                                headingD = 45
                              ENDIF

                              ' north west
                              IF west = 1 AND north = 1 THEN
                                headingD = 315
                              ENDIF
                              ' south west
                              IF west = 1 AND south = 1 THEN
                                headingD = 225
                              ENDIF

                              ' south east
                              IF east = 1 AND south = 1 THEN
                                headingD = 135
                              ENDIF


                              SEROUT 16,16468,[DEC headingD]
                              GOTO main



                        ■Note  Make sure you have the directive for PBASIC 2.5 at the top of your Stamp program, otherwise you’ll
                        get compile errors on the if-then statements.



                            Next, I need to create a corresponding Java class that communicates with our compasses.
                        However, before I discuss this class, I’d like to show you a class diagram of how these sensors
                        relate to the classes in Chapter 2 (see Figure 4-10).
                            The CompassStamp class has four constants and one field. The constants are the actual
                        bytes that correspond to the Compass.bs2 in Example 4-1. Since they’re all unique, I can also
                        use them to enumerate the compasses in the class. The instance field, compass, I set defaulted
                        to the Devantech compass. This will be used in the class as the command sent to the BASIC
                        Stamp and used to determine the delay time for getting the reading.
                            This class has four public methods. The first two, setCompass() and getCompass(), set and
                        get the values for the compass reading. The other two getHeading() methods return the compass
                        heading as an int.
                            In getHeading(), first I create the byte[] that calls the parent execute() method. Then, because
                        the command string will return a string of tilde-delimited (~) integers, I parse and convert that
                        to an int so it can be returned. This method also uses the private method getCompassDelay()
                        because, depending on the current compass, the delay time to get the reading differs.
   132   133   134   135   136   137   138   139   140   141   142