java 串口读写程序


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


import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.UnsupportedCommOperationException;


public class CommIO {
private static SerialPort serialPort;
private static InputStream inputStream;
private static OutputStream outputStream;


public static InputStream getInputStream() {
if (inputStream == null) {
try {
System.out.println("初始化输入流");
inputStream = getSerialPort().getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
return inputStream;
}


public static OutputStream getOutputStream() {
if (outputStream == null) {
try {
System.out.println("初始化输出流");
outputStream = getSerialPort().getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
return outputStream;
}


public static void initialSerialPort(String comm, String baudRate) {
System.out.println("初始化SerialPort");
try {
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier portId = null;
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)// 如果端口类型是串口则判断名称
{
if (portId.getName().equals(comm)) {// 如果是COM1端口则退出循环
break;
} else {
portId = null;
}
}
}
serialPort = (SerialPort) portId.open(
"Serial_Communication", 1000);// 打开串口的超时时间为1000ms
serialPort.setSerialPortParams(Integer.parseInt(baudRate),
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);// 设置串口速率为9600,数据位8位,停止位1们,奇偶校验无
serialPort.notifyOnDataAvailable(true);//这一句话让我浪费了一个上午的时间。没有这句话,添加串口监听器收不到数据
} catch (PortInUseException e) {
e.printStackTrace();
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
}


}


public static SerialPort getSerialPort() {
return serialPort;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值