62,614
社区成员
发帖
与我相关
我的任务
分享
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 WritePortData(String str){
try{
outputStream = serialPort.getOutputStream();
outputStream.write(str.getBytes());
}catch(Exception ee){
JOptionPane.showMessageDialog(this,ee.toString(),"Message",JOptionPane.INFORMATION_MESSAGE);
}
}
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);
}
// JOptionPane.showMessageDialog(this, new String(readBuffer),"当前接收字符",JOptionPane.ERROR_MESSAGE);
/*模拟在屏上显示,内容从单片机中接收*/
this.dp.tme1.stop();
this.dp.tme2.stop();
String comStr = new String(readBuffer).trim(); //主要是这里它会分两次显示....比如说我接到到123456789 先显示1 在显示2345678...问题出在哪里
System.out.println(comStr.length());
if(comStr.length()>15){
this.dp.tme1.start();
}
this.f.str=comStr;
this.f.strcopy = comStr;
this.f.stri = "";
this.f.stricopyi = "";
f.repaint();
}catch(Exception e){
}
break;
}
}