62,615
社区成员
发帖
与我相关
我的任务
分享
发送数据
public void WritePortData(byte [] aa){
try{
outputStream = serialPort.getOutputStream();
outputStream.write(aa);
outputStream.flush();
}catch(Exception ee){
return ;
}
}
public void connectPort() {
if (this.serialPort != null) {
this.serialPort.close();
}
try {
portId = CommPortIdentifier.getPortIdentifier(this.portName);
serialPort = (SerialPort) portId.open("ReadComm", 2000);
this.p3f2.setText(this.portName + " Success\n");
} catch (Exception ee) {
JOptionPane.showMessageDialog(this, ee.toString(), "Message",
JOptionPane.INFORMATION_MESSAGE);
this.p3f2.setText(this.portName + " failure\n");
}
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
} catch (Exception ee) {
JOptionPane.showMessageDialog(this,
"Please connect serial port first!", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
try {
this.inputStream = serialPort.getInputStream();
this.serialPort.addEventListener(this);
} catch (Exception ee) {}
serialPort.notifyOnDataAvailable(true);
}
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[21];
try{
while(inputStream.available()>0){
int numBytes=inputStream.read(readBuffer);
}
String comStr = new String(readBuffer).trim();
}
} catch (Exception e) { }
break;
}
}