【问题标题】:Why does serial.available does not work in this code snippet?为什么 serial.available 在此代码段中不起作用?
【发布时间】:2020-07-05 20:52:54
【问题描述】:

我有一个处理草图,需要与 USB 设备建立 2 个连接。我无法提前知道哪个设备是 USB0,哪个是 USB1。 (至少我不知道)

其中一个带有 hello 的设备 awnsers 根本不回答。因此,我编写了带有简单超时的代码。在设置中,我不断检查是否有要读取的字节。但是 while 和 if 语句都会产生不正确的结果

while( dccCentral.available() < 5 ) {
    if( dccCentral.available() >= 5) break;
    if(millis() > 5000 ) {
        println("timeout occured");
        println(dccCentral.available());
        break;
    }
}

这些行正在设置中。始终打印文本“发生超时”。在它下面,打印 dccCentral.available() 的结果。这个数字是 12,这是正确的。

无论如何,如果 dccCentral.available() 当时打印 12。第一个 if 语句:

if( dccCentral.available() >= 5) break;

在发生超时之前应该已经从 while 循环中跳出。当接收到 5 个或更多字节时,while 循环本身也应该退出。

为什么这两行

while( dccCentral.available() < 5 ) {
    if( dccCentral.available() >= 5) break;

失败了?

【问题讨论】:

  • 我知道在 while 循环中, .available() 的结果始终为 0。但是为什么超时发生时它会显示 12 呢?为什么会这样?

标签: serial-port processing


【解决方案1】:

我个人尽量避免 while 循环,除非没有其他方法(例如在线程内),即避免逻辑陷阱和弄乱可能需要一些时间来初始化的其他对象的生命周期。

如果您从 Arduino 发送字符串并使用println(),您可以使用串行的bufferUntil() 与serialEvent() 一起使用readString() 来初始化端口以轻松捕获它。

一旦您开始获取数据,您就可以:

  1. 使用对您所使用的串行端口的引用和几个额外的端口,直到您知道哪个端口是哪个端口
  2. 使用布尔值“toggle”只处理一次“hello”
  3. 如果收到 hello,您可以使用 serialEvent() Serial 参数分配 dccCentral 并通过消除过程分配另一个端口

这是一个注释草图来说明这个想法:

import processing.serial.*;

// be sure to set this to the baud rate your device use with Arduino as well
final int BAUD_RATE = 115200;
// reference to Serial port sending "Hello" (when that get's detected)
Serial dccCentral;
// reference to the other Serial port
Serial otherDevice;
// temporary references
Serial usb0;
Serial usb1;
// 'toggle' to keep track where the hello was received and handled or not (by default initialised as false)
boolean wasHelloReceived;

void setup(){
    usb0 = initSerial("/dev/ttyUSB0", BAUD_RATE);
    usb1 = initSerial("/dev/ttyUSB1", BAUD_RATE);
}

Serial initSerial(String portName, int baudRate){
    Serial port = null;

    try{
        port = new Serial(this, portName, baudRate);
        // if sending strings and using println() from Arduino
        // you can buffer all chars until the new line ('\n') character is found
        port.bufferUntil('\n');
    }catch(Exception e){
        println("error initialising port: " + portName);
        println("double check name, cable connections and close other software using the same port");
        e.printStackTrace();
    }

    return port;
}

void draw(){
    background(0);
    text("wasHelloReceived: " + wasHelloReceived + "\n"
        +"dccCentral: " + dccCentral + "\n" 
        +"otherDevice: " + otherDevice , 10 ,15);
    // do something with the devices once they're ready (e.g. send a message every 3 seconds)
    if(millis() % 3000 == 0){
        if(dccCentral != null){
            dccCentral.write("ping\n");
        }
        if(otherDevice != null){
            otherDevice.write("pong\n");
        }
    }
}

void serialEvent(Serial port){
    try{
        String serialString = port.readString();
        // if the received string is not null, nor empty
        if(serialString != null && !serialString.isEmpty()){
            // for debugging purposes display the data received
            println("received from serial: " + serialString);
            // trim any white space
            serialString = serialString.trim();
            // check if "hello" was received
            if(serialString.equals("hello")){
                println("hello detected!");
                // if the dccCEntral (hello sending) serial port wasn't assigned yet, assign it
                // think of this as debouncing a button: setting the port once "hello" was received should happen only once
                if(!wasHelloReceived){

                    // now what dccCentral is found, assign it to the named reference
                    dccCentral = port;

                    // by process elimiation, assign the other port 
                    // (e.g. if dccCentral == usb0, then other is usb1 and vice versa)
                    otherDevice = (dccCentral == usb0 ? usb1 : usb0);
                    /*
                    the above is the same as
                    if(dccCentral == usb0){
                        otherDevice = usb1;
                    }else{
                        otherDevice = usb0;
                    }
                    */

                    wasHelloReceived = true;
                }
            }
        }
    }catch(Exception e){
        println("error processing serial data");
        e.printStackTrace();
    }
}

注意上面的代码没有经过测试,所以它可能包含语法错误,但希望能理解这一点。

我不禁注意到,USB0/USB1 是串行设备有时会出现在 Linux 上的方式。 如果您使用的是 Raspberry Pi,如果您对 Python 感到满意,我可以推荐一种稍微简单的方法。 PySerial 有一些技巧:

  1. 您可以简单地调用:python -m serial.tools.list_ports -v,它将列出带有额外信息的端口,例如串行转换器芯片组的序列号。无论使用的制造商和 USB 端口如何,这对于分辨哪个设备是哪个设备很有用
  2. 除了串口名称/位置外,它还支持多种方式(URL)访问端口,非常聪明:hwgrep:// 将允许您通过设备的唯一序列号过滤设备

这是具有相同芯片组的两台设备的基本list_ports -v 输出:

column 1

/dev/ttyUSB9        
    desc: TTL232R-3V3
    hwid: USB VID:PID=0403:6001 SER=FT94O21P LOCATION=1-2.2

column 2

/dev/ttyUSB8        
    desc: TTL232R-3V3
    hwid: USB VID:PID=0403:6001 SER=FT94MKCI LOCATION=1-2.1.4

要使用串行分配设备,您可以使用以下内容:

"hwgrep://FT94O21P"
"hwgrep://FT94MKCI"

更新

逐步调试系统并一次尝试一个端口可能会有所帮助。 这个想法是让代码读取预期的串行字符串紧密。 这是一个基本示例,应该一次简单地将一个字符累积到一个字符串中并显示它:

import processing.serial.*;

Serial port;

String fromSerial = "";

void setup(){
  size(300,300);
  port = initSerial("/dev/ttyUSB0", 115200);
}

Serial initSerial(String portName, int baudRate){
    Serial port = null;

    try{
        port = new Serial(this, portName, baudRate);
        // if sending strings and using println() from Arduino
        // you can buffer all chars until the new line ('\n') character is found
        port.bufferUntil('\n');
    }catch(Exception e){
        println("error initialising port: " + portName);
        println("double check name, cable connections and close other software using the same port");
        e.printStackTrace();
    }

    return port;
}

void draw(){
  
  if(port != null){
    if(port.available() > 0){
      char inChar = port.readChar();
      fromSerial += inChar;
      if(inChar == '\n'){
        println("newline encountered");
        println(fromSerial.split("\n"));
      }
    }
  }
  
  background(0);
  text("from serial:" + fromSerial, 10,15);
}

如果来自dccCentral 的数据符合预期:太好了,可以简化代码并应用正确的条件来过滤将来的设备, 否则它应该有助于查明通信问题首先获得“你好”(如果从 Arduino 使用Serial.println() 发送,这将是 6 个字节(“你好”(5)+ '\n'))

关于 Python,完全没有问题。如果这个想法在未来有帮助,您可以查看this answer。 (AFAIK Processing Serial 在幕后使用 JSSC)

【讨论】:

  • 谢谢。通常我从不使用 while 循环,也不使用延迟,不在 C 中处理(除了主循环)。但是在设置中,我仍然会偶尔将它们用于这些事情。另一方面,您为什么推荐“SerialEvent”?我尝试使用它一次,它给了我我见过的最原子性的错误代码。我发现在 void 循环开始时读取字节比在随机未定义的地方读取更可靠。我也不能/不会使用 python。我无法简单地重新编码我的项目,并且在更换硬件组件时设备 ID 没有用。
  • @bask185 不用担心。感谢您提供更新信息:越多越好的人将能够支持。我过去没有遇到过serialEvent 问题。如果在这种情况下解析数据时出现问题,它会在我的经验中第一次失败后自行禁用。我在上面发布了一个最小的草图来测试从 Arduino 接收字符。希望这将有助于仔细检查您是否从 Arduino 正确接收了所有内容。从理论上讲,如果简单地检查哪个设备发送数据(例如if(port.available() &gt; 0)))而不是等待完整的hello,您也许可以逃脱?
猜你喜欢
  • 2011-10-25
  • 1970-01-01
  • 2013-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多