Search Microcontrollers

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, May 9, 2013

Puzzle algorithm example


For those that have seen my previous post and are eventually interested to see a simple example of the described algorithm, here you can find a bare-bone implementation in Java.
You can configure the size of the square by setting the values of sizeX and sizeY.
Be warned that solutions for squares up to 7x7 come out pretty quickly on an i5 PC, from 8x8 on the magnitude of the problem requires LONG times of execution before the first solution is found.

This is an example of the solution found for a 5x5 problem :


As it is designed now, the algorithm does not implement any kind of optimization and it stops when it finds the first solution (but it can be easily modified to find ALL the solutions) or when it runs out of options.

The reason why I am proposing this java implementation is because it is easily readable and implements a basic execution logic which allows me to easily experiment trying to add some parallelism.

The final solution is not intended to be in Java


public class LatinPuzzle {

    private int stepCounter;  
    private int step[];
    private int cell[][];
    static final int moves[][] = 
    {{1,-2},{2,-1},{2,1},{1,2},
    {-1,2},{-2,1},{-2,-1},{-1,-2}};
    static final int sizeX = 6;
    static final int sizeY = 6;
    private int pSize= sizeX * sizeY;
// debugging/control info
    private long needUpdate =0;
    private int low = 100;
    private int high=0;

    
    void init()
    {
    step = new int[pSize];
    cell = new int[pSize][2];
    stepCounter = 0;
    cell[0][0]=1;
    cell[0][1]=1;
    step[0]=0;
    }
    
    private boolean isValid(int x,int y)
    {
    if ((x<1)||(y<1)||(x>sizeX)||(y>sizeY)) 
      return false;
    int scan =0;
    while (scan<stepCounter)
    {
      if ((cell[scan][0]==x)&&(cell[scan][1]==y))
       return false;
      scan++;
    }
    return true;
    }
    
    private void move(int n)
    {
    step[stepCounter]=n;
    if (n>=8) return;
    int x = cell[stepCounter][0]+moves[n][0];
    int y = cell[stepCounter][1]+moves[n][1];
    if (isValid(x,y))
    {
    stepCounter++;
    cell[stepCounter][0] = x;
    cell[stepCounter][1] = y;  
    }
    }
    
    private boolean backOne()
    {
    step[stepCounter--]=0;
    if (stepCounter<1) return false; else return true;
    }
    
    public void tryPuzzle()
    {
    boolean running = true;
    while ((stepCounter<(pSize-1))&&(running))
    {
    if (step[stepCounter]>=8) running = backOne();
    else
    move(step[stepCounter]+1);
     // debugging/control start
    if (stepCounter>high) high = stepCounter; 
    if (stepCounter<low) low = stepCounter; 
   
    if (needUpdate++ % 10000000 == 0) 
    {
    System.out.println(""+needUpdate+","+stepCounter+" "+low+"-"+high);
    low = pSize;
    high = 0;
    }
     // debugging/control end

    }
     // final output
    if (stepCounter>=(pSize-1))
    {
 System.out.println(""+needUpdate+", Success !! "+stepCounter+".");
          for (int i=0;i<stepCounter;i++)
           System.out.print(""+step[i]+".");
          System.out.println();
          for (int i=0;i<=stepCounter;i++)
             System.out.print(""+cell[i][0]+","+cell[i][1]+" ");
    } else      
      System.out.println(""+needUpdate+",failed "+stepCounter+".");
      }
    
public static void main(String[] args)
{
LatinPuzzle lp = new LatinPuzzle();
lp.init();
lp.tryPuzzle();
}
}

Thursday, October 11, 2012

BeagleBone : Serial ports and multiplexing

Some months ago I released a couple of  Youtube videos where I was illustrating the basics of using java and the comm library RXTX to drive serial communications with the beaglebone.









Since then I keep getting a few questions and from time to time I get requests for a test class.
So I figured I could do a post here to explain few things.
(Ok, ok... if you just want the code and skip the blah blah, you can get it here, good luck with it)

