1

这是示例代码:

在此代码中,它检测美元符号,然后识别字符,1、2、3 等。如果输入,http://x.x.x.x/$1- 意思是,它选择块条件 1。

等等。

我需要更改此代码,以便可以读取字符串并将其存储在变量中。

也许我可以拥有http://x.x.x.x/$25或 45 美元或 100 美元等。

void connection()
{
    EthernetClient client=server.available();

    if (client)
    {
        boolean currentLineIsBlank=true;

        while (client.connected()) {
            if (client.available()) {
                char c = client.read();

                if (incoming && c==' ')
                {
                    incoming=0;
                }
                if (c=='$')
                {
                    incoming=1;
                }
                //Checks for the URL string $1 or $2 and so on.
                if (incoming==1)
                {
                    if(c=='1')
                    {
                        //Insert something
                    }
                    if(c=='2')
                    {

                    }
                    if(c=='3')
                    {
                        redAll();
                    }
                }
                if(c=='\n')
                {
                    currentLineIsBlank=true;
                }
                else if(c!='\r')
                {
                    currentLineIsBlank=false;
                }
            }
        }
        delay(1);
        client.stop();
    }
}

我应该怎么办?让 Arduino 读取字符串。我应该用这段代码改变什么?

4

1 回答 1

1

Adafruit 的SDWebBrowse示例是我发现的最典型的示例。在那里,它将字符构建为字符串以供以后处理。

  ...
  if (client.available()) {
      char c = client.read();

      // If it isn't a new line, add the character to the buffer
      if (c != '\n' && c != '\r') {
          clientline[index] = c;
          index++;
          // Are we too big for the buffer? Start tossing out data
          if (index >= BUFSIZ)
              index = BUFSIZ -1;

          // Continue to read more data!
          continue;
      }

      // Got a \n or \r new line, which means the string is done.
      clientline[index] = 0;

      // Print it out for debugging.
      Serial.println(clientline);
  ...

我确实在以太网库本身中读过,两者都有

virtual int read();

virtual int read(uint8_t *buf, size_t size);

成员函数可用。但是,指针字符串的所有示例都仅显示了UDP的情况,而不是TCP的情况。我怀疑这可能与 UDP 的无状态有关。

不知道客户端缓冲区中的内容以及读取它的长度的实用性可能是预防性原因,我没有看到任何在 TCP 上使用它的示例。在哪里尝试可能很简单。

实际上,client.available()返回接收到的大小,所以应该可以:

...
int _available = client.available();
if (_available> 0) {
  client.read(clientline, _available);
...

注意两者都创建一个字符字符串。不要与String类混淆。

于 2013-01-23T14:21:49.093 回答