java串口
1. java實現串口通信代碼
public static void process() {
try {
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements())
{
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)//如果埠類型是串口則判斷名稱
{
if(portId.getName().equals("COM1")){//如果是COM1埠則退出循環
break;
}else{
portId=null;
}
}
}
SerialPort serialPort = (SerialPort)portId.open("Serial_Communication", 1000);//打開串口的超時時間為1000ms
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);//設置串口速率為9600,數據位8位,停止位1們,奇偶校驗無
InputStream in = serialPort.getInputStream();//得到輸入流
OutputStream out = serialPort.getOutputStream();//得到輸出流
//進行輸入輸出操作
//操作結束後
in.close();
out.close();
serialPort.close();//關閉串口
} catch (PortInUseException e) {
e.printStackTrace();
} catch ( e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}