Search This Blog

Saturday, March 26, 2011

Notes on Learning to Make a Java GUI for the CNC machine

Not sure if this is the way I will go, but I'm exploring using Java to create a small GUI to control the Arduino based XYZ CNC machine.  I did see some folks have already done this, so I may go back and use their code.
This is a place to store my notes as I explore this topic.

My hardware is an Arduino with two motor shields from Adafruit attached (see my post on modding the shield to stack) and another Arduino reading three rotary encoders (see my post on this).  These control a Zen toolworks 7x7 CNC machine.

I've written the code for the Arduino to respond to serial commands to move in straight line at constant velocity from current location to a new location.   Ideally this is all that ever needs to run on the Arduino.  I wrote a simple HPGL interpretor, but the serial communication wasn't working out. When I used the Arduino GUI to dump a serial file to the Arduino, the Arduino did not process the commands fast enough, obviously it has to move motors, etc, and the serial input would overrun the input buffer in the Arduino and trash the data.  The Arduino can't do this job all by itself.  i will never be able to send a whole HPGL file to the Arduino, it needs to be passed a bit at a time by a PC program.

So the goal here is to write a GUI that will allow the PC to feed the Arduino a file a bit at a time, and also have manual buttons to move the motors and display the encoder postions.  Maybe even the limit switches.  All the arduino will do is move from X,Y,Z to X,Y,Z point as commanded.

Downloaded Netbeans and Java JDK here:
https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewFilteredProducts-SingleVariationTypeFilter

Found some information on talking to the serial port here:
http://java.sun.com/developer/Books/javaprogramming/cookbook/11.pdf

That book says I may need to download the Java Communication API, which I found here
http://www.oracle.com/technetwork/java/index-jsp-141752.html
but this looks to be for LINUX only.  The text says for windows...
  To use that, download javax.comm for the 'generic' platform (which provides the front-end javax.comm API only, without platform specific back-end implementations bundled). Then acquire the Windows binary implementation rxtx-2.0.7pre1 from http://www.rxtx.org.


Found a web page with specific instructions!  Here:
http://pradnyanaik.wordpress.com/2009/04/07/communicating-with-ports-using-javaxcomm-package-for-windows/

So I registered at sun and downloaded the generic package java communication API
https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_SMI-Site/en_US/-/USD/ViewFilteredProducts-SingleVariationTypeFilter

Now I'm puzzled, only the comm.jar file is there, not the win32com.dll or the javax.comm.properties

Found another example that seems more clear;
http://edn.embarcadero.com/article/31915
Points to the same oracle page that got me only comm.jar.  hmmmm.
And rxtx.org points to a isp dead end page.

Friend sent me rxtx-2.1-7-bins-r2  dont know where he got it.  But no worries, it is on the web see below
Instructions were similar, but now i had a jar file and a dll.
README referred to this web page, which had the files on it
http://rxtx.qbang.org/wiki

Windows
RXTXcomm.jar goes in \jre\lib\ext (under java)
rxtxSerial.dll goes in \jre\bin

Then went here to use in netbeans
http://rxtx.qbang.org/wiki/index.php/Using_RXTX_In_NetBeans
I did the right click on libraries to add the jar file but i had already copied the files into the locations above, so i think i'm done

Went to the sample project
http://rxtx.qbang.org/wiki/index.php/Documented_interface_to_communicate_with_serial_ports_for_beginners,_including_example_project
Even mentions arduinos - w00t
downloaded the zip file  RXTXexample.zip
Bleh, not really sure how to use this with netbeans.  README talks about ant in linux.
Tried opening as a project in netbeans...no dice

Opened the project my friend sent, myRxTxTest2.  I will go back and figure out how he made this later, sorry for the trail that can't be followed.  Here is the basic Java code that makes up Main.java.  There is
also a GUI form that goes with it, but nothing earth shaking there.

//--------------------------------------------------------------------------------------------------
import java.io.*;
import java.util.*;
import gnu.io.*;
import java.awt.event.MouseAdapter;
//import javax.comm.*;
/**
 *
 * @author eric
 */
public class RealMain {
    Enumeration      portList;
    CommPortIdentifier portId;
    SerialPort      serialPort;
    OutputStream       outputStream;
    InputStream         inputStream;
    boolean      outputBufferEmptyFlag = false;
    Thread             readThread;
    Thread              writeThread;
    boolean             wrFlag=true;
    boolean             rdg=true;
    String              msgin;
    String              msginmod;


