首先,我对node.js和异步函数的概念都是新手,如果能在这里得到任何帮助,我将非常感激。我一直在尝试使用node.js串口模块编写一个脚本来扫描我的Windows机器上的端口,并在Arduino Micro连接到端口后做一些简单的事情。如果Arduino已经连接好了,下面的代码就可以工作了,但是我不知道如何扩展它,这样它就会无限期地等待,直到Micro被插入。如果什么都没有找到,它就会终止。
const serialPort = require('serialport');
var portName;
serialPort.list().then(function(ports){
ports.forEach(function(portInfo){
if (portInfo.vendorId == 2341 && portInfo.productId == 8037) {
portName = portInfo.path;
var myPort = new serialPort(portName);
myPort.on('open' , function() {
showPortOpen();
myPort.write('RL'); // command to initiate functions in Arduino code
});
myPort.on('data' , readSerialData); // echo data from Arduino
myPort.on('close', showPortClose);
}
})
});
function readSerialData(data) {
console.log(data);
}
function showPortOpen() {
console.log(portName,'opened');
}
function showPortClose() {
console.log(portName,'closed');
}发布于 2021-07-13 08:51:15
问题在双倍快的时间内解决。谢谢:-)
我不确定这是否是最干净的方法,但通过在端口关闭时重新调用setInterval函数,我有一个脚本,它会等待并在Arduino插入USB后找到它,如果随后拔出它,则在再次插入它时会再次找到它。这正是我想要的!
const serialPort = require('serialport');
var portName;
loop(); // start searching for Arduino on a port
function loop() {
loopId = setInterval(function() {
serialPort.list().then(function(ports){
ports.forEach(function(portInfo){
if (portInfo.vendorId == 2341 && portInfo.productId == 8037) {
portName = portInfo.path;
var myPort = new serialPort(portName);
myPort.on('open' , function() {
showPortOpen();
myPort.write('RL'); // command to initiate Arduino functions
});
myPort.on('data' , readSerialData); // echo data from Arduino
myPort.on('close', showPortClose);
}
})
})
}, 1000)
};
function readSerialData(data) {
console.log(data);
}
function showPortOpen() {
console.log(portName,'opened');
clearInterval(loopId); // stop looping once Arduino found on port
}
function showPortClose() {
console.log(portName,'closed');
loop(); // start over when Arduino port is closed
}https://stackoverflow.com/questions/68355092
复制相似问题