Re: Com port Communication



gy_722 wrote:

Hi,

Thank you for your reply. I have get the null modem cable already. And
i have two java simple read and simple write program in hand, but it
don't work.

SimpleRead.java

import java.io.*;
import java.util.*;
import javax.comm.*;

public class SimpleRead implements Runnable, SerialPortEventListener {
    static CommPortIdentifier portId;
    static Enumeration	      portList;
    InputStream		      inputStream;
    SerialPort		      serialPort;
    Thread		      readThread;

    /**
     * Method declaration
     *
     *
     * @param args
     *
     * @see
     */
    public static void main(String[] args) {
    boolean		      portFound = false;
    String		      defaultPort = "com1";

 	if (args.length > 0) {
	    defaultPort = args[0];
	}

	portList = CommPortIdentifier.getPortIdentifiers();

	while (portList.hasMoreElements()) {
	    portId = (CommPortIdentifier) portList.nextElement();
	    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
		if (portId.getName().equals(defaultPort)) {
		    System.out.println("Found port: "+defaultPort);
		    portFound = true;
		    SimpleRead reader = new SimpleRead();
		}
	    }
	}
	if (!portFound) {
	    System.out.println("port " + defaultPort + " not found.");
	}

    }

    /**
     * Constructor declaration
     *
     *
     * @see
     */
    public SimpleRead() {
	try {
	    serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
	} catch (PortInUseException e) {}

	try {
	    inputStream = serialPort.getInputStream();
	} catch (IOException e) {}

	try {
	    serialPort.addEventListener(this);
	} catch (TooManyListenersException e) {}

	serialPort.notifyOnDataAvailable(true);

	try {
	    serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
					   SerialPort.STOPBITS_1,
					   SerialPort.PARITY_NONE);
	} catch (UnsupportedCommOperationException e) {}

	readThread = new Thread(this);

	readThread.start();
    }

    /**
     * Method declaration
     *
     *
     * @see
     */
    public void run() {
	try {
	    Thread.sleep(20000);
	} catch (InterruptedException e) {}
    }

    /**
     * Method declaration
     *
     *
     * @param event
     *
     * @see
     */
    public void serialEvent(SerialPortEvent event) {
	switch (event.getEventType()) {

	case SerialPortEvent.BI:

	case SerialPortEvent.OE:

	case SerialPortEvent.FE:

	case SerialPortEvent.PE:

	case SerialPortEvent.CD:

	case SerialPortEvent.CTS:

	case SerialPortEvent.DSR:

	case SerialPortEvent.RI:

	case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
	    break;

	case SerialPortEvent.DATA_AVAILABLE:
	    byte[] readBuffer = new byte[20];

	    try {
		while (inputStream.available() > 0) {
		    int numBytes = inputStream.read(readBuffer);
		}

		System.out.print(new String(readBuffer));
	    } catch (IOException e) {}

	    break;
	}
    }

}

SimpleWrite.java


import java.io.*; import java.util.*; import javax.comm.*;

/**
 * Class declaration
 *
 *
 * @author
 * @version 1.10, 08/04/00
 */
public class SimpleWrite {
    static Enumeration	      portList;
    static CommPortIdentifier portId;
    static String	      messageString = "Hello, world!";
    static SerialPort	      serialPort;
    static OutputStream       outputStream;
    static boolean	      outputBufferEmptyFlag = false;

    public static void main(String[] args) {
	boolean portFound = false;
	String  defaultPort = "com2";

	if (args.length > 0) {
	    defaultPort = args[0];
	}

	portList = CommPortIdentifier.getPortIdentifiers();

	while (portList.hasMoreElements()) {
	    portId = (CommPortIdentifier) portList.nextElement();

	    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

		if (portId.getName().equals(defaultPort)) {
		    System.out.println("Found port " + defaultPort);

		    portFound = true;

		    try {
			serialPort =
			    (SerialPort) portId.open("SimpleWrite", 2000);
		    } catch (PortInUseException e) {
			System.out.println("Port in use.");

			continue;
		    }

		    try {
			outputStream = serialPort.getOutputStream();
		    } catch (IOException e) {}

		    try {
			serialPort.setSerialPortParams(9600,
						       SerialPort.DATABITS_8,
						       SerialPort.STOPBITS_1,
						       SerialPort.PARITY_NONE);
		    } catch (UnsupportedCommOperationException e) {}


try { serialPort.notifyOnOutputEmpty(true); } catch (Exception e) { System.out.println("Error setting event notification"); System.out.println(e.toString()); System.exit(-1); }


System.out.println( "Writing \""+messageString+"\" to " +serialPort.getName());

		    try {
			outputStream.write(messageString.getBytes());
		    } catch (IOException e) {}

		    try {
		       Thread.sleep(2000);  // Be sure data is xferred before closing
		    } catch (Exception e) {}
		    serialPort.close();
		    System.exit(1);
		}
	    }
	}

	if (!portFound) {
	    System.out.println("port " + defaultPort + " not found.");
	}
    }


}


I have try to complie this two program, it nothing error. But when i run them, nothing show in the output of SimpleRead.java when my SimpleWrite.java send the string out.

Please help.

Thank you.


One of the biggest problems with the Comm API is getting it installed correctly. Use the program below to check. If your ports are listed then you've installed it correctly.


import java.io.*;
import java.util.*;
import javax.comm.*;

public class Ports {
    public Ports() {
        CommPortIdentifier cpi = null;

        Enumeration e = CommPortIdentifier.getPortIdentifiers();

        while (e.hasMoreElements()) {
            try {
                cpi = (CommPortIdentifier) e.nextElement();
            } catch (NoSuchElementException n) {}
            System.out.println(cpi.getName());
        }
    }
    public static void main(String[] args) { new Ports(); }
}

--

Knute Johnson
email s/nospam/knute/
.



Relevant Pages

  • Re: Com port Communication
    ... static CommPortIdentifier portId; ... public static void main{ ... static OutputStream outputStream; ...
    (comp.lang.java.programmer)
  • Re: Multiple Undetermined Number of Variables
    ... I"m betting that you are NOT allocating the individual SerialPort instances. ... foreach (string portName in SerialPort.GetPortNames()) ... Uniquely and simultaneously use these ports: ...
    (microsoft.public.dotnet.languages.csharp)
  • Java Communications API, help to start!
    ... I have problem with Java Communications API. ... SerialPort serialPort; ... expect the list of ports, ... javax.comm.properties file correct? ...
    (comp.lang.java.programmer)
  • Re: Multiple Undetermined Number of Variables
    ... number of SerialPort instances that correspond to the number of ports on the ... SerialPort> using the name of the serial port as a key. ... so my code needs to be dynamic with this ... because I want to monitor ALL COM ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: RFID with PIC (PIC16F876)
    ... My laptop has no COM ports. ... My latest cheapy desktop has 2 serial ports and 4 USB ports ... yes, most desktops still have a serialport, but.. ...
    (sci.electronics.design)