首页 > 解决方案 > 为什么 esp8266 客户端没有连接到服务器?

问题描述

我是 Arduino 新手,对它不太熟悉。我不确定为什么客户端无法连接到服务器,我已经看了好几个小时了。对此的任何解决方案都会有很大帮助。

所以我用下面的代码成功建立了一个服务器。但...

// server.ino
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid = "WifiName"; // Wifie name
const char* password = "WifiPassword"; // Wifi password
float sensor_value = 0.0;
String Website;

ESP8266WebServer server(80);

void setup(){
  Serial.begin(115200);
  WiFi.mode(WIFI_AP);

  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while(WiFi.status()!=WL_CONNECTED){
    Serial.print("."); 
    delay(500);
  }
  Serial.println("Server started at port 80."); 
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.print("URL=http://");
  Serial.println(WiFi.localIP());
  
  server.on("/", handleIndex); //use the top root path report last sensor value
  server.on("/update",handleUpdate); // use this route to update sensor value
  server.begin();
}

void loop(){
  server.handleClient();
}

void handleIndex(){ 
    Website = "<html><body onload ='process()'><div id='div1'>"+ String(sensor_value) +"</div></body></html>";
    server.send(200," text/html",Website);
}

void handleUpdate(){
  sensor_value = server.arg("value").toFloat();
  Serial.println(sensor_value);
  server.send(200,"text/plain","Updated");
}

我尝试将客户端连接到服务器,以便它可以向服务器发送数据,但是无法建立客户端和服务器之间的连接,我不知道为什么。我检查了IP地址,一切都正确我只是不明白为什么客户端无法连接到服务器

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <HX711.h>
#include "Wire.h"

#define DOUT D5
#define CLK D6
HX711 scale;

const char* ssid     = "WifiName";
const char* password = "Wifipassowrd";
float calibration_factor = 107095; 
float val_Weight;

const char* host = "192.168.0.167"; // Server host IP.
const int port = 80;
WiFiClient client;


void setup() {
   Serial.begin(115200);       //set baud rate
   Serial.println("Connecting to ");
   Serial.println(ssid); 

   WiFi.begin(ssid, password); 
   while (WiFi.status() != WL_CONNECTED) 
        {
          delay(500);//millisecond
          Serial.print(".");
          }
   Serial.println("");
   Serial.println("WiFi connected & connect to client"); 
  
}

void loop() {

  //connect to the server and send the data as URL parameter

  if(client.connect(host, port)){
    String url = "update?value=";
    url+=String(25.0);
    client.print(String("GET /") + url + "HTTP/1.1\r\n" + "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n");
    delay(10);

    Serial.println("Response: ");
    while(client.available()){
      String line = client.readStringUntil('\r');
      Serial.print(line);
    }
  }else{
    Serial.println("fail");
  }

   
}

任何帮助都会非常感谢!!!

标签: arduinoarduino-esp8266

解决方案


检查密码,你有一个错字。

const char* password = "Wifipassowrd";

推荐阅读