将串行输入读入字符数组

时间:2020-10-13 12:50:56

标签: c++ arduino arduino-esp8266

所以我设法将ESP-01模块连接到我的arduino,现在我试图解析芯片通过串行连接提供的+ IPD响应。我对C ++并不是很方便,但这是我在网上进行大量研究后设法想到的:

#include <SoftwareSerial.h>
SoftwareSerial ESP8266(2, 3); // RX | TX
int baud = 9600;


void setup() {
  ESP8266.begin(baud);
  Serial.begin(baud);
  Serial.println("--- Start ---");
  
}

void loop() {

  if (ESP8266.available()) // check if the esp is sending a message
  {
    Serial.println("Something received");
    delay(500);
    if (ESP8266.find("%<"))
    {
      Serial.println("--------------- DEBUG ----------------A");
      char temp = {char(ESP8266.read())};
      while ((temp != '%') && (ESP8266.available())) {
        Serial.print(temp);
        temp = char(ESP8266.read());
      }
      Serial.println("\n--------------- END DEBUG ----------------");
    }
  }
}

芯片收到消息时给出的标准响应如下:

+IPD,<len>:<Message>
+IPD,0,14:%<255,128,0%

正在尝试发送的数据-随机RGB值(使用'%<'和'%'作为标记/标记):

%<255,128,0%

从这里,我设法编写了上面的代码,它将通过串行方式打印出以下内容:

enter image description here

因此,我设法通过串行输出了我需要的值,但是我似乎无法将它们存储在某种数组中以处理数据。

我尝试过的事情:

  • 使用readString()代替read(),结合indexOf来搜索/提取数据
  • 循环并附加到char数组
  • 一堆数组东西似乎很棘手,因为声明时必须知道其长度

理想情况下,我想要一个函数,该函数读取+ IPD值,提取RGB数据,然后将其拆分为3个索引数组,如下所示:

rgbArray = {124, 234, 96};

任何人和所有帮助都非常感谢!

2 个答案:

答案 0 :(得分:1)

要将输入存储到数组中,只需分配一个数组并将数据存储在其中即可。

      Serial.println("--------------- DEBUG ----------------A");
      int receivedLength = 0;
      char data[16];
      char temp = ESP8266.available();
      while ((temp != '%') && (ESP8266.available())) {
        Serial.print(temp);
        if (receivedLength < 16) data[receivedLength++] = temp;
      }
      for (int i = 0; i < receivedLength; i++) Serial.print(data[i]);
      Serial.println("\n--------------- END DEBUG ----------------");

或者,您可以在读取时转换为整数:

      Serial.println("--------------- DEBUG ----------------A");
      int rgbSize = 0;
      int rgbArray[3];
      int currentValue = 0;
      char temp = ESP8266.available();
      while ((temp != '%') && (ESP8266.available())) {
        Serial.print(temp);
        if (temp == ',') {
          if (rgbSize < 3) rgbArray[rgbSize++] = currentValue;
          currentValue = 0;
        } else {
          currentValue = currentValue * 10 + (temp - '0');
        }
      }
      if (rgbSize < 3) rgbArray[rgbSize++] = currentValue;
      for (int i = 0; i < rgbSize; i++) {
        if (i > 0) Serial.print(',');
        Serial.print(rgbArray[i]);
      }
      Serial.println("\n--------------- END DEBUG ----------------");

答案 1 :(得分:0)

最终采用了不同的处理方式:

设法阅读有关readStringUntil('');在网络的某个黑暗角落。所以我想出了一个超级肮脏的实现-但它能起作用:

假设您输入的字符串是:

+IPD,0,14:%<255,128,0%

然后做:

if (ESP8266.available()) // check if the esp is sending a message
  {

    delay(500);
    if (ESP8266.find("%<"))
    {
      r = ESP8266.readStringUntil(',');
      g = ESP8266.readStringUntil(',');
      b = ESP8266.readStringUntil('%');
    }
  }