Search code examples
javamultithreadinglejos-nxjautonomy

Java Lejos autonomous NXJ-robot threads causing trouble


I'm writing an java code to control a fairly simple robot, which should execute the following actions; PID-linefollower, ultrasonic detection and color detection.

As this is my first program in java, I obviously have lots to learn in regards to OOP.

The robot runs on a track where the line is accompanied by colors on the road, which the robot should periodically check for and if found, act differently based on which color it reads.

So the process should run somewhat alike this following pseudo(java)-code:

Initialize and calibrate sensors.
while (! Button.ENTER.isDown)
Run PID-controller
If (ColorSensorColor = 0 || ColorSensorColor = 2)
    if (color = 0)
        turn left
    if (color = 2)
        turn right
while (UltraSonicDistance < 30cm)
    free-roll motors

My question therefore is; how do I construct two threads that can run the ColorSensor and UltraSonicSensor in parallel with a main thread?

The latest actual code is situated here

Lastly, thanks for all your input - I've scoured the interwebz for good tutorials, but it seems that I have too few braincells to comprehend the mother of all OOP.


Solution

  • /u/evil_burrito on /r/javahelp kindle answered with the following, working suggestion:

    First, you might want to consider a real time JVM, if you're not already. If your controller has to run uninterrupted, that might be something to consider. FWIW, RT is not my area of expertise at all. However, your basic question about threads is easier to answer. Create an inner class for each of the ultrasonic sensor and the color sensor. Have those classes implement Runnable. In the run method, check the appropriate sensor and update a volatile variable in the outer class. Use a ScheduledExecutorService to execute a sensor check for each of these classes (create an instance of the inner class and submit it to the executor to be run at intervals of 1ms or 100 microseconds, or whatever). The main class can just monitor the values of the volatile variables and decide what to do w/o interruption.