COM 端口似乎一直很忙

COM port seems busy all the time

我在使用 Processing3 时遇到问题,当我尝试连接到某个 COM 端口时,应用程序崩溃,出现端口繁忙错误。

这是代码片段:

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 不会产生此类错误。

这似乎是错误的:

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 端口,然后发送一个值。请注意,此代码是 "once and done" 并且不会重复,类似于将其全部放入 setup() 函数中会发生的情况。

在尝试进行更复杂的操作之前,先尝试像这样简单的操作。如果你卡住了,那么 post 一个 MCVE 而不是一堆不连贯的片段。祝你好运。

您不应将 myPort 替换为空端口,而应关闭 myPort 并通过执行 myPort.stop() 释放 COM 端口以进行重复连接。