    public void Go(){
        //inForm inf = new inForm("MyForm");
        //inf.go();
        trash trh = new trash();


      
        trh.setVisible(true);


        try{
            portId= CommPortIdentifier.getPortIdentifier("COM11");
        }catch(Exception e){
            System.out.println("Error getting port ID"+ e);
            Enumeration ports = CommPortIdentifier.getPortIdentifiers();


            //tomw - addeed dump of all active ports
            System.out.println("Active ports found:");
            while(ports.hasMoreElements()){
                CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
                System.out.println(port.getName());
            }
        }
        try{
            serialPort = (SerialPort) portId.open("My RxTx test", 2000);
            System.out.println("Got Serial Port Open");
            System.out.println("type something in the console window to send it (15 characters max) - type exit to quit ");
        }catch(Exception e){
            System.out.println("Error opening port "+ e);
            System.exit(1);
        }
        try {
            outputStream = serialPort.getOutputStream();
        } catch (IOException e) {
            System.out.println("Error setting output stream "+e);
        }
        try {
            inputStream = serialPort.getInputStream();
        } catch (IOException e) {
            System.out.println("Error setting input stream "+e);
        }
        try {
            serialPort.setSerialPortParams(9600,
                                           SerialPort.DATABITS_8,
                                           SerialPort.STOPBITS_1,
                                           SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {}


        ReadHandler RH = new ReadHandler();
        Thread RT = new Thread(RH);
        RT.start();
        InputStreamReader cmlIn = new InputStreamReader(System.in);
        BufferedReader brIn = new BufferedReader(cmlIn);
        PrintWriter pr = new PrintWriter(outputStream,true);
        while (rdg){
            try{
                msgin = brIn.readLine();
                System.out.println("You typed "+ msgin);
                try{                  
                    //pr.print(msgin);
                    //outputStream.write('w');
                    //outputStream.write(0x000a);
                   // pr.print(0x00);
                   // pr.println();
                    if(msgin.length()>15){
                        msginmod=msgin.substring(0, 15);
                        System.out.println("more than 15 characters - will truncate to " + msginmod);
                    }else{
                        msginmod=msgin;
                    }
                    pr.println(msginmod);
                }catch(Exception e){
                    System.out.println("error writing to device "+ e);
                }
                if (msgin.equalsIgnoreCase("exit")){
                    rdg=false;
                    System.out.println("leaving now");                
                    outputStream.close();
                    inputStream.close();
                    brIn.close();
                    pr.close();
                    serialPort.close();
                    System.exit(1);
                }
            }catch(Exception e){
                System.out.println("error reading line"+ e);
            }
        }
    }
    public void Write(){
        System.out.println("got here");
    }


    class ReadHandler implements Runnable {
        volatile boolean on;      
        public void run(){
            int c;
            String msgback;
            InputStreamReader IS = new InputStreamReader(inputStream);
            BufferedReader BR = new BufferedReader(IS);
            while(rdg){
                try{
                    msgback=BR.readLine();
                    System.out.println("line back is "+ msgback);
                }catch(Exception e){
                    //tomw - commented out, screen if filling with this message
                    //System.out.println("error reading back"+ e);
                }
            }
        }
    }


  
}
//--------------------------------------------------------------------------------------------------------

It complained it had non existing paths to my friends RXTXcomm.jar and others.  Trying to point it to my own files
OK - found that right click on Libraries in the project tree, hit properties, brings up the GUI to remove the broken links.  Still missing java.boot.jar  looks like i can ignore this.  Complains the port doesn't exist.
looks like the code points to a port /dev/ttySO, since he uses Linux, I'm still using windows. trying this instead:
Found some code at the bottom of this page that tells how to read what ports are active:
http://stackoverflow.com/questions/274179/nosuchportexception-using-rxtx-java-library-on-windows

    Enumeration ports = CommPortIdentifier.getPortIdentifiers();  

    while(ports.hasMoreElements()){  
        CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
        System.out.println(port.getName());
    }
}  


Bingo - I get:

COM1
COM11
LPT1

So changing the port to "COM11" where my Arduino is and error goes away, but the form flashes up then disappears immediately from within Netbeans, Duh - the arduino app was open and the port was busy.
Closed it and things are looking up!

For testing I made a tiny sketch for the Arduino to respond to serial inputs, turns off LED, etc

//-------------------------------------------------------------------------------------

// Test program for the Arduino
// for development of a serial interface GUI on the PC
// Just makes communication on the serial interface


char inByte = '0';         // incoming serial byte
char outByte = '0';        // outgoing serial byte
boolean contact = false;    //indicates a link partner was found


void setup()
{
  // start serial port at 9600 bps:
  Serial.begin(9600);
  pinMode(13, OUTPUT);    
}


void loop()
{
  if (Serial.available()) {
    contact = true;
    inByte = Serial.read();
    
    if (inByte == 'U') digitalWrite(13, HIGH);   // set the LED on
    if (inByte == 'D') digitalWrite(13, LOW);    // set the LED off
    
    // mess with it a bit to show something happened
    outByte = inByte + 1;
    Serial.println(outByte);         
  } else {
    //spew junk to let the world know you want to talk
    if (!contact)   Serial.print(",");
  }
  
}

//-------------------------------------------------------------------

OK, some success.  The console window shows the responses from the Arduino.  The form is not working but at least it is talking to the Arduino from the Java console!!!  w00t!

Had to switch to my laptop, so brief recap of what i had to do to get netbeans back to this point.....
Download Java netbeans JDK
Download Java Communication API, and get the file comm.jar from the generic platform
Download  rxtx-2.1-7-bins-r2 from http://rxtx.qbang.org/wiki and put the RXTXcomm.jar and rxtxSerial.dll in the folders in netbeans where the README says
OK - back to our show.....

Have the very basics of the GUI working now by splicing together demo GUI program with the rxtx.   I can push a button on the GUI, send a 'U' to the serial interface and turn on the LED.   Awesome!  'D' turns it off.   The port initialization was stolen directly from the code i posted further up.   The Arduino sends back the position and the GUI displays it.  Left a place for the encoders to read back, that requires more work from a second serial port.



Using the basic GUI builder in Netbeans.  The form is just made with the form builder and the functions pasted into it's fields.

I'm in business.  Now the drudgery of making the full GUI, passing coordinate messages, spooling a HPGL file, etc to the real Arduino stepper motor control program.   I'll spare some details until I have a more complete interface put together and write that up.

Here is the Java and the Arduino programs.

package Serial_Comm_GUI;


//imports all the java rxtx libs
import java.io.*;
import java.util.*;
import gnu.io.*;
import java.awt.event.MouseAdapter;
//import javax.comm.*;


/**
 *
 * @author tomw
 */
public class RealMain {
    Form1 myform;
    boolean toggle = false;
    Enumeration      portList;
    CommPortIdentifier portId;
    SerialPort      serialPort;
    OutputStream       outputStream;
    InputStream         inputStream;
    boolean      outputBufferEmptyFlag = false;
    Thread             readThread;
    Thread              writeThread;
    boolean             wrFlag=true;
    boolean             rdg=true;
    String              msgin;
    String              msginmod;
    String              portName = "COM11";


