Java连接串口代码

类库和实例程序下载

https://download.csdn.net/download/TaiJi1985/12538399

代码

import java.util.ArrayList;

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

public class DemoSP {
	public static void main(String[] args) throws Exception {
		ArrayList<String> ret = SerialPortUtil.findPort();
		for(String string : ret){
			System.out.println(string);
		}
		
		
		SerialPort p1 = SerialPortUtil.openPort("COM1", 9600, 8, 0, 1);
		
		SerialPortUtil.sendToPort(p1, "hello".getBytes());
		SerialPortUtil.addListener(p1, new SerialPortEventListener() {
			
			@Override
			public void serialEvent(SerialPortEvent e) {
				System.out.println(e.getEventType());
				if(SerialPortEvent.DATA_AVAILABLE != e.getEventType())return;
				try {
					byte[] a = SerialPortUtil.readFromPort(p1);
					System.out.println(new String(a));
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				
			}
		});
	}
}

下面这个类库是从互联网获取的帮助类

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.TooManyListenersException;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

/**
 * 模块名称:projects-parent com.yotrio.common
 * 功能说明:串口服务类,提供打开、关闭串口,读取、发送串口数据等服务(采用单例设计模式)
 * <br>
 * 开发人员:Wangyq 
 * 创建时间: 2018-09-20 10:05
 * 系统版本:1.0.0
 **/

public class SerialPortUtil {

    private static SerialPortUtil serialPortUtil = null;

    static {
        //在该类被ClassLoader加载时就初始化一个SerialTool对象
        if (serialPortUtil == null) {
            serialPortUtil = new SerialPortUtil();
        }
    }

    //私有化SerialTool类的构造方法,不允许其他类生成SerialTool对象
    private SerialPortUtil() {
    }

    /**
     * 获取提供服务的SerialTool对象
     *
     * @return serialPortUtil
     */
    public static SerialPortUtil getSerialPortUtil() {
        if (serialPortUtil == null) {
            serialPortUtil = new SerialPortUtil();
        }
        return serialPortUtil;
    }


    /**
     * 查找所有可用端口
     *
     * @return 可用端口名称列表
     */
    public static final ArrayList<String> findPort() {
        //获得当前所有可用串口
        Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();

        ArrayList<String> portNameList = new ArrayList<>();

        //将可用串口名添加到List并返回该List
        while (portList.hasMoreElements()) {
            String portName = portList.nextElement().getName();
            portNameList.add(portName);
        }

        return portNameList;
    }

    /**
     * 打开串口
     *
     * @param portName 端口名称
     * @param baudrate 波特率
     * @param databits 数据位
     * @param parity   校验位(奇偶位)
     * @param stopbits 停止位
     * @return 串口对象
     * @throws SerialPortParameterFailure 设置串口参数失败
     * @throws NotASerialPort             端口指向设备不是串口类型
     * @throws NoSuchPort                 没有该端口对应的串口设备
     * @throws PortInUse                  端口已被占用
     */
    public static final SerialPort openPort(String portName, int baudrate, int databits, int parity, int stopbits) throws Exception {

        try {
            //通过端口名识别端口
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);

            //打开端口,并给端口名字和一个timeout(打开操作的超时时间)
            CommPort commPort = portIdentifier.open(portName, 2000);

            //判断是不是串口
            if (commPort instanceof SerialPort) {

                SerialPort serialPort = (SerialPort) commPort;
                try {
                    //设置一下串口的波特率等参数
                    serialPort.setSerialPortParams(baudrate, databits, stopbits, parity);
                } catch (UnsupportedCommOperationException e) {
                    throw new Exception("unsupported operation ");
                }

                //System.out.println("Open " + portName + " sucessfully !");
                return serialPort;
            } else {
                //不是串口
                throw new Exception("no port ");
            }
        } catch (NoSuchPortException e1) {
            throw new Exception("no such port ");
        } catch (PortInUseException e2) {
            throw new Exception(" port in use ");
        }
    }

    /**
     * 关闭串口
     *
     * @param serialPort 待关闭的串口对象
     */
    public static void closePort(SerialPort serialPort) {
        if (serialPort != null) {
            serialPort.close();
            serialPort = null;
        }
    }

