java 串口通信demo_Java 串口通信

/** To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.*/

packagetina;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.io.PrintWriter;importjava.util.TooManyListenersException;importjava.util.logging.Level;importjava.util.logging.Logger;importjavax.comm.CommPortIdentifier;importjavax.comm.NoSuchPortException;importjavax.comm.PortInUseException;importjavax.comm.SerialPort;importjavax.comm.SerialPortEvent;importjavax.comm.SerialPortEventListener;importjavax.comm.UnsupportedCommOperationException;importjavax.swing.JOptionPane;/***

*@authorTina*/

public class DemoCom implementsSerialPortEventListener {private static final String PORT_NAME = "COM4"; //串口号

private static final int PORT_BAUDRATE = 115200; //波特率

private staticDemoCom instance;private finalSerialPort mSerialPort;private finalPrintWriter mWriter;private finalInputStream mInputStream;privateOnMsgArrivedListener mListener;private final StringBuffer buffer = newStringBuffer();public interfaceOnMsgArrivedListener {//收到字符

void OnMsgArrived(charc);

}private DemoCom(CommPortIdentifier portId, int baudrate) throwsPortInUseException, UnsupportedCommOperationException, IOException {

mSerialPort= (SerialPort) portId.open("DemoCom", baudrate);

mSerialPort.setSerialPortParams(baudrate,

SerialPort.DATABITS_8,//Data Bits

SerialPort.STOPBITS_1, //Stop Bits

SerialPort.PARITY_NONE); //无校验

mSerialPort.notifyOnDataAvailable(true);

OutputStream mOutputStream=mSerialPort.getOutputStream();

mInputStream=mSerialPort.getInputStream();

mWriter= newPrintWriter(mOutputStream);

}public staticDemoCom getInstance() {if (instance == null) {

CommPortIdentifier portId;try{

portId=(CommPortIdentifier) CommPortIdentifier.getPortIdentifier(PORT_NAME);

instance= newDemoCom(portId, PORT_BAUDRATE);

}catch(NoSuchPortException ex) {

JOptionPane.showMessageDialog(null, "没有找到串口" + PORT_NAME + ",请确认USB线是否连接好!");

System.exit(0);

}catch(PortInUseException ex) {

JOptionPane.showMessageDialog(null, "串口" + PORT_NAME + "被占用,请关闭其他可能占用的应用软件!");

System.exit(0);

}catch(UnsupportedCommOperationException ex) {

JOptionPane.showMessageDialog(null, "串口" + PORT_NAME + "打开失败:" +ex.getMessage());

System.exit(0);

}catch(IOException ex) {

JOptionPane.showMessageDialog(null, "串口" + PORT_NAME + "打开失败:" +ex.getMessage());

System.exit(0);

}

}returninstance;

}

@Overridepublic voidserialEvent(SerialPortEvent spe) {if (spe.getEventType() ==SerialPortEvent.DATA_AVAILABLE) {try{while (mInputStream.available() > 0) {//处理数据

int c =mInputStream.read();

buffer.append((char) c);//这里只是将数据传到其他需要监听串口数据的地方

if (mListener != null) {

mListener.OnMsgArrived((char) c);

}

}

}catch(IOException ex) {

Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE, null, ex);

}

}

}public String sendAndGet(String command, intdelayMs) {//发送命令

if (mWriter != null) {

mWriter.println(command);

mWriter.flush();

}//延时

try{

Thread.sleep(delayMs);

}catch(InterruptedException ex) {

Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE,null, ex);

}//查看回复的数据

if (!buffer.toString().isEmpty()) { //如果buffer非空

String str =buffer.toString();

System.out.println(buffer.toString());

buffer.delete(0, buffer.length());//读完之后清空

returnstr;

}else{return "";

}

}public voidsend(String command) {

buffer.delete(0, buffer.length());//发送之前清空

try{

Thread.sleep(10);

}catch(InterruptedException ex) {

Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE, null, ex);

}//发送命令

if (mWriter != null) {

mWriter.println(command);

mWriter.flush();

}

}public voidopen() {try{

mSerialPort.addEventListener(this);

}catch(TooManyListenersException ex) {

Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE,null, ex);

}//打开串口后,做一些处理

if (!sendAndGet("reset", 1000).toLowerCase().contains("ok")) {

JOptionPane.showMessageDialog(null, "无法复位!");

System.exit(0);

}

}public voidclose() {if (mWriter != null) {

mWriter.close();

}if (mInputStream != null) {try{

mInputStream.close();

}catch(IOException ex) {

Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE, null, ex);

}

}if (mSerialPort != null) {

mSerialPort.close();

}

}public voidsetOnMsgArrivedListener(OnMsgArrivedListener listener) {

mListener=listener;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值