java开发串口步骤

本文介绍了一个基于RXTX的跨平台串口编程实例,包括环境搭建步骤、Java代码实现及常见问题解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做过一年多的RXTX操作串口项目有现在把一些平时遇到的问题在这里写写: 
RXTX是一个开源包,主要是在COMM开源包中做扩张,以前的COMM包只能在WINDOWS下面对串口或并口做操作,扩充后的RXTX可以在LINUX和MAC下对串口和并口做操作。  现在跨平台: 
在RXTX网站下载JAR包和动态库 
http://users.frii.com/jarvi/rxtx/download.html 
下载后配置环境 
Windows 
拷贝RXTXcomm.jar 文件到 \jre\lib\ext 目录下 
拷贝rxtxSerial.dll文件到 \jre\bin目录下 
Mac OS X (x86 and ppc) (there is an Installer with the source) 
MAC下面我自己没有配置环境成功,后来找一个MAC下RXTX的安装把环境配置好的。 
http://www.jdivelog.org/how-to/mac-os-x/下载安装环境配置文件RXTX_Tiger.pkg 
Linux (only x86, x86_64, ia64 here but more in the ToyBox) 
拷贝RXTXcomm.jar 文件到 /jre/lib/ext 目录下 
拷贝librxtxSerial.so 文件到 /jre/lib/[machine type] (i386 for instance)目录下 
并将拷贝文件释放权限给所有用户 
Solaris (sparc only so far) 
拷贝RXTXcomm.jar 文件到 /jre/lib/ext 目录下 
拷贝librxtxSerial.so 文件到 /jre/lib/[machine type]目录下 
并将拷贝文件释放权限给所有用户 
环境搭建好后开始写代码实现 


Java代码  


import java.io.*;  


import java.text.SimpleDateFormat;  


import java.util.Date;  


import java.util.TooManyListenersException;  


import gnu.io.CommPortIdentifier;  


import gnu.io.NoSuchPortException;  


import gnu.io.PortInUseException;  


import gnu.io.SerialPort;  


import gnu.io.SerialPortEvent;  


import gnu.io.SerialPortEventListener;  


public class SerialComm implements SerialPortEventListener, Runnable  


{  


public final static String PORT_OWER = "MonitorApp";  


private boolean isOpen;  


private boolean isStart;  


private boolean isSave;  


private boolean isPrint;  


private Thread readThread;  


private String portName;  


private String portAddress;  


private CommPortIdentifier portId;  


private SerialPort serialPort;  


private DataInputStream inputStream;  


private OutputStream outputStream;  


private SimpleDateFormat formatter;  


// prase data with process  


private String dataProtocol;  


private Object readWriteLock = new Object();  


public SerialComm() {  


        isOpen = false;  


        isStart = false;  


        isSave = true;  


        isPrint = false;  


        formatter = new SimpleDateFormat("[yyyy-MM-dd hh:mm:ss,SSS]");  


        portName = "COM1";  


        portAddress = "LOCAL";  


        dataProtocol = "Gooseli";  


    }  


public void init(String port, String protocol) throws Exception  


    {  


        portName = port;  


        portAddress = portName;  


        dataProtocol = protocol;  


        init();  


    }  


public void init(String port, String address, String protocol) throws Exception  


    {  


        portName = port;  


        portAddress = address;  


        dataProtocol = protocol;  


        init();  


    }  


public void init() throws IOException, Exception, Exception  


    {  


if (isOpen)  


        {  


            close();  


        }  


try  


        {  


//传送串口名创建CommPortIdentifier对象服务。  


            portId = CommPortIdentifier.getPortIdentifier(portName);  


//使用portId对象服务打开串口,并获得串口对象  


            serialPort = (SerialPort) portId.open(PORT_OWER, 2000);  


//通过串口对象获得读串口流对象  


            inputStream = new DataInputStream(serialPort.getInputStream());  


//通过串口对象获得写串口流对象  


            outputStream = serialPort.getOutputStream();  


            isOpen = true;  


        } catch (NoSuchPortException ex)  


        {  


throw new Exception(ex.toString());  


        } catch (PortInUseException ex)  


        {  


throw new Exception(ex.toString());  


        }  


    }  


public void start() throws Exception  


    {  


if (!isOpen)  


        {  


throw new Exception(portName + " has not been opened.");  


        }  


try  


        {  


//创建对象线程  


            readThread = new Thread(this);  


            readThread.start();  


//设置串口数据时间有效  


            serialPort.notifyOnDataAvailable(true);  


//增加监听  


            serialPort.addEventListener(this);  


            isStart = true;  


        } catch (TooManyListenersException ex)  


        {  


throw new Exception(ex.toString());  


        }  


    }  


public void run()  


    {  


        String at = "at^hcmgr=1\r";  


        String strTemp = at + (char) Integer.parseInt("1a", 16) + "z";  


        writeComm(strTemp);  


        isPrint = true;  


    }  


public void stop()  


    {  


if (isStart)  


        {  


            serialPort.notifyOnDataAvailable(false);  


            serialPort.removeEventListener();  


            isStart = false;  


        }  


    }  


public void close()  


    {  


        stop();  


if (isOpen)  


        {  


try  


            {  


                inputStream.close();  


                outputStream.close();  


                serialPort.close();  


                isOpen = false;  


            } catch (IOException ex)  


            {  


            }  


        }  


    }  


//如果串口有数据上报则主动调用此方法  


public void serialEvent(SerialPortEvent event)  


    {  


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


break;  


case SerialPortEvent.DATA_AVAILABLE:  


            readComm();  


break;  


default:  


break;  


        }  


    }  


public void readComm()  


    {  


        StringBuffer readBuffer = new StringBuffer();  


        String scannedInput = "";  


        Date currentTime = null;  


        String TimeStamp = "";  


int c;  


char a;  


try  


        {  


            InputStreamReader fis = new InputStreamReader(inputStream, "utf-8");  


while ((c = fis.read()) != -1)  


            {  


                readBuffer.append((char) c);  


            }  


            scannedInput = readBuffer.toString().trim();  


            currentTime = new Date();  


            TimeStamp = formatter.format(currentTime);  


        } catch (IOException ex)  


        {  


            ex.printStackTrace();  


        } catch (Exception ex)  


        {  


            ex.printStackTrace();  


        }  


    }  


public void writeComm(String outString)  


    {  


synchronized (readWriteLock)  


        {  


try  


            {  


                outputStream.write(outString.getBytes());  


            } catch (IOException ex)  


            {  


            }  


        }  


    }  


public static void main(String[] args)  


    {  


        SerialComm serialcomm = new SerialComm();  


try  


        {  


            serialcomm.init("COM3", "Air");// windows下测试端口  


// serialcomm.init("/dev/ttyUSB0", "Air");//linux下测试端口  


            serialcomm.start();  


        } catch (Exception ex)  


        {  


        }  


    }  


}  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

懒人烂命

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值