    /**
     * 往串口发送数据
     *
     * @param serialPort 串口对象
     * @param order      待发送数据
     * @throws SendDataToSerialPortFailure        向串口发送数据失败
     * @throws SerialPortOutputStreamCloseFailure 关闭串口对象的输出流出错
     */
    public static void sendToPort(SerialPort serialPort, byte[] order) throws Exception {
        OutputStream out = null;
        try {
            out = serialPort.getOutputStream();
            out.write(order);
            out.flush();
        } catch (IOException e) {
            throw new Exception("send fail");
        } finally {
            try {
                if (out != null) {
                    out.close();
                    out = null;
                }
            } catch (IOException e) {
               
            }
        }
    }

    /**
     * 从串口读取数据
     *
     * @param serialPort 当前已建立连接的SerialPort对象
     * @return 读取到的数据
     * @throws ReadDataFromSerialPortFailure     从串口读取数据时出错
     * @throws SerialPortInputStreamCloseFailure 关闭串口对象输入流出错
     */
    public static byte[] readFromPort(SerialPort serialPort) throws Exception {

        InputStream in = null;
        byte[] bytes = null;

        try {
            in = serialPort.getInputStream();
            int bufflenth = in.available();        //获取buffer里的数据长度

            while (bufflenth != 0) {
                bytes = new byte[bufflenth];    //初始化byte数组为buffer中数据的长度
                in.read(bytes);
                bufflenth = in.available();
            }
        } catch (IOException e) {
            throw new Exception("read fail");
        } finally {
            try {
                if (in != null) {
                    in.close();
                    in = null;
                }
            } catch (IOException e) {
            }
        }

        return bytes;

    }

    /**
     * 添加监听器
     *
     * @param port     串口对象
     * @param listener 串口监听器
     * @throws TooManyListeners 监听类对象过多
     */
    public static void addListener(SerialPort port, SerialPortEventListener listener) throws Exception {

        try {
            //给串口添加监听器
            port.addEventListener(listener);
            //设置当有数据到达时唤醒监听接收线程
            port.notifyOnDataAvailable(true);
            //设置当通信中断时唤醒中断线程
            port.notifyOnBreakInterrupt(true);
        } catch (TooManyListenersException e) {
            throw new Exception("too many listeners");
        }
    }

    /**
     * 删除监听器
     *
     * @param port     串口对象
     * @param listener 串口监听器
     * @throws TooManyListeners 监听类对象过多
     */
    public static void removeListener(SerialPort port, SerialPortEventListener listener) {
        //删除串口监听器
        port.removeEventListener();
    }

}
···
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以通过使用Java Comm API来连接串口。以下是连接串口的一些基本步骤: 1. 下载并安装Java Comm API。这个API是Java的一个扩展包,因此需要单独下载并安装。可以在Oracle官网上下载,也可以在其他网站上找到。 2. 打开串口。可以使用CommPortIdentifier类来获取串口的标识符,然后使用open()方法打开串口。 ```java CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM1"); SerialPort serialPort = (SerialPort) portIdentifier.open("MyApp", 1000); ``` 3. 配置串口参数。可以使用SerialPort类的setSerialPortParams()方法来设置串口的波特率、数据位、停止位和校验位等参数。 ```java serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); ``` 4. 读写串口数据。可以使用InputStream和OutputStream类来读写串口数据。例如,可以使用下面的代码串口发送数据: ```java OutputStream outputStream = serialPort.getOutputStream(); outputStream.write("Hello World".getBytes()); ``` 可以使用下面的代码串口读取数据: ```java InputStream inputStream = serialPort.getInputStream(); byte[] buffer = new byte[1024]; int len = inputStream.read(buffer); String data = new String(buffer, 0, len); ``` 5. 关闭串口。使用SerialPort类的close()方法来关闭串口。 ```java serialPort.close(); ``` 需要注意的是,Java Comm API只支持Windows和Linux操作系统,不支持Mac OS。在使用Java Comm API时,需要在程序中添加comm.jar和javax.comm.properties两个文件的路径到classpath中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值