0

我目前正在做一个练习,通过 Arduino 将电位器数据发送到网页中。我宁愿通过 Web Serial API 而不是节点服务器或类似的东西来做到这一点。我的 Arduino 代码是

void setup() {
  Serial.begin(9600);

}

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

这表明串行监视器中的值没有问题。

javascript代码是这样的(在脚本中,嵌入在html中):

    var b = document.getElementById('button');
    b.addEventListener('click', async () => {
     // Prompt user to select any serial port.
    const port = await navigator.serial.requestPort();
    await port.open({ baudRate: 9600 });
    console.log('working');
    while (port.readable) {
         const reader = port.readable.getReader();
    try {
        while (true) {
    const { value, done } = await reader.read();
    console.log({ value });
    if (done) {
    break;
        }
        }
     } catch (error) {
        console.log('error');
     } finally {
       reader.releaseLock();
      }
    }
    });

这意味着我有一个按钮,可以让我连接到 Arduino 所在的 USB,它正在传递信息流,但它并不是真的可用

{value: Uint8Array(4)}
value: Uint8Array(4) [13, 10, 55, 57, buffer: ArrayBuffer(4), byteLength: 4, byteOffset: 0, length: 4]
[[Prototype]]: Object

因为它不是电位器位置的值。我认为需要一些映射,但我看不到如何。此外,由于 Web Serial API,这目前仅适用于 Google Chrome。

关于如何正确接收电位器数据的任何想法?

谢谢干杯

4

1 回答 1

1

您可能需要对 Uint8Array 进行另一种解释。

例如,如果您期望 aFloat32或 a Uint32,则需要显式使用这些缓冲区视图(或解释)。

这是 javascript 中所有可用缓冲区视图的列表

例如,如果您期望一个数字:

const yourUint8Array = new Uint8Array([13, 10, 55, 57]);

console.log(yourUint8Array); // this is your 'value'

//Interpret the underlying buffer as a Uint32Array
const uint32Array = new Uint32Array(yourUint8Array.buffer); 

// uint32Array[0] would be your uint32 reinterpreted value
console.log(uint32Array); 

//Interpret the underlying buffer as a Float32Array
const float32Array = new Float32Array(yourUint8Array.buffer); 

// float32Array[0] would be your float32 reinterpreted value
console.log(float32Array); 

如果您期望一些文本:

var enc = new TextDecoder("utf-8");

//Interpret the underlying buffer as a UTF-8 string 
console.log(enc.decode(yourUint8Array.buffer));

控制台输出:

// Uint8Array {0: 13, 1: 10, 2: 55, 3: 57}
// Uint32Array {0: 959908365}
// Float32Array {0: 0.00017455984198022634}
// 79 // <-- output from text decoder
于 2021-11-27T14:20:07.287 回答