COM端口似乎一直很忙

时间:2017-09-21 15:56:27

标签: arduino serial-port processing

我遇到了Processing3的问题,当我尝试连接到某个COM端口时,应用程序崩溃,出现Port Busy错误。

以下是代码段:

boolean found = false;
text(Arrays.toString(Serial.list()), 20, 500);
println("Still checking...");
for (String port : Serial.list()) {
  myPort = new Serial(this, port);
  myPort.clear();
  myPort.write("init\n");
  if (myPort.readStringUntil(lf) == "connected") {
    found = true;
    break;
  }
}
if (!found) {
  myPort = emptyPort;
  text("Waiting for device...", 20, 40);
}

这是draw()循环的一部分,在此示例中,错误在第5行引发。在该特定端口可用之前,其他所有端口都运行良好。

这是来自连接的arduino的setup()代码:

Serial.begin(256000);
while (!Serial.available()) {}
while (true) {
  String recv = Serial.readStringUntil('\n');
  if (recv == "init") {
    Serial.println("connected");
    break;
  } else {
    while (!Serial.available()) {}
  }
}
Serial.println("600,400");

Arduino IDE中的串行监视器测试不会产生此类错误。

2 个答案:

答案 0 :(得分:0)

这似乎不对:

for (String port : Serial.list()) {
  myPort = new Serial(this, port);

此处您正在连接每个串口。你应该只连接到一个,对吗?

另外,你说你是从draw()函数做的吗?这似乎也错了。您不希望每秒连接端口60次。您希望从setup()函数连接到一次,然后将该连接用于该程序的其余部分。

如果我是你,我会回过头看一些代码示例。

来自the reference

// Example by Tom Igoe

import processing.serial.*;

// The serial port:
Serial myPort;       

// List all the available serial ports:
printArray(Serial.list());

// Open the port you are using at the rate you want:
myPort = new Serial(this, Serial.list()[0], 9600);

// Send a capital A out the serial port:
myPort.write(65);

此示例只连接到它找到的第一个COM端口,然后发送一个值。请注意,此代码是“一次完成”并且不会重复,类似于将此全部放在setup()函数中时会发生的情况。

在尝试更复杂的事情之前,先得到像这样简单的东西。如果您遇到问题,请发布MCVE而不是一堆断开连接的代码段。祝你好运。

答案 1 :(得分:0)

您应该通过执行myPort.stop()来关闭myPort并释放COM端口以重复连接,而不是使用emptyPort替换myPort。

相关问题