1

I modified a code which replies BAR when I send FOO. The problem is the if else statement always lands on else which prints Wrong command. I tried comparing it to string FOO(??) and also comparing it to char FOO with the same buffer size but no joy. This is the code:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "##########";
const char* password = "##########";

WiFiUDP Udp;
unsigned int localUdpPort = 9999;  // local port to listen on
char incomingPacket[255];  // buffer for incoming packets
char command_1[255] = "FOO"; //Tried same buffer size... no luck
char replay_1[] = "BAR";
char wrong[] = "Wrong command";

void setup()
{
  Serial.begin(74880);
  Serial.println();
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
  Udp.begin(localUdpPort);
}

void loop()
{
  int packetSize = Udp.parsePacket();
  if (packetSize)
  {
    int len = Udp.read(incomingPacket, 255);
    if (len > 0)
    {
      incomingPacket[len] = 0;
    }
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(incomingPacket); // Prints the same as from icoming packet which is FOO (Debbuging)
    if (incomingPacket == command_1) { //Tried comparing to same buffer size "FOO" and string "FOO"... no luck
      Udp.write(replay_1);
    }
    else {
      Udp.write(wrong);
    }
    Udp.endPacket();
  }
}
5

You are comparing a char* to a char*. Array's are contiguous memory locations and the variable name for an array in this case command_1 and incomingPacket point to the first element in the array. Since they are two different array's, the location of the first element in command_1 is different than the location of the first element in incomingPacket so command_1 will never equal incomingPacket.

In order to check if the incoming packet equals "Foo" try

if(strcmp(incomingPacket, "Foo") == 0)

This utilizes the strcmp() compares two null terminated character arrays and returns 0 if they are equal.

Just ensure that the incomingPacket is null terminated I have never worked with this library before.

| improve this answer | |
0
> if (incomingPacket == command_1)

that statement is testing if pointer incomingPacket is pointing to the same address as pointer command_1.

to compare strings, you can either use a ready-canned function (if your compiler supports it), or to define your definition of "string equality" and execute it. most likely that requires comparing size first, and the individual characters in the string until a mismatch is found, or you have exhausted one of the strings.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.