简体   繁体   English

从 java 中的串口读取时获取垃圾值

[英]Getting Garbage value while reading from serial port in java

I am reading data from serialport using jSerialComm package.我正在使用jSerialComm package 从串行端口读取数据。 I am getting following data我收到以下数据

在此处输入图像描述

A total of 22 bytes are being received and I am getting these three garbage bytes too.总共收到了 22 个字节,我也收到了这三个垃圾字节。 The readable data is correct but what these garbage characters are happening?可读数据是正确的,但这些垃圾字符发生了什么?

Following is my code.以下是我的代码。

public static void main(String[] args) {
    SerialPort serialPort = SerialPort.getCommPort("/dev/ttyUSB0");
    if(serialPort.openPort())
    {
        System.out.println("Port Opened Successfully...");
    }
    else
    {
        System.out.println("Unable to open port....");
        return;
    }
    serialPort.setComPortParameters(1200, 8, 1, 0);
    try
    {
        while(true)
        {
            while(serialPort.bytesAvailable() != 0)
            {
                Thread.sleep(1000);
                byte[] readBuffer = new byte[serialPort.bytesAvailable()];
                int numRead = serialPort.readBytes(readBuffer, readBuffer.length);
                String data = new String(readBuffer);
                System.out.println("Read "+numRead+ " bytes." + readBuffer);
                System.out.println(data);
            }
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    serialPort.closePort();
    System.out.println("done...");
}

SerialPort.readBytes seems to be not thread safe, thus yielding "garbage" when called during character reception. SerialPort.readBytes 似乎不是线程安全的,因此在字符接收期间调用时会产生“垃圾”。

I suggest to use the snippet from the author's example which worked fine for me:我建议使用作者示例中的片段,这对我来说效果很好:

// Get a new instance of SerialPort by opening a port.
SerialPort port = SerialPort.open("COM2");

// Configure the connection
port.setTimeout(100);
port.setConfig(BaudRate.B115200, Parity.NONE, StopBits.ONE, DataBits.B8);

// You have the choice, you can either use the Java NIO channels
// or classic Input/Ouput streams to read and write data.
//DEL SerialChannel channel = port.getChannel();
InputStream istream = port.getInputStream();

// Read some data using a stream
byte[] byteBuffer = new byte[4096];
// Will timeout after 100ms, returning 0 if no bytes were available.
int n = istream.read(byteBuffer);

// *** Use n bytes of byteBuffer ***

//DEL ...

port.close();

//DEL : removed from the original code for clarity //DEL : 为清楚起见从原始代码中删除

You did not explain the protocol but I suggest to look it up.你没有解释协议,但我建议查一下。 Presumably these are control characters or like a comment suggests binary data.大概这些是控制字符或像评论建议的二进制数据。 You create a String from a byte buffer without an encoding so this also depends on your environment/ JVM's default encoding.您从没有编码的字节缓冲区创建字符串,因此这也取决于您的环境/JVM 的默认编码。

Try treating the first and the last two bytes as specified in the protocol in use for your project.尝试按照项目使用的协议中指定的方式处理第一个和最后两个字节。 It might also be related to jSerialComm not removing serial signalling, eg handshake, EOT and such.它也可能与 jSerialComm 未删除串行信号有关,例如握手、EOT 等。

If you're reverse-engineering the protocol instead maybe also try another library like RxTx to see if the bytes stay the same.如果您正在对协议进行逆向工程,也可以尝试使用 RxTx 之类的另一个库来查看字节是否保持不变。

To inspect the bytes safely use for example BigInteger to print out a Hex-String instead:要安全地检查字节,请使用例如 BigInteger 来打印出十六进制字符串:

BigInteger bigInteger = new BigInteger(1, bytes);
System.out.printf("%0" + (bytes.length << 1) + "x", bigInteger);

Use this code block and it will run perfectly;使用此代码块,它将完美运行;

    serialPort.addDataListener(new SerialPortDataListener() {
        @Override
        public int getListeningEvents() {
            return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
        }

        @Override
        public void serialEvent(SerialPortEvent serialPortEvent) {
            if (serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_RECEIVED) {
                return;
            }
            byte[] newData = serialPortEvent.getReceivedData();
            String data = new String(newData);
            System.out.println(data);

        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM