java监听串口数据

java监听串口,我看了下3个实现方式

JavaComm;RXTX; PureJavaComm

发现JavaComm太陈旧;PureJavaComm运行都困难。只有RXTX支持的比较好。

使用RXTX需要下载对应的32位或64位DLL文件。下载地址 http://rxtx.qbang.org/wiki/index.php/Download

RXTXcomm.jar 拷贝到 %JAVA_HOME%\jre\lib\ext
rxtxSerial.dll ;rxtxParallel 拷贝到 in %JAVA_HOME%\jre\bin  同时拷贝到 C:\Windows\System32  目录

pom文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.xx</groupId>
    <artifactId>ShowData</artifactId>
    <version>1.0.0</version>


    <name>ShowDataFromSerial</name>
    <description>获取串口数据展示到swing上面</description>
    <inceptionYear>2011-2018</inceptionYear>


    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
         <dependency>
            <groupId>com.github.purejavacomm</groupId>
            <artifactId>purejavacomm</artifactId>
            <version>1.0.1.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

监听程序代码如下:

import java.io.IOException;

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


import com.sunit.window.MainWindows2;


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


public class SerialComm4MainWindows {
    public SerialComm4MainWindows() {
        super();
    }


   public  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(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);


                InputStream in = serialPort.getInputStream();
                (new Thread(new SerialReader(in))).start();
            } else {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }


    /** 读串口数据*/
    public static class SerialReader implements Runnable {
        InputStream in;


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


        public void run() {
            byte[] buffer = new byte[1024];
            int len = -1;
            try {
                while ((len = this.in.read(buffer)) > -1) {
                    String getValue = new String(buffer, 0, len);
                    if(getValue != null && getValue.length() > 2) {
                        MainWindows2.parseValue(getValue);  //获取值往另一个地方丢
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /** */
    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(c);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        try {
            (new SerialComm4MainWindows()).connect("COM5");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Java监听串口可以使用Java Comm API。下面是一个简单的示例代码,演示如何使用Java Comm API在多线程中监听串口: ```java import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.Enumeration; public class SerialCommunication implements Runnable, SerialPortEventListener { private static final int TIME_OUT = 2000; //等待超时时间 private static final int BAUD_RATE = 9600; //波特率 private CommPortIdentifier portId; private SerialPort serialPort; private BufferedReader input; private OutputStream output; private boolean isRunning = false; public static void main(String[] args) { SerialCommunication communication = new SerialCommunication(); communication.start(); } public void start() { Thread thread = new Thread(this); thread.start(); } public void run() { try { //获取串口ID Enumeration portEnum = CommPortIdentifier.getPortIdentifiers(); while (portEnum.hasMoreElements()) { CommPortIdentifier currentPortId = (CommPortIdentifier) portEnum.nextElement(); if (currentPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) { portId = currentPortId; break; } } if (portId == null) { System.out.println("没有发现串口"); return; } //打开串口并设置参数 serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT); serialPort.setSerialPortParams(BAUD_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); //获取输入输出流 input = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); output = serialPort.getOutputStream(); //添加串口事件监听器 serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); System.out.println("串口已打开,开始监听..."); isRunning = true; while (isRunning) { Thread.sleep(1000); } //关闭串口 serialPort.removeEventListener(); serialPort.close(); input.close(); output.close(); System.out.println("串口已关闭"); } catch (Exception ex) { System.out.println("打开串口失败:" + ex.getMessage()); } } public void stop() { isRunning = false; } public void serialEvent(SerialPortEvent event) { if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) { try { String inputLine = input.readLine(); System.out.println("接收到数据:" + inputLine); } catch (Exception ex) { System.out.println("读取串口数据失败:" + ex.getMessage()); } } } } ``` 该示例代码中,首先使用`CommPortIdentifier`类获取所有串口的ID,然后找到需要监听串口的ID。接着打开串口并设置参数,获取输入输出流,并添加串口事件监听器。在`serialEvent`方法中,可以处理从串口接收到的数据。`start`方法创建一个新的线程,该线程调用`run`方法开始监听串口。`stop`方法可以停止监听。 使用多线程的好处是可以在主线程中执行其他任务,而不会阻塞串口监听。当然,在处理串口数据时也可以使用多线程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值