【问题标题】:Packing/unpacking multiple ints from Processing to Arduino via Serial library通过串行库将多个整数从 Processing 打包/解包到 Arduino
【发布时间】:2012-03-21 19:36:15
【问题描述】:

我已成功将单个 int 值从 Processing 发送到 Arduino,但现在我需要一起发送一对整数(值都在 0 到 90 之间),我不知道该怎么做。

阅读文档,我知道我可以发送byte/byte[]/int/char/String 类型。 一种想法是发送包含由逗号字符连接的两个整数的字符串, 但我不是 100% 确定如何将数据转换为字符串并在 Arduino 中拆分。

serial.write(intValue1+","+intValue2);

我在想的另一件事是以某种方式将两个整数打包到 byte[] 中,但我没有太多使用字节,所以任何入门提示都会有所帮助。

【问题讨论】:

  • 听起来你应该尝试以上所有方法以获得更多经验。有点像Arduino,不是吗?在你的 sn-p 中使用 int.ToString() 方法,虽然我不认识这种语言。

标签: serial-port int bytearray processing arduino


【解决方案1】:

如果您要发送整数对或任意数量的字节,您可能需要考虑使用简单的串行协议。这里有几个问题专门针对嵌入式系统的串行命令协议,例如:

  1. How do you design a serial command protocol for an embedded system?
  2. Simple serial point-to-point communication protocol

一个建议是使用标题字节开始您的消息,如果可能的话,通常在您的数据范围之外(在您的情况下>90?)。以下代码未经测试;这只是一个想法,但它应该运行。

int lookingForHeader = 1;
int lookingForByteOne = 0;
int lookingForByteTwo = 0;

while (myPort.available() > 0) {
    while (lookingForHeader == 1) {
        int header = myPort.read();
        if (header == HEADER_BYTE) {
            lookingForHeader = 0;
            lookingForByteOne = 1;
        }
        // Consider incrementing a counter here and timing out if it gets too large.
    }

    if (lookingForByteOne == 1) {
        int byteOne = myPort.read();
        // Check if byteOne is between 0 and 90.
        lookingForByteOne = 0;
        lookingForByteTwo = 1;
    }

    if (lookingForByteTwo == 1) {
        int byteTwo = myPort.read();
        // Check if byteTwo is between 0 and 90.
        lookingforByteTwo = 0;
        lookingForHeader = 1;

        // Perhaps do a serial.write() here to acknowledge that 
        // a header and two bytes have been received.

        // Finally, do stuff with byteOne and byteTwo.
    }
}

另一种选择是确认每个字节的接收(即接收标头,以特殊的“ack header”字节响应,接收下一个字节,以“ack byte one”响应等)。这速度较慢,但​​对您来说可能没问题。

最后,我在上面链接的问题中有几个关键点:

考虑在消息末尾发送校验和(即字节总和)。 Arduino 会将标头、字节 1 和字节 2 相加。如果它与校验和不匹配,则它可能会以失败响应,或再次发送消息。

Rex 对问题 [2] 的回答总结了消息协议的外观:

// total packet length minus flags len+4
U8 sflag;         //0x7e start of packet end of packet flag from HDLC
U8 cmd;           //tells the other side what to do.
U8 len;           // payload length
U8 payload[len];  // could be zero len
U16 crc;
U8 eflag;         //end of frame flag

【讨论】:

  • 这是丰富的数据。我对消息协议不太了解,所以这很方便,谢谢!
  • 希望对您有所帮助。代码示例将用于处理端。您需要在 Arduino 中使用类似的握手代码。最好的办法是写下协议(在纸上),然后在每一方实施。你甚至可以从小一步开始,发送一个两字节的消息——一个用于标头,一个用于数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 2014-06-04
  • 2022-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多