简体   繁体   English

Arduino / C:将字节数组转换为字符串或其他类似的文本格式

[英]Arduino / C: Convert byte array to string or other comparable text format

I am using some third party libraries for some third party hardware. 我正在将一些第三方库用于某些第三方硬件。 The libraries communicate with the hardware over a serial connection. 这些库通过串行连接与硬件通信。 Using the libraries I send data over the serial interface to the hardware and get a response, which is stored in an array: 使用库,我通过串行接口将数据发送到硬件,并获得响应,该响应存储在数组中:

// 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 

How can I convert a byte array into a format that I can evalute in code so I can perform an operation like the following pseudo code; 我如何将字节数组转换为可以用代码求值的格式,以便可以执行以下伪代码之类的操作;

byte comm_buf[201];

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

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

Do I need to convert it to a string some how, or compare to another char array perhaps? 我是否需要将其转换为字符串,或者与另一个char数组进行比较?

Here are all functions in string.h for string/memory comparison that you could use with arduino. 这是 string.h 所有可用于arduino的字符串/内存比较的函数。 You could use strcmp or memcmp . 您可以使用strcmpmemcmp

Beware you can't compare in C two strings by simply using == operator. 注意,仅使用==运算符就无法在C中比较两个字符串。 You would just compare values of two memory pointers. 您只需要比较两个内存指针的值即可。

Here is an example of comparison inside your buffer: 这是缓冲区内部比较的示例:

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

You can use strcmp if your recieved message is null byte terminated, if not you will have to use memcmp for the job. 如果收到的消息以空字节终止,则可以使用strcmp;否则,必须使用memcmp进行作业。

For both functions You have to check if return value is zero, then those strings are equal. 对于这两个函数,您必须检查返回值是否为零,然后这些字符串相等。

If you want to compare not from first byte of buffer (with zero index) but for example fifth (index 4) you can just add 4 to your pointer: 如果您不想比较缓冲区的第一个字节(索引为零),而不是第五个索引(索引为4),则可以将指针添加4:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM