使用java将ASCII写入串行端口

时间:2015-07-02 10:37:59

标签: java serialization

我正在尝试将ASCII代码1写入串口。但现在,我遇到了将其写入串口的问题。我能否知道将ASCII写入串口的方法。

这是我的java代码:

 String number = "1";
 byte arduinoo[] = number.getBytes();
 for(int i=0; i<arduinoo.length; i++){
     outputStream.write(arduinoo[i]);
     System.out.println(arduinoo[i]);
     outputStream.flush();
 }

任何人都可以帮我解决这个问题

1 个答案:

答案 0 :(得分:0)

我认为您正在尝试将字节值0x1发送到arduinoo ...

但是只是尝试发送字符串不会那么容易...因为如果你从字符串中得到字节,你(通常)会得到“ASCII代码”#39;存储在byte []

中的每个字符
    String strA = "1";
    byte[] dataA = strA.getBytes();

    for (int i = 0; i < dataA.length; i ++){
        int asInt = dataA[i];
        System.out.println("it's not what was expected..."+asInt);
    }

    String strB = "1";
    byte[] dataB = new byte[]{(byte)Integer.parseInt(strB)}; //parsing the String literal into an Integer

    for (int i = 0; i < dataB.length; i ++){
        int asInt = dataB[i];
        System.out.println("this is what was expected..."+asInt);
    }

导致不受欢迎/想要的结果:

it's not what was expected...49
this is what was expected...1

所以每当你想发送字节exploixit然后直接创建它们!

byte[] data = new byte[]{1,2,3};