1

I successfully installed and tested the Java Comm API. I could send and receive data through serial port. But the problem is, there are 19 spaces extra before each character. When I tried using hyper terminal, the extra spaces was not there.

Eg:

+CENG:0,"0021,37,99,404,46,36,0000,05,05,77,255"

is expected. But Java program outputs it with spaces before each charector

             +            E            N

The code is:

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;

    public static void main(String[] args) throws Exception
    {
        portList = CommPortIdentifier.getPortIdentifiers();
        System.out.println("SimpleRead Started.");
        while (portList.hasMoreElements())
            {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
                    {
                        System.out.println ("Found " + portId.getName());
                        if (portId.getName().equals("COM5"))
                            {
                                OutputStream outputStream;
                                SerialPort writePort = (SerialPort) portId.open("SimpleWriteApp", 2000);
                                writePort.setSerialPortParams(2400,
                                                              SerialPort.DATABITS_8,
                                                              SerialPort.STOPBITS_1,
                                                              SerialPort.PARITY_NONE);
                                outputStream = writePort.getOutputStream();
                                outputStream.write("AT+CENG=2".getBytes());
                                writePort.close();
                                SimpleRead reader = new SimpleRead();
                            }
                    }
            }
    }

    public SimpleRead()
    {
        try
            {
                serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
            }
        catch (PortInUseException e)
            {
                e.printStackTrace();
            }
        try
            {
                inputStream = serialPort.getInputStream();
            }
        catch (IOException e)
            {
                e.printStackTrace();
            }
        try
            {
                serialPort.addEventListener(this);
            }
        catch (TooManyListenersException e)
            {
                e.printStackTrace();
            }
        serialPort.notifyOnDataAvailable(true);
        try
            {
                serialPort.setSerialPortParams(2400, SerialPort.DATABITS_8,
                                               SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            }
        catch (UnsupportedCommOperationException e)
            {
                e.printStackTrace();
            }
        readThread = new Thread(this);
        readThread.start();
    }

    public void run()
    {
        try
            {
                Thread.sleep(20000);
            }
        catch (InterruptedException e)
            {
                e.printStackTrace();
            }
    }

    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)
                    {
                        e.printStackTrace();
                    }
                break;
            }
    }
}
4
  • 1
    Are you sure your baud rate / flow control / stop bits are set correctly? Can you show your code? For all we know you really are just printing 19 spaces before each character. Commented Aug 13, 2013 at 5:11
  • I set the bits correctly because in hyper terminal I used the same configuration. My code can be found in wepaste.com/harikk09 (sorry for alignment issues) Commented Aug 13, 2013 at 8:49
  • In the future, please include your code with your post. Commented Aug 13, 2013 at 12:53
  • @JasonC Thanks. I will do it in future. Commented Aug 14, 2013 at 3:29

1 Answer 1

1

In your code you have (exception handling removed for purpose of example):

byte[] readBuffer = new byte[20];

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

System.out.print(new String(readBuffer));

You have a 20-byte buffer and you are constructing a String from all 20 bytes no matter how much data you read. In Java, a String can contain nulls, and so your string ends up being a character followed by 19 nulls. Then when you print it your particular console displays spaces instead of nulls.

Couple of things to note. First, it's not really clear what you are trying to do with this loop. You repeatedly read into the same 20 byte buffer no matter how many bytes are left on the stream (e.g. if there are 400 bytes to read, at most readBuffer ends up with the last 20).

Second, to solve the string problem I just described, you want to only use the bytes you actually read from readBuffer, i.e. the first numBytes bytes of the buffer.

Third, you should always specify a character encoding when constructing a String from raw bytes. For your data, it seems us-ascii is appropriate.

So something like this, for example:

byte[] readBuffer = new byte[20];

while (inputStream.available() > 0) {
    int numBytes = inputStream.read(readBuffer);
    System.out.print(new String(readBuffer, 0, numBytes, "us-ascii"));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.