Search code examples
arduinoiotesp8266arduino-esp8266esp8266wifi

How to solve "Connection failed" for D1mini(ESP8266)


I'm trying to use D1 mini to fetch some data from website. I created an API key on Thingspeak ThingHttp. However, the client didn't connect properly. I got "connection failed" from the Serial monitor.

Here is my code. I think they are almost the same as this.

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
WiFiClientSecure client;

#define HOST "api.thingspeak.com"
void setup()
{
const char *ssid = "my_wifi";
const char *password = "qwertyui";
const char *API = "W0B96PD71W3Z245Q";
Serial.begin(115200);

WiFi.mode(WIFI_STA);
delay(100);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
    Serial.print(".");
    delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
IPAddress ip=WiFi.localIP();
Serial.println(ip);
delay(5000);
Serial.println("finish setup");
}
void loop()
{
delay(5000);
if (!client.connect(HOST, 80))
{
    Serial.println(F("Connection failed"));
    return;
}
Serial.println("***");
}

And here is what I got from the serial monitor.

WiFi connected
IP address: 
192.168.0.53
finish setup
Connection failed
Connection failed

It's obvious that it indeed connected to my wifi correctly, but just unable to connect to the server.

Does anyone know how to fix this? Or are there any crucial step I should set on my D1mini? (I'm using VSCode instead of Arduino IDE)


Solution

  • You're using the wrong port number.

    Port 80 is for unencrypted HTTP.

    Port 443 is for HTTPS.

    You're using WiFiClientSecure, so presumably you're intending to use HTTPS. HTTPS runs on port 443, not port 80. You'll need to change your code to use 443, or you'll need to use WiFiClient in order to work with port 80 (but make sure the API you're trying to connect to allows access over plain HTTP - most will not).

    I highly recommend that you use an existing HTTP client rather than implement the protocol yourself as you'll need to with WiFiClient or WiFiClientSecure, which just provide TCP and encrypted TCP connections. You can find examples of how to use ESP8266HTTPClient in the ESP8266 Arduino core repository.