搜档网
当前位置:搜档网 › Java串口编程

Java串口编程

Java串口编程
Java串口编程

前沿,要进行串口编程必须安装sun公司的comm包和相应的dll文件,若是用eclipse编程的话,把jar和dll文件复制到你所建的项目下,然后在eclipse中选择“项目"菜单,把项目下的.jar文件作为外部jars加入。

首先介绍两个类

CommPortIdentifier------串口和并口的硬件初始化类,同时包括选择是并口还是串口,这在它的常用构造方法里很好的体现了:CommPortIdentifier.getPortIdentifier(commName),commName形式为COM1字符串时表示为串口.

SerialPort------------串口类的软件初始化类,包括输入输出流、设置参数等等。名字随看起来像是串口,但是它的意思实际上是序列话,包括串口和并口的基本设置.常用构造方法SerialPort serialPort = (SerialPort) portId.open("CommBean", 1000),第一个参数为应用程序名称,第二个为超时时间。

注意点:

一、这两个类创建的时候,第一个类CommPortIdentifier应该设置为static,不然的话,运行到第二次便会出错,原因是还在使用串口,不能创建新的串口程序了。

二、在SerialPort设置参数的时候,数据位一定要设置好,不然的话,会出现?,反过来如果出现了?在程序结果里就是你的数据位设置有误。

三、如果程序里出现了“口”方框一样的东西就是你在没有数据送来的时候读取数据,解决方法是,等待有数据时才读串口。

程序实例:

package four;

import gnu.io.*;

import java.io.*;

import java.util.*;

public class COM implements Runnable, SerialPortEventListener {

private static Thread readThread;// static,保证该线程唯一

private volatile boolean toRead = false;// volatile 保证不同线程得到的值一致

private static CommPortIdentifier portId;// 只设portId为static就可,下面的输入输出流由portId产生

private SerialPort serialPort;

private String commName = "COM2";

private int bPS = 9600;

private int dataBit = 7;//和C51通信必须设为7位,不然输出不对

private int stopBit = 1;

private int pariteyBit = 0;

private OutputStream out;

private InputStream in;

private String encoding = "gb2312";

public boolean initComm() {

boolean ok = false;

try {// 打开硬件资源,获取并口

portId = CommPortIdentifier.getPortIdentifier(commName);

} catch (NoSuchPortException e) {

System.out.println("Get portid err" + e.getMessage());

return ok;

}

try {// 打开软件资源,设置进程名称和超时时间

serialPort = (SerialPort) portId.open("CommBean", 1000);

} catch (PortInUseException e) {

System.out.println("Get serialport err " + e.getMessage());

return ok;

}

try {// 设置数据传输参数

serialPort.setSerialPortParams(bPS, dataBit, stopBit, pariteyBit); } catch (UnsupportedCommOperationException e) {

System.out.println("Set port params err " + e.getMessage()); return ok;

}

try {// 创建输入流

in = serialPort.getInputStream();

} catch (IOException e) {

System.out.println("Create instream err " + e.getMessage()); return ok;

}

try {// 创建输出流

out = serialPort.getOutputStream();

} catch (IOException e) {

System.out.println("Create outstream err " + e.getMessage()); return ok;

}

try {// 监听串口

serialPort.addEventListener(this);

} catch (TooManyListenersException e) {

System.out.println("SerialPort addEventListener err"

+ e.getMessage());

}

serialPort.notifyOnDataAvailable(true);

if (readThread == null) {

readThread = new Thread(this);// 初始化读串口线程,复制主进程readThread.start();

}

// System.out.println(commName+" init is ok");// 调试语句

ok = true;

return ok;

}

public void setName(String commname) {

commName = commname;

public void setBps(int bps) {

bPS = bps;

}

public void setDataBit(int datebit) {

dataBit = datebit;

}

public void setStopBit(int stopbit) {

stopBit = stopbit;

}

public void setParityBit(int paritybit) {

pariteyBit = paritybit;

}

public boolean hasInput(){

boolean yes=false;

if(toRead)

yes=true;

return yes;

}

//获取波特率

public int getbaud(){

return bPS;

}

public static String[] listPort() {

int i = 0;

String commList[] = new String[5];// 假定为五个串口CommPortIdentifier commPort = null;

Enumeration portList = null;

portList = CommPortIdentifier.getPortIdentifiers();

// iterate through the ports.

while (portList.hasMoreElements()) {

commPort = (CommPortIdentifier) portList.nextElement();

if (commPort.getPortType() == CommPortIdentifier.PORT_SERIAL) { commList[i] = commPort.getName();

System.out.print(commList[i] + " ");// 调试语句

i += 1;

}

System.out.println();// 调试语句

return commList;

}

public synchronized String readPort() {

byte[] buf = new byte[1];

String msg = null;

boolean go = false;

try {

go = in.available() > -1;

} catch (IOException e) {

System.out.println("Check inputstream available err "

+ e.getMessage());

return msg;

}

if (go && toRead) {

try {

in.read(buf);

} catch (IOException e) {

System.out.println("Start read port err " + e.getMessage());

return msg;

}

notifyAll();

toRead=false;//必不可少,读了后标志为false

try {// 把字节转换为字符串

msg = new String(buf, encoding);

} catch (UnsupportedEncodingException e) {

System.out.println("byte to string err " + e.getMessage());

return msg;

}

return msg;

}

return null;

}

public synchronized boolean writePort(String msg) { boolean ok = false;

try {

out.write(msg.getBytes(encoding));

out.flush();

} catch (Exception e) {

System.out.println("Write port err " + e.getMessage()); return ok;

notifyAll();

// System.out.println("Writting port");// 调试语句

ok = true;

return ok;

}

public boolean closePort() {

boolean ok = false;

if (out != null)

try {

out.flush();

} catch (IOException e) {

System.out.println("Outstream flush err " + e.getMessage());

return ok;

}

try {

in.close();

out.close();

} catch (Exception e) {

System.out.println("Close IO err " + e.getMessage());

return ok;

}

serialPort.close();

// System.out.println("Close port");// 调试语句

return ok;

}

public void serialEvent(SerialPortEvent e) {

switch (e.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:

{ // System.out.println("没数据传来");//调试语句

break;

}

case SerialPortEvent.DA TA_A V AILABLE:

// System.out.println("有数据传来");//调试语句

toRead = true;

}

}

public void run() {

while (true) {

try {// 释放CPU 1s钟,给其他线程

Thread.sleep(1000);

// System.out.println("监听串口,休息一秒钟");//调试语句} catch (InterruptedException e) {

System.out.println("Readthread sleep err " + e.getMessage()); }

}

}

public static void main(String[] args) {

COM.listPort();

COM c = new COM();

if (c.initComm())

while(true){

if(c.hasInput())

System.out.print(c.readPort());

//c.writePort("Write");

try {// 释放CPU 给读线程1/bps 的时间,以便数据准确

Thread.sleep(1/9600);

} catch (InterruptedException e) {

System.out.println("Readthread sleep err " + e.getMessage());

}

}

}

}

相关主题