【问题标题】:Arduino / C: Convert byte array to string or other comparable text formatArduino / C:将字节数组转换为字符串或其他类似的文本格式
【发布时间】:2013-08-01 18:37:52
【问题描述】:

我正在为一些第三方硬件使用一些第三方库。库通过串行连接与硬件通信。使用库,我通过串行接口向硬件发送数据并获得响应,该响应存储在数组中:

// This is the byte array declared in the third party libraries
// that stores data sent back from the external hardware
byte comm_buf[201];

/* I send data to hardware, comm_buf gets filled */

// Printing out the received data via a second serial line to which
// I have a serial monitor to see the data

for (int i = 0; i <= 50; i++) {
  Serial.print(gsm.comm_buf[i]);
}    

// This is printed via the second monitoring serial connection (without spaces)
13 10 43 67 82 69 71 58 32 48 44 51 13 10 13 10 79 75 13 10 00

// It is the decimal ascii codes for the following text
+CREG: 0,3 

如何将字节数组转换为我可以在代码中评估的格式,以便我可以执行类似以下伪代码的操作;

byte comm_buf[201];

/* I send data to hardware, comm_buf gets filled */

if (comm_buf[] == "CREG: 0,3" ) {
  // do stuff here
}

我是否需要以某种方式将其转换为字符串,或者与另一个 char 数组进行比较?

【问题讨论】:

  • 您在寻找strcmp(com_buffer, "CREG: 0,3")吗?
  • if (strcmp(gsm.comm_buf,"\r\n+CREG: 0,3\r\n\r\nOK\n")) { 给出错误invalid conversion from 'byte*' to 'const char*'
  • 是的,您可以通过谷歌搜索错误消息来解决该错误;)
  • strcmp((const char *)comm_buf, "foobar")
  • 与效率无关。在这种(最简单的)情况下,类型转换操作在代码中什么都不做——它只会愚弄编译器。原因:strcmp() 需要两个 const char * 类型的参数,但您的数组是 byte[] 类型,当传递给函数时会衰减为 byte * - 以及两个基本类型不同的指针 (const char *byte * 在你的情况下)是不兼容的类型。

标签: c arduino bytearray


【解决方案1】:

Here arestring.h 中的所有函数用于字符串/内存比较,您可以与 arduino 一起使用。您可以使用strcmpmemcmp

请注意,您不能在 C 中仅使用 == 运算符来比较两个字符串。您只需比较两个内存指针的值。

以下是缓冲区内的比较示例:

if (strcmp((const char*)gsm.comm_buf, "\r\n+CREG: 0,3\r\n\r\nOK\n")==0)
{
    Serial.print("abc");
}

如果您收到的消息是空字节终止的,您可以使用 strcmp,如果不是,您将不得不使用 memcmp 来完成这项工作。

对于这两个函数,您必须检查返回值是否为零,那么这些字符串是否相等。

如果您不想从缓冲区的第一个字节(索引为零)而是例如第五个字节(索引 4)进行比较,您可以将 4 添加到您的指针:

if (strcmp((const char*)gsm.comm_buf + 4, "\r\n+CREG: 0,3\r\n\r\nOK\n")==0)

【讨论】:

  • 很好的建议,我不知道您链接的参考和 == 问题。谢谢!
  • memcmp 需要最后一个参数 (.., .., size_t num)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-07
  • 1970-01-01
相关资源
最近更新 更多