gpt4 book ai didi

c++ - 为什么我的 if 子句不起作用?如何修复变量类型?

转载 作者:行者123 更新时间:2023-11-28 01:20:29 25 4
gpt4 key购买 nike

我想用udp语句改参数。我正在获取 udp,但我的 if 子句不起作用。怎么能 comper 2个变量?

我更改了变量类型和/或 if 子句类型(例如 if ( strcmp ( UdpMsg , "relay01_off") == 0) )。

设置IF子句变量

String UdpMsg = "12345";...

获取UDP报文

String UdpMsg ((char *)buffer);...

IF 子句

if ( UdpMsg == "relay01_off" ) {
digitalWrite(relay_pin, HIGH);
Serial.print ("You!\n");
}

我期待看到“你!”当我发送 UDP 但它找不到相等时。

信息的完整代码:

#include <WiFi.h>
#include <WiFiUdp.h>
#include <cstring> //For the string functions

const char* wifi_name = "SSID"; // Your Wifi network name here
const char* wifi_pass = "password"; // Your Wifi network password here
WiFiServer server(80); // Server will be at port 80

// IP address to send UDP data to.
const char * udpAddress = "192.168.1.6";
int udpPort = 4444;

//create UDP instance
WiFiUDP udp;

// relay PINi
int relay_pin = 15;

// UDP Mesajı gelen
String UdpMsg = "12345";

void setup()
{
Serial.begin (115200);
pinMode (relay_pin, OUTPUT);

Serial.print ("Connecting to ");
Serial.print (wifi_name);
WiFi.begin (wifi_name, wifi_pass); // Connecting to the wifi network

while (WiFi.status() != WL_CONNECTED) // Waiting for the response of wifi network
{
delay (500);
Serial.print (".");
}
Serial.println("");
Serial.println("Connection Successful");
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); // Getting the IP address
Serial.println("Type the above IP address into browser search bar");
server.begin(); // Starting the server
digitalWrite(relay_pin, LOW); // switch i AC

//This initializes udp and transfer buffer
udp.begin(udpPort);
}

void loop()
{
uint8_t buffer[50] = "";
//processing incoming packet, must be called before reading the buffer
udp.parsePacket();
//receive response from server, it will be HELLO WORLD
if(udp.read(buffer, 50) > 0){
Serial.print("Recevied UDP: ");
Serial.println((char *)buffer);
String UdpMsg ((char *)buffer);
}

//////// UDP IF leri ///////////
if ( UdpMsg == "relay01_off" ) { // Equal strings
digitalWrite(relay_pin, HIGH);
Serial.print ("You!\n");
}

}

最佳答案

您似乎在以下位置构建了第二个 UdpMsg 变量:

  if(udp.read(buffer, 50) > 0){
Serial.print("Recevied UDP: ");
Serial.println((char *)buffer);
String UdpMsg ((char *)buffer); // <--- 2nd UdpMsg, released after 'if' clause
}

UdpMsg 在这一行时:

if ( UdpMsg == "relay01_off" )

指第一个,全局的,保持初始值“12345”。

关于c++ - 为什么我的 if 子句不起作用?如何修复变量类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56511826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com