0

I have this following code, which is working for any string to send and receive hello world. But how can i send specific string and use if then else ?

for example, when i send following its always sending hello world only but how can i do

echo "command1" | nc -4u localhost 21
echo "command2  | nc -4u localhsot 21

on receive i want to parse them with if then else but its not working:

if ( packetBuffer == "command1" ) { 

else if ( packetBuffer == "command2") { 

} else {

}

code:

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>

byte mac[]={0xDE, 0xAD, 0xBE, 0xEF, 0xAD, 0xDE};
IPAddress ip(192,168,1,2);
unsigned int localPort = 21;

char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
char  ReplyBuffer[] = "hello world";
EthernetUDP Udp;

char          r1[] = "1";
char          r2[] = "2";
char          r3[] = "3";

void setup() {
  Ethernet.begin(mac,ip);
  Udp.begin(localPort);
}

void loop() {
  int packetSize = Udp.parsePacket();
  if(packetSize) {
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
    Udp.write(packetBuffer);

      if ( !strcmp(packetBuffer, "command1") ) {
        Udp.write(r1);
      } else if ( !strcmp(packetBuffer, "command2") ) {
        Udp.write(r2);
      } else {
        Udp.write(r3);
      }

    Udp.endPacket();
  }
  delay(10);
}
4

1 回答 1

1

使用相等运算符==时,您正在比较指针。

在您的情况下,您可以使用strcmp()“字符串比较”来比较内容。

if ( !strcmp(packetBuffer, "command1") ) { 

else if ( !strcmp(packetBuffer, "command2") ) { 

} else {

}

请注意,当字符串匹配时strcmp()返回,否则(取决于字母顺序)。0-1+1

于 2013-10-08T10:36:19.707 回答