Installing LeJOS NXJ on Mac OS X 10.6 (Snow Leopard)

The intensity of the term has lulled, marginally, so last night I completed my migration from PC to Mac.  I installed LeJOS NXJ, a Java programming environment for the LEGO Mindstorms NXT. It lets us program LEGO robots in Java.

LeJOS is an open source project hosted in the sourceforge repository. It was forked from the TinyVM project which implemented a Java VM for the LEGO Mindstorms RCX system.

By installing I mean adding these to my Macbook Pro and successfully installing the first item on the list on my LEGO Mindstorms NXT brick:

  1. Replacement firmware for the NXT that includes a Java Virtual Machine
  2. A library of Java classes that implement the leJOS NXJ API
  3. A linker for linking user Java classes with classes.jar to form a binary file that can be uploaded and run on the NXT
  4. PC tools for flashing the firmware, uploading programs, debugging, etc
  5. A PC API for writing PC programs that communicate with leJOS NXJ programs using Java streams over Bluetooth, USB, or the LEGO Communications Protocol (LCP)

I’ve blogged about my introduction to LeJOS and Mindstorms and have successfully used LeJOS on Windows Vista and Windows 7 as well as Ubuntu.   Configuring the environment on my Mac was, as usual, easiest of the three.

Recall that I am using a mid-2010 MacBook Pro running Mac OS X 10.6. LeJOS NXJ requires some of the drivers from the original LEGO brand software that ships with the robot.  I tried using the CD that came with my Mindstorms (purchased in May 2008) to install the original LEGO system, but it didn’t install.  There were no error messages but the app never appeared in my apps folder.  This is how I solved the problem:

1. A little probing on the LEGO website and I found a Snow Leopard fix which I used to complete the installation.  I also found and installed the latest LEGO firmware update (version 1.29).

2. Because of the difficulty I’ve had with drivers on both Windows and Ubuntu, I also installed the Fantom Driver on top of the MindStorms app.

All of these are at: http://mindstorms.lego.com/en-us/support/files/Driver.aspx#Driver

3. Download and unzip LeJOS NXJ: http://sourceforge.net/projects/lejos/files/lejos-NXJ/

4. Set the permissions in the downloaded folder:
chmod -R 755 /pathto/lejos_nxj/

5. Edit etc/launchd.conf to include (I already had this from a former install):
setenv JAVA_HOME /Library/Java/Home

6. Edit ~/.bash_profile to include
LEJOS_HOME=/pathto/lejos_nxj
NXJ_HOME="$LEJOS_HOME"
DYLD_LIBRARY_PATH=/pathto/lejos_nxj/bin
export LEJOS_HOME NXJ_HOME DYLD_LIBRARY_PATH
PATH="$LEJOS_HOME/bin:$PATH"
export PATH

This is where I got stuck.  No matter how I adjusted these environment variables, every time I connected the NXT brick by USB and tried to flash the LeJOS firmware onto it, I received some permutation of

Bad news: An error has occurred lejos.pc.comm.NXTCommException: Cannot load a comm driver!

It’s always something with LeJOS and it’s always something I’ve overlooked.  In this case, my Java defaults to 64 bit and LeJOS needs to use 32 bit.  I recently upgraded my RAM to 8GB and in order for the Win 7 virtual drive in my Virtual Box to use 4 GB of memory I have to boot Snow Leopard in 64 bit kernel mode (by holding the 6 and the 4 down during startup).  It is necessary to:

7. Manually add the -d32 flag to the LEJOS scripts. Setting the Java version in system preferences won’t do the trick.  Open all the non-binary files (the ones that don’t end with .bin) in the /pathto/lejos_nxj/bin/ folder and edit all calls to “java” to include -d32 to make them run in 32-bit mode.

Worked like a charm.

I was motivated by more than the opportune free evening.  I am considering enrolling in September in a directed studies course at UBC in which students make a proposal to a faculty member to investigate a topic that goes beyond that which is covered in existing courses.  I’ve enjoyed working (and playing!) with Mindstorms (what red-blooded Canadian wouldn’t!) and last term I enjoyed learning Haskell and Prolog.  This term’s course in internet computing is beginning to stand out as a favourite.  I’m also itching to learn Erlang.  Somewhere in this there is some interesting work…

Share

LeJOS NXJ

LeJOS is replacement firmware for the Lego Mindstorms RCX and NXT bricks. It’s based on the Java programming language and includes a JVM, or Java Virtual Machine, which allows Lego Mindstorms robots to be programmed in Java.

LeJOS is an open source project which means you can participate in its development, or download the source code and turn it into a creation of your own.

The current version is 0.85 released September 2009.

