我目前正在做一个练习,通过 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。
关于如何正确接收电位器数据的任何想法?
谢谢干杯