java 串口编程 (windows)

因为是windows下开发,去下载http://mdubuc.freeshell.org/Jolt/javacomm20-win32.zip(完整的2.0版本,还有examples)。

 将下载的文件解压缩后,在\javacomm20-win32\commapi目录下有必需的三个文件comm.jar,javax.comm. properties和win32comm.dll。
 
    将文件comm.jar拷贝到%JAVA_HOME%\jre\lib\ext;
    文件 javax.comm. properties拷贝到%JAVA_HOME%\jre\lib; 
    文件win32comm.dll拷贝到%JAVA_HOME%\bin。
 
 
代码:
 
import java.io.*;
import java.util.*;

import javax.comm.*;

public class IP1725_reg_read {

    CommPortIdentifier portId;
    SerialPort serialPort;
    OutputStream outputStream;
    InputStream inputStream;

    public void open_port(String port) {
        try {
            portId = CommPortIdentifier.getPortIdentifier(port);
            serialPort = (SerialPort) portId.open("IP1725_reg_readApp", 2000);
            outputStream = serialPort.getOutputStream();
            inputStream = serialPort.getInputStream();
            serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        } catch (NoSuchPortException | PortInUseException | IOException
                | UnsupportedCommOperationException e) {
            e.printStackTrace();
        }
    }

    public void do_get_reg() {
        open_port("COM15");
        FileWriter fw = null;
        String s;
        byte[] readBuffer = new byte[4];
        byte[] buf = new byte[2];
        int i;
        try {
            fw = new FileWriter("ip1725reg.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (i = 0; i < 256; i++) {
            try {
                buf[0] = (byte) 0xdd;
                buf[1] = (byte) i;
                outputStream.write(buf, 0, 2);
                outputStream.flush();
                s = String.format("%02x:", buf[1]);
                System.out.print(s);
                fw.write(s);
            } catch (IOException e) {
                System.out.println("." + e);
            }
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
            }
            try {
                inputStream.read(readBuffer);
                s = String.format("%02x", readBuffer[0])
                        + String.format("%02x", readBuffer[1]) + "\r\n";
                System.out.print(s);
                fw.write(s);
            } catch (IOException e) {
                System.out.print(".");
            }
        }
        try {
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new IP1725_reg_read().do_get_reg();
    }
}

 

posted on 2015-01-09 08:09  lion382  阅读(1162)  评论(0编辑  收藏  举报