Home > Articles > Programming > Java

This chapter is from the book

Controlling the RCX Through a Network

Data communications is great for sending sensor readings back to the PC for analysis, but it can also be used for direct control of the RCX brick. In this project we take it one step further by controlling the RCX from another PC across a network—including the Internet (Figure 11–7). This type of control, where the controller is not present in the same space as the robot, is known as telerobotics. The NASA Mars mission controlled Sojourner using telero-botics, as the robot could not be controlled in real time due to the time it takes for radio signals to travel from Earth to Mars. Instead, Sojourner was given a series of instructions to complete on its own, depending on what the NASA controllers chose to do from the pictures they received. It was left up to the internal code of the robot to navigate around obstacles it encountered along the way to its destination.

Figure 11–7 Architecture for robot control over the Internet.

In this project we have a problem similar to the problem encountered by NASA. We don't have a time delay factor, as a robot could be controlled over a network almost real time, even across the Internet. The problem is that when our rover turns away from the IR tower we lose contact. The best we can do is give the robot a series of instructions, then wait for it to return to the IR tower and report back with some results.

The robot in this project can be any of the Navigator robots we programmed in Chapters 7, 8, and 10. This project is specifically programmed for the rotation sensor robot used in Chapter 8, which has been modified slightly to include a light sensor (Figure 11–8). The robot is given an array of coordinates to move to. Once it reaches the final coordinate it captures a light reading and then uses the coordinates in reverse to make its way back to the IR tower. Once there, it transmits the light reading to the PC. The code for the RCX side is simple, and uses the same concepts introduced in the explanation of leJOS RCX communications.

Figure 11-8 Tippy Senior modified with a light sensor.

The architecture for this project is a little more complex than the other projects in this book. It requires code to run on three separate platforms—a client computer, a server, and the RCX brick (Figure 11–7). There are also two separate media used for data transfer—the Internet and IR light. The client application sends user commands from the client to the server. The server acts as a sort of middle man, shuffling commands from the user to the RCX and vice versa. The robot just sits in front of the IR tower waiting for a destination. When it has some coordinates it takes off and records a light reading at the farthest point. Let's examine this code first:

 1. import josx.platform.rcx.*;
 2. import josx.robotics.*;
 3. import josx.platform.rcx.comm.*;
 4. import java.io.*;
 6. public class RCXExplorer {
 7.    DataInputStream in;
 8.    DataOutputStream out;
 9.    Navigator robot;
10.    final byte ARRAY_SIZE = 4;
11.    short [] xCoords;
12.    short [] yCoords;
14.    public RCXExplorer() {
15.       // TimingNavigator Constructor for Tippy Senior:
16.       robot = new TimingNavigator(Motor.C, Motor.A, 4.475f, 1.61f);
17.       RCXDataPort dp = new RCXDataPort();
18.       in = new DataInputStream(dp.getInputStream());
19.       out = new DataOutputStream(dp.getOutputStream());
20.       xCoords = new short [ARRAY_SIZE];
21.       yCoords = new short [ARRAY_SIZE];
22.    }
24.    public static void main(String [] args) {
25.       RCXExplorer re = new RCXExplorer();
26.       while(true) {
27.          re.readCoordinates();
28.          short lightValue = re.fetchValue();
29.          re.returnValue(lightValue);
30.       }
31.    }
33.    /** Reads coordinates from PC into arrays.*/
34.    public void readCoordinates() {
35.       try {
36.          for(int i=0;i<ARRAY_SIZE;++i) {
37.            xCoords[i] = in.readShort();
38.            yCoords[i] = in.readShort();
39.          }
40.       } catch(IOException e) {}
41.    }
43.    /** Sends bot to destination to sample light value.*/
44.    public short fetchValue() {
45.       Sensor.S2.activate();
46.       for(int i=0;i<ARRAY_SIZE;++i)
47.          robot.gotoPoint(xCoords[i],yCoords[i]);
48.       short light = (short)Sensor.S2.readRawValue();
49.       Sensor.S2.passivate();
50.       return light;
51.    }
53.    /** Sends bot back to starting point and sends value to PC.*/
54.    public void returnValue(short val) {
55.       for(int i=ARRAY_SIZE-1;i>-1;--i)
56.          robot.gotoPoint(xCoords[i],yCoords[i]);
57.       robot.gotoPoint(0,0);
58.       robot.gotoAngle(0);
59.       try {
60.          out.writeShort(val);
61.          out.flush();
62.       } catch(IOException ioe) {}
63.    }
64. }

