SerialPortManager.java 文件源码

java
阅读 32 收藏 0 点赞 0 评论 0

项目:SerialPortDemo 作者:
/**
 * 打开串口
 * 
 * @param portName
 *            端口名称
 * @param baudrate
 *            波特率
 * @return 串口对象
 * @throws SerialPortParameterFailure
 *             设置串口参数失败
 * @throws NotASerialPort
 *             端口指向设备不是串口类型
 * @throws NoSuchPort
 *             没有该端口对应的串口设备
 * @throws PortInUse
 *             端口已被占用
 */
public static final SerialPort openPort(String portName, int baudrate)
        throws SerialPortParameterFailure, NotASerialPort, NoSuchPort,
        PortInUse {
    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,
                        SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
            } catch (UnsupportedCommOperationException e) {
                throw new SerialPortParameterFailure();
            }
            return serialPort;
        } else {
            // 不是串口
            throw new NotASerialPort();
        }
    } catch (NoSuchPortException e1) {
        throw new NoSuchPort();
    } catch (PortInUseException e2) {
        throw new PortInUse();
    }
}
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号