gpt4 book ai didi

javascript - Node.js 串口同步读写

转载 作者:搜寻专家 更新时间:2023-10-31 23:18:06 24 4
gpt4 key购买 nike

有没有人有任何示例代码以阻塞/同步方式使用 node.js 串行端口模块?

我想做的是向微 Controller 发送命令并等待响应,然后再发送下一个命令。

我有发送/接收工作,但数据只是随监听器一起进来

serial.on( "data", function( data) {
console.log(data);
});

有没有办法在做a之后等待返回的数据

serial.write("Send Command");

我应该设置一个全局标志还是什么?

我对 node.js 的异步编程风格还是陌生

谢谢

最佳答案

没有这样的选项,实际上也没有必要。这样做的一种方法是维护一个命令队列。像这样:

function Device (serial) {
this._serial = serial;
this._queue = queue;
this._busy = false;
this._current = null;
var device = this;
serial.on('data', function (data) {
if (!device._current) return;
device._current[1](null, data);
device.processQueue();
});
}

Device.prototype.send = function (data, callback) {
this._queue.push([data, callback]);
if (this._busy) return;
this._busy = true;
this.processQueue();
};

Device.prototype.processQueue = function () {
var next = this._queue.shift();

if (!next) {
this._busy = false;
return;
}

this._current = next;
this._serial.write(next[0]);
};

关于javascript - Node.js 串口同步读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23684802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com