提问人:Ruo Mungai 提问时间:11/15/2023 最后编辑:engineersmnkyRuo Mungai 更新时间:11/16/2023 访问量:28
如何从串口读取完整数据 [已关闭]
How to read the full data from serial port [closed]
问:
我正在尝试从体重秤上获取重量读数。我能够使用网络串行 api 读取重量。 代码如下:
import React, { useState, useEffect } from 'react';
export default function Myscale() {
let [info, setInfo] = useState(null);
const [value, setValue] = useState('')
let start = async () => {
if ('serial' in navigator) {
// Prompt user to select an Arduino Uno device.
const port = await navigator.serial.requestPort();
const { usbProductId, usbVendorId } = port.getInfo();
port && setInfo(port.getInfo());
await port.open({ baudRate: 9600 });
const reader = port.readable.getReader();
// Listen to data coming from the serial device.
while (true) {
const { value, done } = await reader.read();
if (done) {
// Allow the serial port to be closed later.
reader.releaseLock();
break;
}
// value is a string.
function arrayBufferToString(buffer) {
return String.fromCharCode.apply(null, new Uint16Array(buffer));
}
const weight= arrayBufferToString(value)
//console.log(weight)
setValue(weight)
}
return (
<div>
<h1 style={{ textDecoration: 'underline' }}>Web Serial Info</h1>
<p>
{info ? (
<code>{JSON.stringify(info, null, '\t')}</code>
) : (
'Device not selected'
)}
</p>
<button
onClick={(e) => {
start();
}}
>
Start
</button>
{valu}
</div>
);
}
我能够得到重量,但它没有稳定下来。它发送数据的速度太快了。 如何减慢流数据的速度,以便我可以在表单中使用它来将数据发送到后端
答: 暂无答案
评论