【问题标题】:arduino send data in binary format(binary packets) instead of 1 and 0. sending like 00000000 and 00000001(8 bit binary)arduino 以二进制格式(二进制数据包)而不是 1 和 0 发送数据。发送 00000000 和 00000001(8 位二进制)
【发布时间】:2014-10-21 08:42:02
【问题描述】:

私人无效发送数据(字符串消息){ byte[] msgBuffer = message.getBytes();

    Log.d(TAG, "...Send data: " + message + "...");

    try {
        outStream.write(msgBuffer);

    } catch (IOException e) {
        String msg = "In onResume() and an exception occurred during write: "
                + e.getMessage();
        if (address.equals("00:00:00:00:00:00"))
            msg = msg
                    + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
        msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString()
                + " exists on server.\n\n";

        errorExit("Fatal Error", msg);
    }
}

在上面的代码中,我们可以发送像“0”和“1”这样的数据。但想发送 8 位,如 00000000 和 00000001。它应该显示在 Arduino 板上。如果按发送数据 1 应该显示 00000001 和 00000000。

【问题讨论】:

    标签: android arduino


    【解决方案1】:

    使用这个:

    String str = "25789";
        int i = Integer.parseInt(str);
        String binarystr = Integer.toBinaryString(i); 
    
        char[] buffer = new char[binarystr.length()];
        binarystr.getChars(0,binarystr.length(), buffer, 0);
    
        System.out.println("char array:: "+Arrays.toString(buffer));
    
        byte[] binaryFormat = getbyteFromString(buffer);
    
    
        for (byte b : binaryFormat) {
            System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1));
        }
    

    方法:

    private byte[] getbyteFromString(char[] binarystr){
    int length = binarystr.length/8;
    
    if(binarystr.length % 8 > 0)
        length++;
    
    int iterationCount = length ;
    
    byte[] binaryFormat = new byte[iterationCount];
    int iter = iterationCount - 1;
    
    
    for(int i = binarystr.length - 1; i >=0 ;){
    
        byte byt = 0x0;
        for(int j = 0; j < 8 ; j++){
    
            if(i < 0)
                break;
    
            int b = binarystr[i] - 48;
            byt = (byte) (byt + (b << j));
            i--;
        }
    
        binaryFormat[iter] = byt;
    
        iter--;
    }
    
    return binaryFormat;
    

    }

    【讨论】:

    • 没有上面的解决方案是给 java.lang.ArrayIndexOutOfBoundsException:
    • 答案已编辑。现在试试。您也可以使用 System.arraycopy()。而不是 for 循环复制新字节数组中的字节。
    • newMessage=[49, 0, 0, 0, 0, 0, 0, 0] 在我调试时显示第一个数组索引显示 49。但我发送为 sendData("1" ).所以,在 Arduino lcd 中什么都看不到。
    • 49 是字符 '1' 的 ascii 值。如果您想要数值减去 48。如果您的问题得到解决,请接受作为答案。
    • 无法减去,因为“msgBuffer”是字节值。
    猜你喜欢
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2011-10-14
    • 2010-10-17
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多