Lego Mindstorms Robotics Kits:
http://mindstorms.lego.com/
LeJOS Java for Lego Mindstorms
http://lejos.sourceforge.net/
Official LeJOS Developer Forum:
http://lejos.sourceforge.net/forum/
Lego Digital Designer:
http://ldd.lego.com/
Installing Lejos on Ubuntu 8.04 (old but still applicable):
http://lejos.sourceforge.net/forum/viewtopic.php?p=3785
http://ubuntuforums.org/showthread.php?t=854846

In 2008 at BCIT I worked with a team of 4 others in a software development project using LeJOS. BCIT owns a large room full (and I mean FULL) of Lego Mindstorms Lego. We applied what we had learned about iterative development and project management during our first year to a 5-week software development lifecycle, from requirements gathering to specification to implementation and delivery. We applied two terms of Java to a series of architecture and programming milestones and a final tournament based on the competitions organized by the First Lego League.

Our team (Hadaga) finished in 2nd place out of 23 (winner score: 495 / average score: 320 / our score: 395 ). I’ve included some of our code and design documents as an example of great teamwork and good clean fun.

Our Team Hadaga Tournament Code (Uncompiled Java):
Nano table [3 KB] Power table [12 KB]
Team Hadaga Robot Building Instructions (Lego Digital Designer format):
Hadaga_Building_Instructions.lxf [28 KB]
Team Hadaga Design Docs (pdf):
Team Agreement [73 KB] Concept Document [224 KB] Design Document [3.4 MB]
Share

Java’s Sorted Collections and the Comparable and Comparator Interfaces

Java’s SortedSet interface and the classes that implement it (like TreeSet) will store a collection of objects that are sortable. In order to make a class sortable so that we can store it in a sorted collection, we have two choices:

  1. the sorted class can implement the Comparable interface
  2. we can pass a Comparator to the collection’s constructor.

1. Comparable Interface

This is probably the easiest way to make sure we can store objects in a sorting collection. The Comparable interface has a single method that we recognize from classes like String:

int compareTo(Object o)

This method must return an integer: 0 if this.equals(o), a negative int if this is less than o, and a positive int if this is greater than o. Using the Comparable interface defines what we call the “natural ordering” for a class. Here’s an example I wrote for a PTerm, which is a term in a polynomial:

public int compareTo( PTerm other )
{
    return other.power - power;
}

2. Comparator Interface

An interesting alternative is the Comparator interface. By using the Comparator interface we can define different comparators for a class if we need to order objects of a type in different ways. The Comparator interface contains two methods:

1. equals()
2. int compare(T o1, T o2).

Here’s the trick: the class we are comparing does NOT implement Comparator–we create a brand new class that implements it, and pass the implementing class to the collection’s constructor. Here’s an example:

public class TermComparator implements Comparator<PTerm>
{
    public int compare( PTerm term1, PTerm term2 )
    {
        return term2.getPower() - term1.getPower();
    }
}

In this case, we’re sorting the terms in the polynomial by the magnitude of the exponent, but we could have also decided to sort them by the magnitude of the coefficient.

We create the TreeSet like this:

    SortedSet<PTerm> polynomial = new TreeSet<PTerm>( new TermComparator() );

So now, whenever we add a term to the polynomial, the TreeSet will use the TermComparator to decide where it goes.

Don’t forget to override equals() in the PTerm class either:

public boolean equals( Object obj )
{
    if( obj == null )
        return false;
    if( getClass() != obj.getClass() )
        return false;
    PTerm other = (PTerm) obj;
    return power == other.power;
}

Share

AT91SAM7S256 aka the NXT Brain

The Lego MindStorms NXT Brick is controlled by a pair of Atmel microcontrollers:

The AT91SAM7S256 is part of an Atmel series of low pin-count Flash microcontrollers based on the 32-bit ARM7DMI ARM Thumb RISC processor. It features:

  • a maximum clock speed of 55 MHz (48 MHz in the NXT)
  • 64 KB of high-speed on-chip SRAM
  • 256 KB of integrated high-speed Flash memory
  • 11 peripheral DMA channels
  • 1 USB 2.0 (12 MB/s) device port
  • three 16-bit timers
  • four PWM controllers
  • 32 I/O pins
  • and requires a 3.0- to 3.6-volt power supply

The key facts here are:

  • The RISC–reduced instruction set architecture–is based on ARMv4T Von Neumann architecture. The ARM7DMI processor provides 0.9 MIPS (millions of instructions per second).
  • ARM–32-bit instruction set
  • Thumb–critical subset of the ARM 32-bit instruction set that has been encoded into a 16-bit instruction set
  • Flash memory–can be programmed in-system via the JTAG-ICE interface or through a parallel interface on a production programmer prior to mounting

