通过javascript将十六进制字符串发送到串行

通过javascript将十六进制字符串发送到串行,javascript,serial-port,hex,Javascript,Serial Port,Hex,我正在尝试使用Web串行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); }

我正在尝试使用Web串行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 );
现在,这在页面上加载的脚本中不起作用,该页面显示
serialDevices[1]。write(用额外的数据编写\u hex\u命令)
但是如果我复制这个确切的命令并从控制台复制十六进制输出字符串,那么控制台会说:

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');

它起作用了!那么,我如何协调这一点呢?在我看来,我正在向“串行写入”命令发送正确的字符串,但是串行计算机没有响应,除非我明确地将其拼写出来,并且不将其作为变量值发送。

答案以
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 ));
函数ascii_到_hexa(str){
var arr1=[];
对于(var n=0,l=str.length;n
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 ));