【问题标题】:send hex string to serial through javascript通过javascript将十六进制字符串发送到串行
【发布时间】:2021-01-28 07:20:46
【问题描述】:

我正在尝试使用 Web Serial Api 和 javascript 将十六进制字符串发送到串行端口。

function ascii_to_hexa(str) {
    var arr1 = [];
    for (var n = 0, l = str.length; n < l; n++) {
        var hex = Number(str.charCodeAt(n)).toString(16);
        arr1.push("\\x" + hex);
    }
    return arr1.join("");
}

    
       for (const [key, value] of Object.entries(master_array)) {       
                converted_hex += ascii_to_hexa(value) + "\\x0d";
        }

        compose_hex_command_with_extra_data = "\\x01\\x44\\x52\\x54\\x02" + converted_hex + "\\x04";
        console.log(compose_hex_command_with_extra_data );

        serialDevices[1].write(compose_hex_command_with_extra_data );

每个单独的命令后都需要有一个回车符。这就是为什么我在ascii_to_hexa 函数的每次迭代之后添加一个“x0d”。当我控制台记录读出时,它是正确的。这是打印到控制台的compose_hex_command_with_extra_data 示例:

\x01\x44\x52\x54\x02\x52\x53\x2b\x30\x32\x2e\x30\x30\x0d\x52\x43\x2d\x30\x2e\x35\x30\x0d\x52\x41\x30\x34\x35\x0d\x2b\x30\x2e\x37\x35\x0d\x2b\x31\x2e\x30\x30\x0d\x2d\x31\x2e\x30\x30\x0d\x30\x32\x31\x0d\x2b\x30\x2e\x37\x35\x0d\x04

现在,这在显示serialDevices[1].write(compose_hex_command_with_extra_data ); 的页面上加载的脚本中不起作用 但是如果我复制这个确切的命令并从控制台复制十六进制输出的字符串,以便控制台说:

serialDevices[1].write('\x01\x44\x52\x54\x02\x52\x53\x2b\x30\x32\x2e\x30\x30\x0d\x52\x43\x2d\x30\x2e\x35\x30\x0d\x52\x41\x30\x34\x35\x0d\x2b\x30\x2e\x37\x35\x0d\x2b\x31\x2e\x30\x30\x0d\x2d\x31\x2e\x30\x30\x0d\x30\x32\x31\x0d\x2b\x30\x2e\x37\x35\x0d\x04');

有效!那么我该如何调和呢?在我看来,我正在向“串行写入”命令发送正确的字符串,但串行机器没有响应,除非我明确拼写出来并且不将其作为变量值发送。

【问题讨论】:

    标签: javascript serial-port hex


    【解决方案1】:

    答案以decodeURIComponent() 的形式出现。只需将 "\\x" 实例替换为 "%" 并将组合的十六进制字符串包装在 decodeURIComponent 函数中即可!

    function ascii_to_hexa(str) {
        var arr1 = [];
        for (var n = 0, l = str.length; n < l; n++) {
            var hex = Number(str.charCodeAt(n)).toString(16);
            arr1.push("%" + hex);
        }
        return arr1.join("");
    }
    
        
           for (const [key, value] of Object.entries(master_array)) {       
                    converted_hex += ascii_to_hexa(value) + "%0d";
            }
    
            compose_hex_command_with_extra_data = "%01%44%52%54%02" + converted_hex + "%04";
           
    
            serialDevices[1].write(decodeURIComponent(compose_hex_command_with_extra_data ));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-19
      • 2014-03-07
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多