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();
    }
}

 

转载于:https://www.cnblogs.com/lion382/p/4212399.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值