赞
踩
两种不同的方法,适用于所有java读取串口的情况。
下载地址RXTX for Java (fizzed.com)http://fizzed.com/oss/rxtx-for-java
可以看到在rxtx文档介绍中已经介绍了应该咋那么存放文件
rxtxParallel.dll
,rxtxSerial.dll
复制到C:\Program Files\Java\jdk1.8.0_112\jre\bi
将RXTXcomm.jar 导入项目中。
IDEA设置:Ctrl+Shift+ALt+S——>选择Libraries——>左上角+号找到jar包所在位置添加应用。
-
- import gnu.io.CommPortIdentifier;
- import gnu.io.SerialPort;
-
- import java.io.InputStream;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.Scanner;
- import java.util.Timer;
- import java.util.TimerTask;
-
- public class SerialReader {
-
- public static void main(String[] args) throws Exception {
- CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM3");
- SerialPort serialPort = (SerialPort) portIdentifier.open("SerialReader", 2000);
- serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
- InputStream input = serialPort.getInputStream();
-
- Timer timer = new Timer();
- TimerTask task = new TimerTask() {
- @Override
- public void run() {
- try {
- SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
- Date date = new Date(System.currentTimeMillis());
- Scanner scanner = new Scanner(input);
- while (scanner.hasNextLine()) {
- String line = scanner.nextLine();
- System.out.println("串口发送: "+line+" "+formatter.format(date));
- }
- } catch (Exception e) {
- System.err.println("从串口读取失败:" + e.getMessage());
- }
- }
- };
-
- // 每隔1秒执行一次任务x
- timer.scheduleAtFixedRate(task, 0, 1000);
- }
-
-
- }
注意:运行时串口不得被其他软件或者硬件占用。不然读取会报错。
- <dependency>
- <groupId>com.fazecast</groupId>
- <artifactId>jSerialComm</artifactId>
- <version>2.6.2</version>
- </dependency>
如果引入不进去的可以去官网下载依赖,手动导包。
- import com.fazecast.jSerialComm.SerialPort;
-
- import java.io.InputStream;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.Scanner;
- import java.util.Timer;
- import java.util.TimerTask;
-
- public class JSerialCommReader {
- public static void main(String[] args) {
- SerialPort serialPort = SerialPort.getCommPort("COM3");
- serialPort.openPort();
- serialPort.setBaudRate(9600);
- serialPort.setNumDataBits(8);
- serialPort.setNumStopBits(1);
- serialPort.setParity(SerialPort.NO_PARITY);
-
- InputStream input = serialPort.getInputStream();
-
- Timer timer = new Timer();
- TimerTask task = new TimerTask() {
- @Override
- public void run() {
- try {
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
- Date date = new Date(System.currentTimeMillis());
- Scanner scanner = new Scanner(input);
- while (scanner.hasNextLine()) {
- String line = scanner.nextLine();
- System.out.println("串口发送: " + line + " " + formatter.format(date));
- }
- } catch (Exception e) {
- System.err.println("从串口读取失败:" + e.getMessage());
- }
- }
- };
-
- // 每隔1秒执行一次任务
- timer.scheduleAtFixedRate(task, 0, 1000);
-
- // 运行后请记得在合适的地方关闭串口连接,例如在应用程序退出时
- // serialPort.closePort();
- }
- }
- import gnu.io.CommPortIdentifier;
- import gnu.io.SerialPort;
-
- import java.io.OutputStream;
-
- public class SerialWriter {
-
- public static void main(String[] args) throws Exception {
- // 调用 sendSerialData 方法发送串口数据
- sendSerialData("COM3", "hello World");
- }
-
- /**
- * 发送串口数据
- *
- * @param portName 串口名称
- * @param data 要发送的数据
- * @throws Exception 发送数据时可能抛出的异常
- */
- public static void sendSerialData(String portName, String data) throws Exception {
- // 获取串口标识符
- CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
- // 打开串口
- SerialPort serialPort = (SerialPort) portIdentifier.open("SerialWriter", 2000);
- // 设置串口参数
- serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
- // 获取输出流
- OutputStream output = serialPort.getOutputStream();
-
- // 将字符串转换为字节数组,并写入串口
- output.write(data.getBytes());
-
- // 关闭输出流和串口
- output.close();
- serialPort.close();
- }
- }
-
-
- import com.fazecast.jSerialComm.SerialPort;
-
- import java.io.OutputStream;
-
- public class JSerialCommWriter{
- public static void main(String[] args) {
- // 获取串口对象
- SerialPort serialPort = SerialPort.getCommPort("COM3");
- // 打开串口
- serialPort.openPort();
- // 设置串口参数
- serialPort.setBaudRate(9600);
- serialPort.setNumDataBits(8);
- serialPort.setNumStopBits(1);
- serialPort.setParity(SerialPort.NO_PARITY);
-
- try {
- // 获取串口输出流
- OutputStream output = serialPort.getOutputStream();
-
- // 要发送的数据
- String data = "Hello World";
- // 将数据转换为字节数组
- byte[] bytes = data.getBytes();
-
- // 将数据写入串口输出流
- output.write(bytes);
- // 刷新输出流,确保数据被发送到串口
- output.flush();
-
- System.out.println("已发送数据:" + data);
- } catch (Exception e) {
- System.err.println("发送数据失败:" + e.getMessage());
- } finally {
- // 关闭串口连接
- serialPort.closePort();
- }
- }
- }
- import com.fazecast.jSerialComm.SerialPort;
-
- import java.io.OutputStream;
- import java.util.Scanner;
-
- public class JSerialCommWriter {
- public static void main(String[] args) {
- // 获取串口对象
- SerialPort serialPort = SerialPort.getCommPort("COM3");
- // 打开串口
- serialPort.openPort();
- // 设置串口参数
- serialPort.setBaudRate(9600);
- serialPort.setNumDataBits(8);
- serialPort.setNumStopBits(1);
- serialPort.setParity(SerialPort.NO_PARITY);
-
- // 获取串口输出流
- OutputStream output = serialPort.getOutputStream();
- Scanner scanner = new Scanner(System.in);
- System.out.println("请输入要发送的数据:");
-
- // 不断读取用户输入并发送到串口
- while (true) {
- // 读取用户输入
- String input = scanner.nextLine();
- if (input.equalsIgnoreCase("exit")) {
- break;
- }
-
- try {
- // 将输入的数据转换为字节数组
- byte[] data = input.getBytes();
- // 将数据写入串口输出流
- output.write(data);
- // 刷新输出流,确保数据被发送到串口
- output.flush();
- System.out.println("已发送数据:" + input);
- } catch (Exception e) {
- System.err.println("发送数据失败:" + e.getMessage());
- }
- }
-
- // 关闭串口连接
- serialPort.closePort();
- }
- }
RXTX 和 jSerialComm 都是用于在Java中进行串口通信的库,它们有一些区别和特点,下面我将详细比较这两个库:
SerialPort
和 SerialPortEvent
。总的来说,jSerialComm 在易用性、跨平台性和维护活跃性方面更有优势,特别适用于一般用途的串口通信。如果您需要更高性能的串口通信或有特殊需求,RXTX也是一个可选的选择,但需要更多的配置和处理。但需要注意的是,由于RXTX的维护相对较慢,建议在新项目中考虑使用jSerialComm。
下篇给大家分享如何利用websocket将串口数据进行传输
Java通过WebSocket读取传输串口数据
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。