Java串口读取十六进制值

时间:2015-12-15 14:03:03

标签: java serial-port

我想将一些十六进制数据写入串口并读回一些数据。我在阅读中遇到问题(什么都不读)可能有人帮忙???

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

public class Test {
    public static void main(String[] args) throws IOException {
        char c='s';
        ProcessBuilder builder = new ProcessBuilder("c:\\windows\\system32\\mode.com", "portname", 
            "baud=115200", "parity=n", "data=8","stop=1");
        Map<String, String> environ = builder.environment();
        String portname="com6";
        final Process process = builder.start();
        String x="";
        byte data[] = {(byte)0xF5, (byte)0xfa, (byte)0x01, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0xfe, (byte)0x0f};
        FileOutputStream fos = new FileOutputStream(portname );
        BufferedOutputStream bos = new BufferedOutputStream( fos );
        fos.flush();
        fos.write( data);
        fos.close();
        bos.close();
        FileInputStream fstream1 = new FileInputStream(portname);
        DataInputStream in = new DataInputStream(fstream1);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        int n = 0;
        while ((n =(char) in.read()) !=-1 ){
            System.out.println((char)fstream1.read());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你传入一个字符串&#34; portname&#34;而不是变量portname。请参阅以下对代码的更改:

String portname="com6"; //Move it here
ProcessBuilder builder = new ProcessBuilder("c:\\windows\\system32\\mode.com", 
             portname, //instead of "portname"
           "baud=115200", "parity=n", "data=8","stop=1");
Map<String, String> environ = builder.environment();

在更改之后,我在read()上有了系统块 - 因为我没有连接到该端口。

您从两个流中读取 - 这样就可以跳过字节。首先尝试使用最基本的流:

 try{
   FileOutputStream fos = new FileOutputStream(portname ); 
   fos.write( data);
   fos.flush();
   fos.close();

   FileInputStream    fstream1 = new FileInputStream(portname);
   int n = in.read();
   while (n != -1 ){
       System.out.println(n);
       n = in.read();
   }
   System.out.println("Reading ended");
 } catch(Exception e) {
    e.printStackTrace();
 }

至少应该回复你所写的内容。