The ARM7DML can execute both the high-performance 320bit ARM and high-density 16-bit Thumb instruction sets. The instruction sets are toggled by the processor as an ARM state or a Thumb state. In the ARM state, the 32-bit instructions are executed conditionally, while the 16-bit Thumb state instructions are a re-encoded subset of the ARM instruction set. The stegosaurus had a brain in its arse, and basically so does the NXT Brick. The AVR 8-bit ATmega48 microcontroller acts as a co-processor. Inside it there are:

  • 4 KB reprogrammable Flash program memory
  • 512 Byte SRAM
  • 256 Byte EEPROM
  • 8-channel, 10-bit AéD converter (TQGPéMLF)
  • 23 I/O pins
  • 4 MHz clock speed

Here’s the interesting thing. The ATmega48 is much smaller than the main AT91SAM7S256 processor, but this 8-bit microprocessor achieves almost 1 MIPS per MHz by executing its RISC instruction set in a single clock cycle.

Share

Artifact J-2: Java RPN Calculator (Command Prompt)

Description

A simple command prompt calculator that uses Reverse Polish Notation.

In Reverse Polish Notation the operators follow their operands; for instance, to add three and four, one would write “3 4 +” rather than “3 + 4″. If there are multiple operations, the operator is given immediately after its second operand; so the expression written “3 − 4 + 5″ in conventional infix notation would be written “3 4 − 5 +” in RPN: first subtract 4 from 3, then add 5 to that.

The algorithm for evaluating any postfix expression is fairly straightforward:

  • While there are input tokens left
    • Read the next token from input
    • If the token is a value
      • Push it onto the stack
    • Otherwise, the token is an operator
      • It is known a priori that the operator takes n arguments
      • If there are fewer than n values on the stack
        • (Error) The user has not input sufficient values in the expression.
      • Else, Pop the top n values from the stack.
      • Evaluate the operator, with the values as arguments
      • Push the returned results, if any, back onto the stack
  • If there is only one value in the stack
    • That value is the result of the calculation
  • If there are more values in the stack
    • (Error) The user input too many values

For more information on Reverse Polish Notation read: http://en.wikipedia.org/wiki/Reverse_Polish_Notation.

Technical Knowledge

I applied my knowledge of:

  • object oriented programming in Java
  • Reverse Polish Notation
  • polymorphism.

Skills Applied

I developed these skills while making this artifact:

  • using the NetBeans IDE
  • test-driven design using Netbeans
  • object oriented programming with Java.

Notes

I wrote this for BCIT’s COMP 2526, Intermediate Java, in February 2008.

I employed an iterative, test-driven approach. My first iteration resulted in a program that used classes to deal with different operations. The second iteration reduced code duplication and improved the quality of the code with polymorphism.

The application was written using NetBeans against a series of Unit tests provided by our instructor, D’Arcy Smith.

Demonstration

Download the source code [8 KB ZIP].

Download the JAR file here [13 KB]. Navigate to the download folder with your command prompt and run using:

java -jar RPN_2.jar

Share

Artifact J-1: Codeword Parity Validator

Description

A program that tells the user if a parity-encoded word is valid or not, and if a Hamming codeword is valid or not.

A parity-encoded word is a series of binary digits (zero or one) where the left most digit is either a zero or one depending on the type of parity being used (EVEN or ODD). If a word is encoded with EVEN parity the number of one bits must be an even number. If a word is encoded with ODD parity the number of one bits must be an odd number.

For example, if the original word is: 100

  • EVEN codeword is 1100 (1 + 1 is 2, an even number)
  • ODD codeword is 0100 (1 is an odd number)

A Hamming encoded word is a series of binary digits (zero or one) where the 2x bits are either a zero or one depending on the type of parity being used (EVEN or ODD)

For example, if the original word is: 10

  • EVEN codeword is 11100
  • ODD codeword is 00110

For more information on parity checking read: http://en.wikipedia.org/wiki/Parity_bit.
For more information on Hamming codes read: http://en.wikipedia.org/wiki/Hamming_code.

Technical Knowledge

I applied my knowledge of:

  • Java basics including GUI classes
  • regular expressions
  • object oriented programming.

Skills Applied

I developed these skills while making this artifact:

  • working with the NetBeans IDE
  • test-driven design using NetBeans
  • object oriented programming with Java.

Notes

I wrote this for BCIT’s COMP 2526, Intermediate Java, in January 2008.

I employed an iterative, test-driven approach. My first iteration resulted in a program that checked the parity of a codeword entered as a command-line argument. The second iteration added logic to check Hamming codewords, and the third and final iteration added a GUI envelope for the program.

The application was written using NetBeans against a series of Unit tests provided by our instructor, D’Arcy Smith.

Demonstration

Download the source code [7 KB].

Download the JAR file here [21 KB]. Navigate to the download folder with your command prompt and run using:

java -jar Parity_Validator_3.jar

Share