如何在Node js中同步使用串行端口? [英] how can i use serial port Synchronously in Node js ?
问题描述
我在节点js中使用serialport模块,并执行类似的代码,但是发生了错误.
for(i=0; i<5; i++){
a(i) ;
}
function a(i){
port = new serialport(port_name,{
baudRate:9600 ,
parser: new serialport.parsers.Readline('\n')
});
port.on('open',function(){
port.write(port_command+'\n');
data = port.read();
console.log(i + data);
port.close();
});
}
但发生错误
"UnhandledPromiseRejectionWarning:错误资源暂时不可用,无法锁定端口"
"UnhandledPromiseRejectionWarning:未处理的诺言拒绝.此错误可能是由于在没有catch块的情况下抛出了异步函数而引起的,或者是因为拒绝了未经.catch()处理的诺言.
"DeprecationWarning:已弃用未处理的承诺拒绝.将来, 未处理的承诺拒绝将终止节点. js过程 一个非零的退出代码.
我希望它们按
的顺序运行a(0)端口打开,写入,读取,关闭
a(1)端口打开,写入,读取,关闭
a(2)端口打开,写入,读取,关闭
a(3)端口打开,写入,读取,关闭
a(4)端口打开,写入,读取,关闭
我认为a(0)打开,a(1)打开,所以出错..我该如何解决这个问题?
您可以从函数中返回一个在端口关闭时解析的promise:
function ping(i){
const port = new serialport(port_name,{
baudRate:9600 ,
parser: new serialport.parsers.Readline('\n')
});
port.on('open',function(){
port.write(port_command+'\n');
data = port.read();
console.log(i + data);
port.close();
});
return new Promise(resolve => port.on("close", resolve));
}
现在您可以通过以下方式实现循环了:
(async function loop() {
for(let i = 0; i < 3; i++) {
await ping(i);
}
})();
i use serialport module in node js , and execute the code like this, but error occurred.
for(i=0; i<5; i++){
a(i) ;
}
function a(i){
port = new serialport(port_name,{
baudRate:9600 ,
parser: new serialport.parsers.Readline('\n')
});
port.on('open',function(){
port.write(port_command+'\n');
data = port.read();
console.log(i + data);
port.close();
});
}
but error is occurred ,
"UnhandledPromiseRejectionWarning: Error Resource temporarily unavailable Cannnot lock port"
"UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). "
"DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node. js process with a non-zero exit code.
I want them to run in order like
a(0) port open , write , read , close
a(1) port open , write , read , close
a(2) port open , write , read , close
a(3) port open , write , read , close
a(4) port open , write , read , close
i think a(0) open, a(1) open so error .. how can i solve this problem?
You could return a promise from the function that resolves when the port closes:
function ping(i){
const port = new serialport(port_name,{
baudRate:9600 ,
parser: new serialport.parsers.Readline('\n')
});
port.on('open',function(){
port.write(port_command+'\n');
data = port.read();
console.log(i + data);
port.close();
});
return new Promise(resolve => port.on("close", resolve));
}
Now you can achieve your loop as:
(async function loop() {
for(let i = 0; i < 3; i++) {
await ping(i);
}
})();
这篇关于如何在Node js中同步使用串行端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!