The next part of our project is the server code. It is responsible for accepting an array of coordinates from a client on another PC and passing those to the RCX. It is also responsible for waiting for the RCX and sending the light reading back to the client computer. Let's examine this code:

 1. import java.net.*;
 2. import java.io.*;
 3. import pc.irtower.comm
 5. public class ExplorerServer {
 7.    ServerSocket server;
 8.    Socket client;
 9.    DataOutputStream clientOutStream;
10.    DataInputStream clientInStream;
11.    PCDataPort port;
12.    DataInputStream inRCX;
13.    DataOutputStream outRCX;
15.    public ExplorerServer(int portNumber) {
16.      try {
17.        // Internet connection:
18.        server = new ServerSocket(portNumber);
20.        // RCX Connection:
21.        port = new PCDataPort("COM2");
22.        inRCX = new DataInputStream(port.getInputStream());
23.        outRCX = new DataOutputStream(port.getOutputStream());
24.      }
25.      catch (IOException io){
26.         io.printStackTrace();
27.         System.exit(0);
28.      }
29.    }
31.    public static void main(String [] args) {
32.      ExplorerServer host = new ExplorerServer(ExplorerCommand.PORT);
33.      while(true) {
34.         host.waitForConnection();
35.         while(host.client!=null)
36.           host.waitForCommands();
37.      }
38.    }
40.    /** Wait for a connection from the Client machine */
41.    public void waitForConnection() {
42.      try {
43.         System.out.println("Listening for client.");
44.         client = server.accept();
45.         clientOutStream = new DataOutputStream(client.getOutputStream());
46.         clientInStream = new DataInputStream(client.getInputStream());
47.         System.out.println("Client connected.");
48.      } catch(IOException io) {
49.         io.printStackTrace();
50.      }
51.    }
53.    /** Wait for coordinates from the Client machine */
54.    public void waitForCommands() {
55.      int [] x = new int[ExplorerCommand.ARRAY_SIZE];
56.      int [] y = new int[ExplorerCommand.ARRAY_SIZE];
57.      try {
58.         for(int i=0;i<ExplorerCommand.ARRAY_SIZE;++i) {
59.           x[i] = clientInStream.readInt();
60.           y[i] = clientInStream.readInt();
61.         }
62.      } catch(IOException io) {
63.         System.out.println("Client disconnected.");
64.         System.exit(0);
65.      }   
66.      sendCommandsToRCX(x, y);
67.      waitForRCX();
68.    }
70.    /** Send coordinates to the RCX */
71.    public void sendCommandsToRCX(int [] x, int [] y) {
72.      System.out.println("Sending data to rcx: ");
73.      for(int i=0;i<ExplorerCommand.ARRAY_SIZE;++i) {
74.         System.out.println(x[i] + " " + y[i]);
75.         try {
76.           outRCX.writeShort(x[i]);
77.           outRCX.writeShort(y[i]);
78.           outRCX.flush();
79.         } catch (Exception e) {
80.           e.printStackTrace();
81.           break;
82.         }
83.      }
84.    }
86.    /** Wait for light reading from the RCX */
87.    public void waitForRCX() {
88.      System.out.println("Waiting for RCX reply.");
90.      try {
91.         short value = inRCX.readShort();
92.         System.out.println("Got value " + value + ".Sending to user.");
93.         clientOutStream.writeInt(value);
94.      } catch(IOException io) {
95.         io.printStackTrace();
96.      }
97.    }   
98. }


In Line 21 the string must be the port your RCX tower is attached to (e.g., COM1 or USB).

