【问题标题】:esp8266 create tcp server but can't receive dataesp8266 创建 tcp 服务器但无法接收数据
【发布时间】:2016-08-08 01:49:21
【问题描述】:

我正在使用 arduino ide 对 esp8266(wifi 模块)进行编程,并在模块上创建了一个 tcp 服务器,然后我使用 tcp 客户端测试程序来发送和接收数据。这是我正在使用的代码 我设法从模块发送数据,但无法从我的手机接收任何数据,有人可以帮助我吗? 这是我正在使用的代码

#include <ESP8266WiFi.h>
int i =0;
char ssid[] = "moataz";         
char pass[] = "58295829";  
int status = WL_IDLE_STATUS;

WiFiServer server(1050);

void setup() 
{
  Serial.begin(115200);
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin("moataz", "58295829");
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(".");
  } 
  Serial.println("connectedd");
  server.begin();
  IPAddress myAddress = WiFi.localIP();
  Serial.println(myAddress);
  delay(200);
}

bool alreadyConnected = 0;
void loop() {
  WiFiClient client = server.available();
  if (client) {
    if (!alreadyConnected) {
      client.flush();
      Serial.println("We have a new client");
      client.println("Hello, client!");
      alreadyConnected = true;
    }
  }
  if (client.available() > 0) {
    char thisChar = client.read();
    Serial.println("We got data");
    Serial.println(thisChar);
    delay(200);
  }
}

【问题讨论】:

  • 你在手机上做什么来接收数据?

标签: esp8266 arduino-ide


【解决方案1】:

WifiClient被删除时,连接被关闭,那么你的标志alreadyConnected不表示连接状态。
您的代码应该可以在第一次运行。
为了接受 TCP 连接,发送“Hello, client!”,读取 1 个字符,关闭 TCP 连接,您可以这样进行:

void loop() {
    WiFiClient client = server.available();
    if (client) {
        Serial.println("We have a new client");
        client.println("Hello, client!");

        if (client.available() > 0) {
            char thisChar = client.read();
            Serial.println("We got data");
            Serial.println(thisChar);
            delay(200);
        }
    }
}

如果您想保持连接打开,则需要将其保持在循环之外。 此示例WiFiTelnetToSerial.ino 展示了如何维护WIFIClient 的列表。

【讨论】:

    猜你喜欢
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2016-05-11
    • 2017-07-17
    相关资源
    最近更新 更多