Bluetooth communication between Arduino and Lego NXT using leJOS

The Lego NXT is a robotics platform that makes it easy to start creating robots with standard Lego pieces, an “intelligent brick” and a wide variety of sensors and actuators. One of the problems of the NXT is that it only has 3 motor ports and 4 sensor ports. If you want to extend the amount of sensors and actuators that the NXT can have access to, a solution is to use an Arduino with a Bluetooth module. In our case, we used the leJOS firmware for the NXT, which allows us to write the code for the robot in Java.

The first step is to pair both devices, which you can do by going to the Bluetooth menu  on the NXT. Afterwards, you can access the Arduino through its Bluetooth ID via the Java code:

It is VERY important that you use the RAW mode (NXTConnection.RAW) when connecting to a Bluetooth device other than another NXT brick. By default leJOS sends some extra bytes with every communication, which can mess up your data transmission. After the connection is established, you can open the input and/or output streams and start sending data:

Make sure that you read data from the stream on a different thread if you don’t want your robot to block while waiting for data. In our case, the NXT brick was communicating with an Arduino. Here’s an example of how that looks like:

Something that gave us some headaches was the difference between Serial.print() and Serial.write(). The value that you pass to Serial.print(), even if it’s an int, gets converted to its corresponding character. For instance, Serial.print(5) will send the character ‘5’, which corresponds to the ASCII value of 53. If you want to send the integer 5, use Serial.write(5).