The final part of the project is the client GUI, which resides somewhere across a network. This GUI includes an area to type in a series of coordinates, and also a series of shortcut buttons to send the robot to predesignated areas (Figure 11–9). Ideally this GUI would also include a map of the area with measurements, or even a live feed of the floor space from a Web cam. For the purposes of keeping this short, however, we omit these features and leave it up to the programmer to implement. Let's examine this program, which is called the Explorer Command Console:

  1 import java.awt.*;
  2. import java.awt.event.*;
  3. import java.io.*;
  4. import java.net.Socket;
  6. public class ExplorerCommand extends Panel {
  7.    public static final int PORT = 5067;
  8.    public static final int ARRAY_SIZE = 4; 
 10.    Button btnConnect;
 11.    Button btnGo;
 12.    Button btnKitchen;
 13.    Button btnLivingRoom;
 14.    Button btnBedRoom;
 15.    TextField txtX;
 16.    TextField txtY;
 17.    TextField txtIPAddress;
 18.    TextArea messages;
 20.    private Socket socket;
 21.    private DataOutputStream outStream;
 22.    private DataInputStream inStream;
 24.    public ExplorerCommand(String ip) {
 25.       super(new BorderLayout());
 27.       ControlListener cl = new ControlListener();
 29.       btnConnect = new Button("Connect");
 30.       btnConnect.addActionListener(cl);
 31.       btnGo = new Button("Go!");
 32.       btnGo.addActionListener(cl);
 33.       btnKitchen = new Button("Kitchen");
 34.       btnKitchen.addActionListener(cl);
 35.       btnLivingRoom = new Button("Living Room");
 36.       btnLivingRoom.addActionListener(cl);
 37.       btnBedRoom = new Button("Bed Room");
 38.       btnBedRoom.addActionListener(cl);
 40.       txtX = new TextField("",20);
 41.       txtY = new TextField("",20);
 42.       txtIPAddress = new TextField(ip,16);
 44.       messages = new TextArea("status: DISCONNECTED");
 46.       Panel north = new Panel(new FlowLayout(FlowLayout.LEFT));
 47.       north.add(btnConnect);
 48.       north.add(txtIPAddress);
 50.       Panel south = new Panel(new FlowLayout());
 51.       south.add(btnKitchen);
 52.       south.add(btnLivingRoom);
 53.       south.add(btnBedRoom);
 55.       Panel center = new Panel(new GridLayout(4,1));
 56.       center.add(new Label("Enter coordinates separated by
              commas (e.g. 40,70,10,35)"));
 58.       Panel center1 = new Panel(new FlowLayout(FlowLayout.LEFT));
 59.       center1.add(new Label("X:"));
 60.       center1.add(txtX);
 62.       Panel center2 = new Panel(new FlowLayout(FlowLayout.LEFT));
 63.       center2.add(new Label("Y:"));
 64.       center2.add(txtY);
 66.       Panel center3 = new Panel(new FlowLayout(FlowLayout.LEFT));
 67.       center3.add(btnGo);
 68.       center3.add(messages);
 70.       center.add(center1);
 71.       center.add(center2);
 72.       center.add(center3);
 74.       this.add(north, "North");
 75.       this.add(south, "South");
 76.       this.add(center, "Center");
 77.    }
 79.    public static void main(String args[]) {
 80.       System.out.println("Starting Explorer Command...");
 81.       Frame mainFrame = new Frame("Explorer Command Console");
 82.       mainFrame.addWindowListener(new WindowAdapter() {
 83.          public void windowClosing(WindowEvent e) {
 84.             System.exit(0);
 85.          }
 86.       });
 87.       mainFrame.setSize(400, 300);
 88.       mainFrame.add(new ExplorerCommand(""));
 89.       mainFrame.setVisible(true);
 90.    }
 92.    /** Sends coordinates to the server, then waits for
 93.    * the server to return a light value. */
 94.    private int fetchLightReading(short [] x, short [] y){
 95.       // Send coordinates to Server:
 96.       messages.setText("status: SENDING Coordinates.");
 97.       try {
 98.          for(int i=0;i<ARRAY_SIZE;++i){
 99.            outStream.writeInt(x[i]);
100.            outStream.writeInt(y[i]);
101.          }
102.       } catch(IOException io) {
103.          messages.setText("status: ERROR Problems occurred sending data.");
104.          return 0;
105.       }
107.       // Wait for server to return light reading:
108.       int light = 0;
109.       try {
110.          messages.setText("status: WAITING for rover to return.");
111.          light = inStream.readInt();
112.       } catch(IOException io) {
113.       messages.setText("status: ERROR Data transfer of light reading failed.");
114.       }   
115.       messages.setText("status: COMPLETE The light reading was " + light);
116.       return light;
117.    }
119.    /** A listener class for all the buttons of the GUI. */
120.    private class ControlListener implements ActionListener{
121.       public void actionPerformed(ActionEvent e) {
122.          String command = e.getActionCommand();
123.          int light = 0;
124.          if (command.equals("Connect")) {
125.          try {
126.             socket = new Socket(txtIPAddress.getText(), PORT);
127.             outStream = new DataOutputStream(socket.getOutputStream());
128.             inStream = new DataInputStream(socket.getInputStream());
129.             messages.setText("status: CONNECTED");
130.             btnConnect.setLabel("Disconnect");
131.          } catch (Exception exc) {
132.             messages.setText("status: FAILURE Error establishing connection with server.");
133.             System.out.println("Error: " + exc);
134.          }
135.       }
136.       else if (command.equals("Disconnect")) {
137.          try {
138.             outStream.close();
139.             inStream.close();
140.             socket.close();
141.             btnConnect.setLabel("Connect");
142.             messages.setText("status: DISCONNECTED");
143.          } catch (Exception exc) {
144.             messages.setText("status: FAILURE Error closing connection with server.");
145.             System.out.println("Error: " + exc);
146.          }
147.       }
148.       else if (command.equals("Go!")) {
149.          short [] x = parseArray(txtX.getText());
150.          short [] y = parseArray(txtY.getText());
151.          fetchLightReading(x,y);
152.       }
153.       else if (command.equals("Kitchen")) {
154.          short [] x = {-100,-100,-300,-310};
155.          short [] y = {0,100,100,100};
156.          fetchLightReading(x,y);
157.       }
158.       else if (command.equals("Bed Room")) {
159.          short [] x = {0,200,200,250};
160.          short [] y = {-100,-100,-200,-250};
161.          fetchLightReading(x,y);
162.       }   
163.       else if (command.equals("Living Room")) {
164.          short [] x = {-50,-50,-150,-150};
165.          short [] y = {0,-300,-300,-310};
166.          fetchLightReading(x,y);
167.        }
168.       }   
170.       /** Takes a string of coordinates and parses out
171.        * the short values (using commas) and assembles
172.        * them into an array. */
173.       public short [] parseArray(String coords) {
174.          int order = 0;
175.          short [] ar = new short[ARRAY_SIZE];
176.          for(int i=0;i<coords.length();++i) {
177.            int firstComma = coords.indexOf(",",i);
179.            String leading;
180.            if(firstComma < 0) {
181.              leading = coords.substring(i);
182.              i = coords.length();
183.            }
184.            else {
185.              leading = coords.substring(i,firstComma);
186.              i = firstComma;
187.            }
188.            ar[order++] = Short.parseShort(leading);
189.          }
190.          return ar;
191.       }   
192.     }
193. }

Figure 11-9 The Explorer Command Console


In the preceding code, I used several locations in my home for the shortcut buttons, so feel free to customize the locations in Lines 153 to 166 according to your own location.

Now that we have all the code ready, it's time to test it. First, upload the code to the RCX, sit it in front of the IR tower, and press the Run button. The robot waits patiently for a series of coordinates from the PC. Next, run the server code on your PC. It will sit waiting for an Explorer Command Console to connect to it. Finally, run the Command Explorer Console (either on the same machine or on a different machine on the network). Type in the IP address (or leave it as if on the same machine) and click Connect. You can now click one of the shortcut buttons, or alternately enter a series of four coordinates. Once the coordinates have been entered click Go. The robot heads to the location and records a light reading. When the robot returns you are presented with the result. If it fails to return, try using the TimingNavigator.setDelay() method.


This project really taxes the RCX memory. It uses several large classes, including TimingNavigator, which also uses the Math class. I wasn't even able to use the Sound or LCD class in this project because they pushed memory usage over the limit. This project works with the current release of leJOS, but if leJOS changes in the future and takes up more space, you might see a dreaded exception, which means out of memory. Chapter 12, "Advanced Topics," gives some explanations on how to free up memory in leJOS if you wish to expand this code.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020