【资料来源于网络,本文只是总结了一下自己学习的笔记。】
JAVA实现串口通信
一、配置JAVA下串口通信环境
1.下载Java Communication包:
下载地址如下:http://mdubuc.freeshell.org/Jolt/javacomm20-win32.zip。
2.解压缩javacomm20-win32.zip
3. 把javax.comm.properties,win32com.dll拷贝到你的jdk中,具体位置为:C:\Program Files\Java\jdk1.6.0_06\bin。然后配置windows系统环境变量,在path中加入C:\Program Files\Java\jdk1.6.0_06\bin;
4. 打开你的java工程,配置user library,并导入comm.jar包:
工具栏project->properties->Java Build Path->Libraries->addExternal JARs…->选择comm.jar包。
二、源码如下:
gui.java算是一个框架;panel.java是面板,相当于前台;SerialCommunication.java是一个JavaBean,相当于后台。面板视图如下:
//gui.java
package gui;
import java.awt.*;
importjavax.swing.*;
public class gui
{
public static voidmain(String[] args)
{
JFrameframe=new JFrame("密谈");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(newpanel());
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
}
}
//panel.java
package gui;
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
public class panelextends JPanel
{
StringSB;
JTextAreashow;
JTextFieldtext;
JButtonsubmit,connect,stop;
SerialCommunicationport;
Timertimer;
JPanelwrite;
JPanelread;
publicpanel()
{
SB=newString("");
port=newSerialCommunication(1);
timer=newTimer(100,new timeListener());
show=newJTextArea(20,25);
show.setLineWrap(true);
show.setAutoscrolls(true);
text=newJTextField("",25);
submit=newJButton("提交");
connect=newJButton("连接");
stop=newJButton("断开");
write=newJPanel();
read=newJPanel();
setLayout(newBoxLayout(this,BoxLayout.Y_AXIS));
submit.addActionListener(new submitListener());
connect.addActionListener(newconnectListener());
stop.addActionListener(newstopListener());
write.setPreferredSize(newDimension(300,70));
write.add(text);
write.add(connect);
write.add(submit);
write.add(stop);
write.setBackground(Color.CYAN);
read.setPreferredSize(newDimension(300,375));
read.setBackground(Color.yellow);
read.add(show);
add(read);
add(write);
}
private classsubmitListener implements ActionListener
{//提交按钮的监听器
public voidactionPerformed(ActionEvent event)
{
Strings=text.getText();
port.write(s);
SB=newString(port.readBuffer());
show.append(SB);
System.out.println("提交!");
}
}
private classconnectListener implementsActionListener
{//连接按钮的监听器
public voidactionPerformed(ActionEvent event)
{
port.open();
timer.start();
System.out.println("连接!");
}
}
private classstopListener implementsActionListener
{//断开按钮的监听器
public voidactionPerformed(ActionEvent event)
{
port.close();
timer.stop();
System.out.println("断开!");
}
}
private classtimeListener implementsActionListener
{//timer的监听器,用作轮询后台
public voidactionPerformed(ActionEvent event)
{
if(port.dataComes())
{
SB=newString(port.readBuffer());
port.dataHadRead();
show.append(SB);
repaint();
System.out.println("读到数据!");
}
}
}
}
//SerialCommunication.java
package gui;
importjava.util.*;
importjava.io.*;
importjavax.comm.*;
import java.awt.*;
import javax.comm.SerialPortEvent.*;
import javax.comm.SerialPortEventListener.*;
public class SerialCommunication
{
StringportName;
CommPortIdentifierportId;
InputStream inputStream;
OutputStream outputStream;
SerialPort serialPort;
StringBuffer buffer;//串口读入缓存
boolean recieve;//有新数据读入的标识
publicSerialCommunication(int n)
{//创建一个名字为"COM"+n 的串口通信对象
buffer=newStringBuffer("");
EnumerationportList=CommPortIdentifier.getPortIdentifiers();
while(portList.hasMoreElements())
{
portId =(CommPortIdentifier)portList.nextElement();
if (portId.getPortType()==CommPortIdentifier.PORT_SERIAL)
{
if(portId.getName().equals("COM"+n))
{portName="COM"+n;break;}
}
else
{System.out.println("找不到串口!");}
}
}
public voidopen()
{//打开串口以及输入输出流
recieve=false;
try
{serialPort=(SerialPort)portId.open("SerialCommunication", 2000);}
catch(PortInUseExceptione){System.out.println("端口正被占用!");}
try
{serialPort.setSerialPortParams
(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);}
catch(UnsupportedCommOperationExceptione){System.out.println("不支持通信");}
try
{
outputStream=serialPort.getOutputStream();
inputStream=serialPort.getInputStream();
}
catch(IOException e){System.out.println("无法初始化输入输出流!");}
try
{serialPort.addEventListener(newserialPortListener());}
catch (TooManyListenersException e){System.out.println("监听器太多了!");}
serialPort.notifyOnDataAvailable(true);
}
public voidwrite(String s)
{//将参数字符串s转换成字节,并将此字节流写入到outputStream中
buffer=newStringBuffer("SEND:"+s+"\n");
try
{outputStream.write(s.getBytes());}
catch(IOException e){System.out.println("往串口写入数据时发生错误!");}
}
public voidclose()
{
try
{
outputStream.close();
inputStream.close();
}
catch(IOExceptione){System.out.println("输入输出流关闭失败!");}
serialPort.close();
}
public classserialPortListener implementsSerialPortEventListener
{//监听是否有新数据读入的监听器
public voidserialEvent(serialPortListener event)
{
if(event.getEventType()==SerialPortEvent.DATA_AVAILABLE)
{//若有新数据传来,则将其转换成字符串,并加进缓存
StringreadResult;
byte[]readBuffer=new byte[20];
try
{
while(inputStream.available()>0)
inputStream.read(readBuffer);
}
catch(IOExceptione)
{
System.out.println(e);
System.out.println("从串口读取数据时发生错误!");
readResult="";
}
readResult=newString(readBuffer);
buffer=newStringBuffer("RECIEVE:"+readResult+"\n");
recieve=true;//然后置新数据读入标识为真
}
}
private intgetEventType() {
// TODOAuto-generated method stub
return 0;
}
@Override
public voidserialEvent(SerialPortEvent arg0) {
// TODOAuto-generated method stub
}
}
publicStringBuffer readBuffer()//返回缓存所存储的字符串
{System.out.println(buffer);return(buffer);}
public booleandataComes()//判断串口是否有新数据读入
{return(recieve);}
public voiddataHadRead()//此方法可以让外部的应用程序在读取一次数据后置标识为假
{recieve=false;}
}