User Tools

Site Tools


marvin:ecp5

This is an old revision of the document!


Lab report 5 - Bluetooth controlled robot

Date: January 19nd and 20th 2009
Duration of activity: 8-16 (both days)
Participants: Kasper, Bent and Johnny

Project Goal

Make robot remote controlled from the PC through bluetooth.

Plan

  • Make a bluetooth client code Behaviour on the Marvin, that can receive numbers and act on them.
  • Make pc bluetooth app read from keyboard arrows to determine control direction.

FIXME: Insert the right video and thumbnail (marvin being remote controlled)
p_lab3_bhv.jpg 1gR1UL5FbTQ

The BTControl class

Bluetooth control behavior. It reads integers from a bluetooth input stream, interpreting them as keycodes. It reacts only on the keycodes connectred with the arrow keys (up, down, left, right) and tells Marvin to drive accordingly.

Key KeyCode Variable
left 37 directionLeft
right 39 directionRight
up 38 directionForward
down 40 directionBackward

All exception handlers have been removed to improve on readability:

public class BTController extends Behavior 
{
  .
  .
  .
 
  public void run() 
  {
    NXTConnection conn = Bluetooth.waitForConnection();
    DataInputStream istream = conn.openDataInputStream();
 
    while(true) {
      if(istream.available() > 0) direction = istream.readInt();
      else delay(200);
 
      if(direction >= directionLeft && direction <= directionBackward) {
        suppressLower();
        switch(direction) {
        case directionLeft:
          left(200);
          break;
 
        case directionRight:
          right(200);
          break;
 
        case directionForward:
          forward(200);
          break;
 
        case directionBackward:
          backward(200);
          break;
        }
        unsuppressLower();
 
        // Empty input buffer... we only want to use the latest keystroke.
        while(istream.available() > 1) istream.readInt();
      }
    }
  }
}

And on the PC a window (JFrame) captures keyboard input and redirects their keycode values to the bluetooth stream:

NXTComm nxtComm = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH);
NXTInfo nxtInfo = new NXTInfo("Marvin", "00:16:53:06:E3:36");
nxtComm.open(nxtInfo);
 
OutputStream os = nxtComm.getOutputStream();
final DataOutputStream dos = new DataOutputStream(os);
 
JFrame frame = ...
 
frame.addKeyListener(new KeyListener() {
  public void keyPressed(KeyEvent e) {
    dos.writeInt(e.getKeyCode());
    dos.flush();
  }
  public void keyReleased(KeyEvent e) {}
  public void keyTyped(KeyEvent e) {}
});

The full source code for both of these classes can be found in the files BTController.java and PCController.java in the Marvin code tarball 1). See the marvinController script file in the same tarball, to get an idea of how to run the bluetooth client program.

marvin/ecp5.1233154722.txt.gz · Last modified: 2009/01/28 15:58 by deva