First thing : RXTX is an open source communication library, maybe it's not perfect, but I find it great for a number of reasons, one of them being it's portability.
Driving hardware (like serial ports) in java is a bit tricky, because you need native code (i.e. written in C, ASM...) for the specific architecture you are using.
To put it in simple words : you need some code which is not executed in the JVM, so it's not java.
This is obviously an issue : java is designed to be portable cross platform, you normally just need a jvm for the specific architecture you are using and you are normally pretty much done.

If you need to execute native code, then you need the specific version that can work on your device.
The native part of the RXTX library has been successfully ported to the bone, which makes it possible to use the library in java on this device.

I am not going to provide a tutorial on rxtx here, if you want to use it and you have no knowledge on it, I strongly suggest you search for tutorials in the web and first learn how to use it on a pc.
I have a software logging data from a RS485 every 30 seconds, running since about 3 months, it was developed and tested on a PC and finally deployed (smoothly) on the bone.

So, what's special with the bone?
Not much honestly and in fact, if you use a usb/serial converter you probably don't need any bone specific instruction : what runs on your pc is supposed to run on the bone just the same.

However, the bone offers also some "internal" ttl uarts (3.3V !! beware) and to use those you need some bone specific code.
Those uarts are physically accessible from the P8 and P9 headers of the board, their pin mapping -extracted from the bbone user manual- is the following :


i.e. P9.21.1 means pin 21 on the P9 header and multiplex value = 1

You should probably be familiar with the multiplexing concept, if not, here's a very quick explanation :

Multiplexing 

Many of the modern processors and microcontrollers, provide a wide range of functionality.
At this point the issue became to export all those functions with physical electrical contacts (pins).
A solution was found in assigning multiple functions to the same pin and allowing the processor to be configured, via software, to set a specific function to a specific pin.
The ARM cortex processors use a lot this feature.
To get back to our serial ports, this means that the RX function of uart2 will normally be located at pin xxx, however at the same pin you can eventually find other 7 functions, which could be GPIO, timer output, etc...
So, what we want to do is to configure properly the function, direction (input/ output) etc of the pins we need.

But wait... that sounds like an issue if we are using java, right?
Again we would need to access the hardware, so we would need native code...

No, the Linux OS comes in help with that.
To allow an easy access to these functionality, the OS exports a virtual file system which acts as a sort of interface for all those hardware configuration.
From the java side, we just need to deal with files and directories.

For that I created a specific helper class, it's not really finished, but it does the job for me.
It can be found here and if you can read java code it should be quite self explanatory.
I use it to interface the beaglebone headers (it can do gpio read/writes), not just for setting the multiplex values.
This class uses an external dat file (gpiomux.dat) which is actually a text file in which I list the contacts on the P8 and P9 header.
Except for the serial ports, for which I provide a specific method, to configure the other pins (should you need to), you need to refer to the user manual, discover which pin is assigned to the function you are looking for and find also the function number.
With that info, the BBMux class will do the configuration for you.

Allowing RXTX to see the ttl uart ports

The RXTX library uses a list of known port names to discover your available serial ports, unfortunately this list does not include the beaglebone internal serial ports.
No worries, there is an easy fix, no coding required!
The solution is documented here : http://rxtx.qbang.org/wiki/index.php/Trouble_shooting
Check where it says : How does rxtx detect ports? Can I override it?

In my case I decided to specify the port list when running the program.
The internal serial ports are seen by the OS as ttyOx (O stands for Omap)


java
    -classpath ./:./rxtx/RXTXcomm.jar
    -Djava.library.path=/usr/lib/jni
    -Dgnu.io.rxtx.SerialPorts=/dev/ttyO1:/dev/ttyO2:/dev/ttyO3:/dev/ttyO4:/dev/ttyO5
   MyClass

My command line sets :
- the java classpath to include the rxtx java library (jar)
- the java library path to include the rxtx native library folder
- the rxtx serial ports to the list of ports I could use in my program


Note : I created the test class TestBBSerial by ripping code from my program, I hope it works, but it's really meant just to illustrate the concepts.
You can find great rxtx examples on the web,
Unfortunately I cannot post my other programs as they would be too complex to explain, I normally use some wrappers for rxtx to handle buffers, configurations, protocols etc.
These wrappers use json, webservices for remote configurations... so I would need to post tons of classes that would just confuse you more.