Welcome to Dream.In.Code
Become a Java Expert!

Join 150,116 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,960 people online right now. Registration is fast and FREE... Join Now!




Serial Port Communications and GUI Display

 
Reply to this topicStart new topic

Serial Port Communications and GUI Display

HulkingNightcrawler
26 Jun, 2008 - 12:26 PM
Post #1

New D.I.C Head
*

Joined: 26 Jun, 2008
Posts: 20

I am trying to read data off of a serial port and then display the data in a GUI. I am having trouble appending the data on the GUI though, and for some reason it looks to me like my code is getting stuck on the txtOutput.append(new String(readBuffer)) line in the serialEvent method. Any advice/help/assistance would be greatly appreciated, thanks!!!

CODE



public class Data implements Runnable, SerialPortEventListener{
    static CommPortIdentifier    portId;
    static Enumeration            portList;
    InputStream                      inputStream;
    SerialPort                     serialPort;
    Thread                          readThread;
    static Shell                          shell;
    static Display                          dispMain;
    static Text                        txtOutput;

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

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

        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;
                    Data reader = new Data();
                }
            }
        }
        if (!portFound) {
            System.out.println("port " + defaultPort + " not found.");
        }
        
        while (!shell.isDisposed())
        {
            if (!dispMain.readAndDispatch()) dispMain.sleep();
        }
    }

    /**
     * Constructor declaration
     *
     *
     * @see
     */
    public Data() {
        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) {}
    }

    public static void buildGUI()
    {
        dispMain = new Display();
        shell = new Shell(dispMain);

        shell.setText("Parking Meter Test Bench Data");
        shell.setSize(800,600);
        shell.open();        

        txtOutput = new Text(shell, SWT.BORDER | SWT.H_SCROLL |SWT.V_SCROLL);
        txtOutput.setBounds(10,90,200,200);
        txtOutput.setEditable(false);
        txtOutput.setText("Test Text\n");
        txtOutput.append("Hello World");    
        txtOutput.append("Hello Look at Me");
        txtOutput.setLocation(10, 150);        
        
        

    }

    /**
     * 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));
                txtOutput.append(new String(readBuffer));
                
            } catch (IOException e) {}

            break;
        }
    }

}

User is offlineProfile CardPM
+Quote Post

pbl
RE: Serial Port Communications And GUI Display
26 Jun, 2008 - 02:28 PM
Post #2

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,587



Thanked: 233 times
Dream Kudos: 75
My Contributions
CODE

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));
        txtOutput.append(new String(readBuffer));
                
    } catch (IOException e) {}



You are trying to read 20 bytes even if there are only 5 bytes on the stream
your inputStream.read() will get stuck until effectively 20 bytes are available to read.

Even worst if 25 bytes are available... you will read the first 20 ones and then get stuck trying to read 20 other bytes
without having printing them (stuck in your while loop) and erasing in readBuffer the 20 last ones you have read

better to do it that way

CODE

case SerialPortEvent.DATA_AVAILABLE:

    try {
        int nb = inputStream.available();
        while (nb > 0) {
            byte[] readBuffer = new byte[nb];
            inputStream.read(readBuffer);      
            String str = new String(readBuffer);
            System.out.print(str);
            txtOutput.append(str);
            nb = inputStream.available();
        }                  
                
    } catch (IOException e) {}



By the way, why creating a Thread that does nothing ?

This post has been edited by pbl: 26 Jun, 2008 - 07:36 PM
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/9/09 01:12AM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month