-1

I have problems reading from a serial port, I’m trying the code below to read and write from a serial port, I run the program and I enter some data in console and I can write to serial ports. I’m using an application “Free Device Monitoring Studio” to watch the serial port’s behavior. But when I run my program it doesn’t read any data. This is the Program which I got from this link:

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * This version of the TwoWaySerialComm example makes use of the
 * SerialPortEventListener to avoid polling.
 *
 */
public class TwoWaySerialComm
{
    public TwoWaySerialComm()
    {
        super();
    }

    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);


                OutputStream out = serialPort.getOutputStream();

                (new Thread(new SerialWriter(out))).start();
                InputStream in = serialPort.getInputStream();
     // serialPort.notifyOnDataAvailable(true);
                serialPort.addEventListener(new SerialReader(in));

                serialPort.notifyOnDataAvailable(true);

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }


       public static class SerialWriter implements Runnable
    {
        OutputStream out;

        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }

        public void run ()
        {
            try
            {
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write((byte)c);
                    System.out.println((byte)c);
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }



    /**
     * Handles the input coming from the serial port. A new line character
     * is treated as the end of a block in this example.
     */
    public static class SerialReader implements SerialPortEventListener
    {
        private InputStream in;
        private byte[] buffer = new byte[1024];

        public SerialReader ( InputStream in )
        {
            this.in = in;
        }

        public void serialEvent(SerialPortEvent arg0) {
            int data;

            try
            {
                data = in.read();
                int len = 0;
                while ( in.available()>0 )
                {
                    if ( data == '\n' ) {
                        break;
                    }
                    buffer[len++] = (byte) data;
                }
                System.out.print("read"+new String(buffer,0,len));
            }
            catch ( IOException e )
            {
               System.out.println(e.getMessage());
               System.out.println("error");
               e.printStackTrace();
            }
        }

    }

    /** */




    public static void main ( String[] args )
    {
        try
        {
            (new TwoWaySerialComm()).connect("COM5");
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.print(e.toString());
        }
    }


}

I put a breakpoint at While loop in serialEvent(SerialPortEvent arg0) method,

 while ( ( data = in.read()) > -1 )

But it never arrives at breakpoint. And It can't read data and so it doesn't write something in console with this line:

System.out.print("read"+new String(buffer,0,len));

I need some help to know what the problem is.

Bootimar
  • 3
  • 5

2 Answers2

0

You shouldn't be reading to end of stream in an event handler. This is one of the rare cases where you should loop while (in.available() > 0).

EDIT Sigh.

int len = 0;
while (in.available() > 0)
{
    data = in.read();
    if ( data == -1 || data == '\n' ) {
        break;
    }
    buffer[len++] = (byte) data;
}
user207421
  • 305,947
  • 44
  • 307
  • 483
  • I Changed the While loop to what you said but there is no difference in the rezult. @EJP – Bootimar Sep 23 '15 at 09:02
  • You'll have to show us. Telling us is not sufficient. Edit the new code into your question. – user207421 Sep 23 '15 at 09:43
  • Give me a break. You aren't doing any reads inside that loop. You're just coding nonsense here. What in earth would be the point of looping without doing a read? It doesn't make sense. – user207421 Sep 23 '15 at 10:12
  • how should I do a read there? I thought it's reading what I'm writing on the console. maybe it's my question @EJP – Bootimar Sep 23 '15 at 10:18
  • You should do the read inside the loop, of course. I'm trying to get you to think here. – user207421 Sep 23 '15 at 10:21
  • But my problem is that when debugging it ignores my breakpoint in front of the while loop, implementing the while loop is another story. @EJP – Bootimar Sep 23 '15 at 10:25
  • No, your problem is that your code is nonsense. Fix that and you won't have to debug it. I haven't used a debugger for several years. See edit. – user207421 Sep 23 '15 at 10:25
  • I applied your edit. no difference again. It ignores the implementation of serialEvent when debugging. the problem is not that while loop. it is why it doesn't come to the while loop. @EJP – Bootimar Sep 23 '15 at 10:30
  • So you haven't added the event listener, or you need to uncomment the line that is commented out immediately above it. And you need to make all these issues clear in your question, instead of reserving them for comments on answers. You didn't state that the code was never executed. And your previous claim about ignoring the breakpoint is obviously untrue. You never got to it at all. It is impossible to help people who don't report their symptoms accurately and completely. It is a vital skill. Cultivate it. – user207421 Sep 23 '15 at 10:33
  • I think you haven't read my question carefully and my code never arrives at that breakpoint when debugging. my code executes but it doesn't read, it doesn't have any problem with writing. I don't konw why it doesn't print anything on console if it is reading. @EJP – Bootimar Sep 23 '15 at 10:49
  • Never arriving at a breakpoint is different from ignoring a breakpoint. The first is unexpected program flow. The second is a bug in the debugger. You're in no position to criticize others' reading. The only interesting thing here is what happened when you tried the suggestions in my last comment, and there's no evidence here that you've even tried it. The merest glance at the [Javadoc](http://docs.oracle.com/cd/E17802_01/products/products/javacomm/reference/api/javax/comm/SerialPort.html#notifyOnDataAvailable(boolean)) suggests that calling `notifyOnDataAvailable()` is essential. – user207421 Sep 23 '15 at 10:54
  • I applied all of your suggestions and nothing happened in result. I would tell you if it made something new. – Bootimar Sep 23 '15 at 10:58
  • about notifyOnDataAvailable(): I applied it after serialPort.addEventListener(new SerialReader(in)); – Bootimar Sep 23 '15 at 11:04
0

I found answer by myself. my mistake was that I was sending something nonsense to my board via serial port, when I sent something meaningful it was reading from serial port too.

Bootimar
  • 3
  • 5