Tuesday, July 05, 2011

Programming the NXT to communicate with Linux

This is Part 3 of a three-part series on programming the Lego NXT through Linux.
  1. Part 1 to setup the NXT-bluetooth connection
  2. Part 2 to setup your programming environment
If you have followed along, you are now ready to program in NXC.
Let's write a simple C program for Linux, and an NXC program for the NXT that communicate through Bluetooth. The interface of this program is totally dopey and unprofessional, but it demonstrates how to send information to the NXT and get information from it. The ideas are borrowed by notes from the CPSC 3720 Software Engineering course at the University of Lethbridge, in particular this handout. Here are the steps you need to follow.
  • Install Bluetooth libraries and GTK libraries on Linux. On Ubuntu, the command is:
    $ sudo apt-get install libbluetooth-dev \
           libgtk2.0-dev libc6-dev make gcc
  • Make the Tribot from the Mindstorms quickstart. This is the first project, the quick start.
  • Ensure that B is connected to the right motor, and C to the left motor. Leave A unconnected.
  • Now download my nxtBluetooth.tar.gz package to demonstrate Linux Bluetooth communication. Unpack it, and go through the files.
  • There are two programs: nx_soldier, which is the NX's program. It listens on Bluetooth and obeys the commands of the commander. The pc_commander is a GTK application that allows you to specify commands that the soldier will faithfully carry out.
  • There is a single place you have to edit to specify your NXT's address. Remember the times you changed 11:22:33:44:55:66 address above? Well, you need to open the pc_commander.c file and change this address to that of your NXT again.
  • Attach your NXT using the USB cable. Compile the programs with
    $ grep ADDRESS pc_commander.c       
    $ # Make sure you have the right address
    $ make nx_soldier.rxe
    $ make pc_commander && ./pc_commander
  • Run the nx_soldier program on the NXT.
  • Run the pc_commander on the Linux machine. Press the buttons to make the soldier move according to your wishes.
  • When you ask the soldier for his status, he always replies he is fine.
  • This program makes a good starting point: the code is reasonably well documented, and easy to adapt. You could try putting the bumper sensor on the TriBot, and modifying the nx_soldier so that he replies with "I am stuck" when it has hit a wall.