    public void go() {


        // Pops up the GUI
        myform = new Form1(this);
        myform.setVisible(true);


        myform.setLabel2(portName);
        myform.setLabel11("contacting...");
        myform.setLabel7("contacting...");




        // Opens the serial port and configures it, handles errors
        try{
            portId= CommPortIdentifier.getPortIdentifier(portName);
            System.out.println(portName);
        }catch(Exception e){
            System.out.println("Error getting port ID"+ e);
            Enumeration ports = CommPortIdentifier.getPortIdentifiers();


            //tomw - addeed dump of all active ports
            System.out.println(portName);
            System.out.println("Port not Found - Active ports found:");
            while(ports.hasMoreElements()){
                CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
                System.out.println(port.getName());
            }
        }
        try{
            serialPort = (SerialPort) portId.open("My RxTx test", 2000);
            System.out.println("Serial Port Open");
            System.out.println("type in the console window to send commands");
        }catch(Exception e){
            System.out.println("Error opening port "+ e);
            System.exit(1);
        }
        try {
            outputStream = serialPort.getOutputStream();
        } catch (IOException e) {
            System.out.println("Error setting output stream "+e);
        }
        try {
            inputStream = serialPort.getInputStream();
        } catch (IOException e) {
            System.out.println("Error setting input stream "+e);
        }
        try {
            serialPort.setSerialPortParams(9600,
                                           SerialPort.DATABITS_8,
                                           SerialPort.STOPBITS_1,
                                           SerialPort.PARITY_NONE);
            myform.setLabel11("0:0:0");
        } catch (UnsupportedCommOperationException e) {}


        ReadHandler RH = new ReadHandler();
        Thread RT = new Thread(RH);
        RT.start();
        InputStreamReader cmlIn = new InputStreamReader(System.in);
        BufferedReader brIn = new BufferedReader(cmlIn);


    }




