ESP8266从网页获取请求返回Connectionr拒绝

时间:2017-07-15 07:00:42

标签: get arduino esp8266

我希望能够将数据从网页发送到esp8266并控制一个引脚,每当我按下网页上的按钮,它就会返回ESP的{i}地址和CONNECTION REFUSED。我究竟做错了什么?

ESP代码:

void setup() {
  Serial.begin(115200);
  delay(100);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to: ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while( WiFi.status() != WL_CONNECTED){
      delay(500);
      Serial.print(".");
     }

  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Netmask: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("Gateway: ");
  Serial.println(WiFi.gatewayIP());

}

int value = 0;


void loop() {
   HTTPClient http;

   http.begin("192.168.0.24:80");
   int httpCode = http.GET();

   if(httpCode > 0){
    String payload = http.getString();
    Serial.println(payload);
    }
    http.end();
    delay(3000);

}

HTML网站:

<html>
<head>
  <title>ESP8266 toggle page</title>
</head>
  <body>
    <button id="3" class="led">Toggle pin 3</button>

    <script src="jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
          $(".led").click(function(){
            var p = $(this).attr('id');
            $.get("http://192.168.0.16:80", {pin:p});
          });
        });
    </script>
  </body>
</html>

1 个答案:

答案 0 :(得分:3)

你让你的esp8266充当客户端而不是服务器。你应该让你的esp8266接受请求而不是一个。然后,您的esp8266将成为服务器,您的网站将成为客户端。您将能够从您的网站向esp8266上的服务器发出请求并进行处理。

到您的包含添加:

#include <ESP8266WebServer.h>

在包含任何函数之前添加:

ESP8266WebServer server(80);

setup()添加:

server.on("/", HTTP_GET, handleTogglePin);
server.begin();

loop()添加:

server.handleClient();

setup()之前添加:

void handleTogglePin() {
    if (server.hasArg("pin")) { server.send(500, "text/plain", "Missing argument: pin"); return; }
    Integer pin = server.arg("pin").toInt();
    if (digitalRead(pin) == HIGH) {
        digitalWrite(pin, LOW);
    } else {
        digitalWrite(pin, HIGH);
    }
}

哦,不要忘记将引脚设置为setup()中的输出:

pinMode(3, OUTPUT);