String comparsion in Arduino

2020-05-09 09:09发布

I am working on web based Home Automation System, so my Arduino sends a request to the server and gets the following response in serial monitor, along with "loneOn", which is due to Serial.println(r); statement.

HTTP/1.1 200 OK
Date: Mon, 13 Oct 2014 17:46:03 GMT
Server: Apache/2.4.4 (Win32) PHP/5.4.16
X-Powered-By: PHP/5.4.16
Content-Length: 14
Content-Type: text/html

loneOn.ltwoOn.


loneOn

In another case the response from the server will have loneOff, instead of loneOn, I need to decide which one it exactly is. But that's not the point right now, I am having trouble comparing the Strings. (Also the response would loop in the serial monitor, but again, that's not the point.)

This is the code for Arduino:

#include <TextFinder.h>
#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp.h>
#include <util.h>
#include <String.h>
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte server[] = { 192,168,137,1 } ; 
IPAddress ip(192,168,1,100);
EthernetClient client;
String response = "";
String r = "";

void setup() {
    Serial.begin(9600);
    while (!Serial) {
        ; 
    }

    if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        Ethernet.begin(mac, ip);
    }

    delay(1000);
    Serial.println("connecting...");

    if (client.connect(server, 80)) {
        Serial.println("connected");

        client.println("GET /dir/ardu.php HTTP/1.1");
        client.println("Host: localhost");
        client.println();

    } 
    else {
        Serial.println("connection failed");
    }
}

void loop(){
    char c,s;

    while(client.available()) 
    {
        c = client.read();
        response = response + c; 
    }

    Serial.println(response);
    r = (response.substring(165,174));
    Serial.println(r);

    if (r == "loneOn")
        Serial.println("Light 1 is on");
}

The problem is:

Serial.println(r);
if (r == "loneOn")
    Serial.println("Light 1 is on");
} 

Doesn't work, I mean here I am comparing the String 'r' with what its real value is i.e "loneOn", which is printed exactly as it is in the serial monitor, but the if statement returns nothing. I have tried several other methods of comparing Strings but it doesn't work. I wanted to know if there's anything I am missing about the Strings.

2条回答
时光不老,我们不散
2楼-- · 2020-05-09 09:49

Try

if(r.equals("loneOn"))
{
     Serial.println("Light 1 is on");
}

http://arduino.cc/en/Reference/StringEquals

查看更多
Deceive 欺骗
3楼-- · 2020-05-09 10:05
r = (response.substring(165,174)); 

I was using the wrong index, it was supposed to begin at 167. Which means there were blank spaces or "\n"s that were causing the string not to match with the given value.

查看更多
登录 后发表回答