串口实现
来源:互联网 发布:linux 没有service 编辑:程序博客网 时间:2024/06/04 16:57
package comm;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import javax.comm.CommPortIdentifier;import javax.comm.NoSuchPortException;import javax.comm.PortInUseException;import javax.comm.SerialPort;import javax.comm.SerialPortEvent;import javax.comm.SerialPortEventListener;import javax.comm.UnsupportedCommOperationException;public class portsent {public CommPortIdentifier portId;public SerialPort serialPort;private String portname;private OutputStream outputStream;private InputStream inputStream;public portsent(){Enumeration<?> en = CommPortIdentifier.getPortIdentifiers();while (en.hasMoreElements()) {portId = (CommPortIdentifier) en.nextElement();// 如果端口类型是串口,则打印出其端口信息if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {System.out.println(portId.getName());portname=portId.getName();}}if(portname==null)System.out.println("no port found");}public void openSerialPort() { // 获取要打开的端口try {portId = CommPortIdentifier.getPortIdentifier(portname);} catch (NoSuchPortException e) {System.out.println("抱歉,没有找到"+portname+"串行端口号!");return ;}// 打开端口try {serialPort = (SerialPort) portId.open("JavaRs232", 2000);System.out.println(portname+"串口已经打开!");} catch (PortInUseException e) {System.out.println(portname+"端口已被占用,请检查!");return ;}// 设置端口参数try {int rate = 9600;int data = 8;int stop = 1;int parity =0;serialPort.setSerialPortParams(rate,data,stop,parity);} catch (UnsupportedCommOperationException e) {System.out.println(e.getMessage());}// 打开端口的IO流管道 try { outputStream = serialPort.getOutputStream(); inputStream = serialPort.getInputStream(); } catch (IOException e) {System.out.println(e.getMessage());} serialPort.notifyOnDataAvailable(true); } public void sentmsg(String mesg){try { outputStream.write(mesg.getBytes()); outputStream.flush(); } catch (IOException e) { System.out.println(e.getMessage());} System.out.println(" 发送: "+mesg);}public void closeSerialPort() { try { if(outputStream != null) outputStream.close(); if(serialPort != null) serialPort.close(); serialPort = null; System.out.println(portname+"串口已经关闭!"); } catch (Exception e) { System.out.println(e.getMessage()); } } }
0 0
- 串口实现
- C#实现串口监听
- 虚拟串口实现
- C#实现串口通信
- 串口通信协议实现
- WinApi实现串口通信
- WIN32API函数实现串口
- mfc 实现串口通信
- API实现串口通讯
- 串口读写类实现
- S3C2440串口通讯实现
- C#实现串口通讯
- S3C2440串口通讯实现
- S3C2440串口通讯实现
- 串口通信实现
- java 实现串口通信
- JAVA实现串口通信
- Qt实现串口编程
- Vim高级用户3大技巧
- 浅谈数据结构——赫夫曼数
- Php开发ZendStudio常用快捷键大全
- <img>图像标签
- OrmLite框架 —— OrmLite 复杂条件查询
- 串口实现
- App架构(读书笔记)
- C++ Primer 第5版--练习10.18
- 测试同样需要注重安全测试
- linux笔记之消息队列
- 解决eclipse开启更新progress
- 102. Binary Tree Level Order Traversal
- 一个简单的Ajax二级联动下拉菜单
- jQuery保存cookie