    public void longTextChange() {
        if (toggle == false) {
            myform.setLabel2("Oops!");
            toggle = true;
        } else   {
            myform.setLabel2("Ahhhh!");
            toggle = false;
        }
        System.out.println("You pushed me!!");
    }
    public void pushedUp(){
        PrintWriter pr = new PrintWriter(outputStream,true);
        pr.println('U');
        System.out.println("Up");
    }
    public void pushedDown(){
        PrintWriter pr = new PrintWriter(outputStream,true);
        pr.println('D');
        System.out.println("Down");
    }
    public void pushedRight(){
        PrintWriter pr = new PrintWriter(outputStream,true);
        pr.println('R');
        System.out.println("Right");
    }
    public void pushedLeft(){
        PrintWriter pr = new PrintWriter(outputStream,true);
        pr.println('L');
        System.out.println("Left");
     }
    public void pushedZup(){
        PrintWriter pr = new PrintWriter(outputStream,true);
        pr.println('Z');
        System.out.println("Z up");
     }
    public void pushedZdown(){
        PrintWriter pr = new PrintWriter(outputStream,true);
        pr.println('W');
        System.out.println("Z down");
     }


    class ReadHandler implements Runnable {
        volatile boolean on;
        public void run(){
            int c;
            String msgback;
            InputStreamReader IS = new InputStreamReader(inputStream);
            BufferedReader BR = new BufferedReader(IS);
            while(rdg){
                try{
                    msgback=BR.readLine();
                    System.out.println("Position "+ msgback);
                    myform.setLabel11(msgback);
                }catch(Exception e){
                    //tomw - commented out, screen if filling with this message
                    //System.out.println("error reading back"+ e);
                }
            }
        }
    }
}




//--------------------------------------------------------------------------------------------------------------------------------


// Test program for the Arduino
// for development of a serial interface GUI on the PC
// Just makes communication on the serial interface


char inByte = '0';         // incoming serial byte
char outByte = '0';        // outgoing serial byte
boolean contact = false;    //indicates a link partner was found
int stepperX = 0;
int stepperY = 0;
int stepperZ = 0;


void setup()
{
  // start serial port at 9600 bps:
  Serial.begin(9600);
  pinMode(13, OUTPUT);    
}


void loop()
{
  if (Serial.available()) {
    contact = true;
    inByte = Serial.read();
    
     switch( inByte ) {
      case 'U' : 
        digitalWrite(13, HIGH);   // set the LED on
        stepperY++;
        break;
      case 'D' : 
        digitalWrite(13, LOW);    // set the LED off
        stepperY--;
        break;
      case 'R' : 
        for( int i=0; i<3 ; i++) {
          digitalWrite(13, LOW);    // set the LED off
          delay(300);
          digitalWrite(13, HIGH);    // set the LED on
          delay(300);
        }
        stepperX++;
        break; 
      case 'L' : 
        for( int i=0; i<5 ; i++) {
          digitalWrite(13, LOW);    // set the LED off
          delay(100);
          digitalWrite(13, HIGH);    // set the LED on
          delay(100);
        }    
        stepperX--;    
        break;    
      case 'Z' : 
        for( int i=0; i<10 ; i++) {
          digitalWrite(13, LOW);    // set the LED off
          delay(50);
          digitalWrite(13, HIGH);    // set the LED on
          delay(50);
        }        
        stepperZ++;
        break;  
      case 'W' : 
        for( int i=0; i<10 ; i++) {
          digitalWrite(13, LOW);    // set the LED off
          delay(50);
          digitalWrite(13, HIGH);    // set the LED on
          delay(150);
        }  
        stepperZ--;       
        break;   
      default :
        // ignore unknown letter command
        break;
     }
    
    Serial.print(stepperX);Serial.print(":");Serial.print(stepperY);Serial.print(":");Serial.println(stepperZ);    
  } else {
    //spew junk to let the world know you want to talk
    if (!contact)   Serial.print(",");
  }
  
}




4 comments:

  1. I feel this is one of the so much vital information for me. And i am happy studying your blog. However should observation on some general issues, The web site taste is ideal, the blog is actually great : D. Excellent activity, cheers.
    Router Mill

    ReplyDelete
  2. Dear sir,

    i need step by step explanation through videos ...i need to get the information from serial communication using java...

    thanks for advance

    ReplyDelete
  3. I did an earlier post on how to do serial communication to an arduino using java and demonstration code that you can download links are in it.
    http://blog.workingsi.com/2013/01/revisiting-arduino-control-from-pc.html
    I hope that helps, I don't do videos, I hate them.

    ReplyDelete
  4. It is imperative that we read blog post very carefully. I am already done it and find that this post is really amazing. CNC machine

    ReplyDelete