How:Java实现RS232串口通信

时间:2021-06-01 22:21:16

先来看一幅图:

How:Java实现RS232串口通信

说明:1.图中只是指出了其核心部分,要实现自己特定的软件功能可在此基础上扩展

            2.理解包中各个类:

              An application first uses methods in CommPortIdentifier to negotiate with the driver to discover which communication ports are available and then select a port for opening. It then uses methods in other classes like CommPortParallelPort and SerialPort to communicate through the port.

实例:

    1.获取所有可用串口并添加到列表框(其中portList为列表框)

Enumeration comIdentifiersEn=CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier portId=null;
while(comIdentifiersEn.hasMoreElements())
{
portId=(CommPortIdentifier) comIdentifiersEn.nextElement();
if(portId.getPortType()==CommPortIdentifier.PORT_SERIAL)
portList.addItem(portId.getName());
}

    2.打开端口(含各种初始化工作)

   try {
sPort=(SerialPort) com.open(ownerName, 60);
} catch (PortInUseException e) {
// TODO Auto-generated catch block
System.out.println("端口已被占用!");
e.printStackTrace();
}
//sPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
setPortParameters(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
try {
inputStream=sPort.getInputStream();
outputStream=sPort.getOutputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
sPort.addEventListener(this);
} catch (TooManyListenersException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sPort.notifyOnDataAvailable(true);
try {
sPort.enableReceiveTimeout(2000);
} catch (UnsupportedCommOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    3.写数据

outputStream.write((int)stringToWrite.charAt(i));
  4.读数据
switch(serialEvent.getEventType()){case SerialPortEvent.DATA_AVAILABLE:char tmpReceivedChar;try {//System.out.print((char)inputStream.read());//messageAreaIn.append(""+(char)inputStream.read());while((tmpReceivedChar=(char)inputStream.read())!=(char)-1) //保证将数据读完{while(tmpReceivedChar!='\n'){tmpReceivedString+=tmpReceivedChar;tmpReceivedChar=(char) inputStream.read();}if(!isFile){if(tmpReceivedString.equals(START_FILE)){isFile=true;isFileName=true;tmpReceivedString="";}else if(tmpReceivedString.equals(END_FILE)){//messageAreaIn.append("");tmpReceivedString="";}else{messageAreaIn.append(dateManager.getFormattedTime()+" receive:\n    "+tmpReceivedString+"\n");messageAreaIn.setCaretPosition(messageAreaIn.getText().length());//使文本自动移到最后tmpReceivedString="";}}else{if(isFileName)  //若是文件那么将接下来的第一个字符串作为文件名创建文件类,并连接到PrintWriter{File folderCreater=new File("./received");folderCreater.mkdir();File fileReceived=new File("./received/"+tmpReceivedString);tmpReceivedString="";//判断该文件名是否已经存在??outputStreamToFile=new PrintWriter(new FileOutputStream(fileReceived));isFileName=false;isLength=true;System.out.println("alreay creat the file !");}else if(isLength){lengthOfReceivedFile=Integer.parseInt(tmpReceivedString);tmpReceivedString="";if(!isReceivingBarStart){System.out.println("before receivingBar start");ReceivingBarThread receivingBar=new ReceivingBarThread();receivingBar.start();System.out.println("receivingBar started !");isReceivingBarStart=true;}System.out.println("Got length is "+lengthOfReceivedFile);isLength=false;isFirstLine=true;}else if(tmpReceivedString.equals(END_FILE)){outputStreamToFile.close();isFile=false;tmpReceivedString="";alreadyReceivedLength=lengthOfReceivedFile;System.out.println("File sending is over !");}else{if(isFirstLine){outputStreamToFile.print(tmpReceivedString);alreadyReceivedLength+=tmpReceivedString.length()+2;isFirstLine=false;}else{outputStreamToFile.println();outputStreamToFile.print(tmpReceivedString);alreadyReceivedLength+=tmpReceivedString.length()+2;System.out.println("alreadyReceivedLength is "+alreadyReceivedLength);}tmpReceivedString="";System.out.println("receiving the file");}}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}