Page 140 - Hacking Roomba
P. 140
Chapter 6 — Reading the Roomba Sensors 121
Enumerations
Enumerations are a way of using a number to encode a list of things. The remote codes in
Table 2-2 are an example of such an enumeration. In RoombaComm they are dealt with by
creating a list of constants that can be checked against. For example, if you want to check to
see if the spin left button on the remote was being pressed, you can do this:
if( roombacomm.remoteOpcode() == RoombaComm.REMOTE_SPINLEFT) {
// do something
}
If you’re not inspecting the values of the enumeration, you can treat them as ordinary numbers,
which is useful when you need to store them (like you’re recording all remote control button
presses over a period of time).
Byte Values
Byte values present a special problem in Java because it doesn’t have the concept of an unsigned
byte. For example, if you want to implement a wrapper method that returns the left dirt sensor
value (a byte value from 0–255), your first inclination may be to implement it like this:
public byte dirtLeft() {
return sensor_bytes[DIRTLEFT];
}
This works well until the value goes over 127; then it becomes negative. This is because of the
decision to make all bytes signed in Java. Instead the following must be done:
public int dirtLeft() {
return sensor_bytes[DIRTLEFT] & 0xff;
}
From an efficiency standpoint, such a change is horrible because it adds an extra computation
and doubles the storage used. Java is rarely about computing or storage efficiency, however,
because it chooses to make a language that’s easier to use for most people. For the normal uses
of RoombaComm, the extra overhead doesn’t matter, but you should be aware of it when port-
ing RoombaComm to a more constrained platform (like a microcontroller).
Using Sensor Data
Any program you write to control the Roomba for more than a few seconds runs in a loop of
the following form:
while( !done ) {
lookAround()
doSomething()
}
In this loop, the hypothetical function lookAround() contains sensor reading functionality
and doSomething() moves the Roomba or otherwise controls its actuators. Advanced pro-
grams may have multiple loops of this type and ways to jump among them.