java comm形式的串口通讯介绍及简单示例

来源:互联网 发布:腾讯软件中心 mac 编辑:程序博客网 时间:2024/04/29 02:43

java comm形式的串口通讯介绍及简单示例

一、下载:

         javacomm 官网:http://mdubuc.freeshell.org/Jolt

         javacomm下载地址:http://mdubuc.freeshell.org/Jolt/javacomm20-win32.zip

二、配置:

         将javacomm20-win32.zip下载的文件解压缩后,在\javacomm20-win32\commapi目录下有必需的三个文件:comm.jar,javax.comm.properties和win32comm.dll。%JAVA_HOME%表示jdk的安装根目录

1 将文件comm.jar拷贝到%JAVA_HOME%\jre\lib\ext;

2文件 javax.comm.properties拷贝到%JAVA_HOME%\jre\lib;

3文件win32comm.dll拷贝到%JAVA_HOME%\jre\bin。

(注意:原参考地址博文中是:%JAVA_HOME% \bin,我上官网查阅是:%JAVA_HOME%\ jre\bin,不过因为电脑是64位没有测试成功,不确认是否有影响,这里就将以官网上的为主)

三、简单示例代码:

package com.garfield.comm;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import javax.comm.CommPortIdentifier;import javax.comm.SerialPort;public class SimpleCommIO implements Runnable {    static CommPortIdentifier portId;    static String cmdHand = "I\r\n";    static String cmdWeight = "WX\r\n";    static SerialPort serialPort;    static OutputStream outputStream;    static String comm="COM11";    InputStream inputStream;    Thread readThread;    public void run() {        while (true) {            try {                byte[] readBuffer = new byte[200];                try {                    while (inputStream.available() > 0) {                        int numBytes = inputStream.read(readBuffer);                        System.out.print("收到数据:"+new String(readBuffer));                    }                } catch (IOException e) {                    e.printStackTrace();                }                Thread.sleep(2000);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    public void initComm() {        try{            portId = CommPortIdentifier.getPortIdentifier(comm);            serialPort = (SerialPort) portId.open("SimpleCommIO",2000);            outputStream = serialPort.getOutputStream();            inputStream = serialPort.getInputStream();            serialPort.setSerialPortParams(9600,                    SerialPort.DATABITS_8,                     SerialPort.STOPBITS_1,                    SerialPort.PARITY_NONE);        }catch(Exception e){            e.printStackTrace();        }    }    public void writeComm(String cmd) {        try {            outputStream.write(cmd.getBytes());        } catch (IOException e) {            e.printStackTrace();        }    }    public static void main(String[] args) {        SimpleCommIO reader = new SimpleCommIO();        reader.initComm();        Thread readThread = new Thread(reader);        readThread.start();        System.out.println("发出指令:"+cmdHand);        reader.writeComm(cmdHand);   }

备注:我电脑是64位的系统,报错:Can't load IA 32-bit .dll on a AMD 64-bit platform由于java comm太久远,并没有找到64位的,然后就换成了Rxtx进行java与串口的通讯了

参考地址: http://www.cnblogs.com/GarfieldTom/p/3675485.html



0 0
原创粉丝点击