-6

Good day! I have a problem about my code. Why is it that I'm getting a connection failed when I'm connecting to my web server. By the way, I'm using a NodeMCU. Hope you guys can help me. Thank you in advance.

dda
  • 6,030
  • 2
  • 25
  • 34
Phen
  • 1
  • 1
  • 2
  • 2
    a) Post the code. b) [arduino.se] – 001 Oct 02 '17 at 13:07
  • Serial.print("Connecting to "); Serial.println(host); WiFiClient client; const int httpPort = 80; if (!client.connect(host, httpPort)) { Serial.println("Connection failed!"); return; } – Phen Oct 03 '17 at 09:01
  • You can't be THAT lazy... – dda Oct 05 '17 at 05:49

1 Answers1

1

Providing the full code would be helpful. Also, I can see you are taking part of the WiFiClient sketch as provided in the ESP8266 package for the Arduino IDE which is working for me, at least. If I'm wrong (that you are not using that sketch) then try this one:

#include <ESP8266WiFi.h>

const char* ssid     = "your-ssid";
const char* password = "your-password";

const char* host = "stackoverflow.com";
const char* streamId   = "....................";
const char* privateKey = "....................";

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

  // We start by connecting to a WiFi network
  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());
}

int value = 0;

void loop() {
 delay(5000);
 ++value;

 Serial.print("connecting to ");
 Serial.println(host);

 // Use WiFiClient class to create TCP connections
 WiFiClient client;
 const int httpPort = 80;
 if (!client.connect(host, httpPort)) {
  Serial.println("connection failed");
  return;
 }

 // We now create a URI for the request
 String url = "/";

 Serial.print("Requesting URL: ");
 Serial.println(url);

 // This will send the request to the server
 client.print(String("GET ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" + 
           "Connection: close\r\n\r\n");
 unsigned long timeout = millis();
 while (client.available() == 0) {
 if (millis() - timeout > 5000) {
  Serial.println(">>> Client Timeout !");
  client.stop();
  return;
 }
}

 // Read all the lines of the reply from server and print them to Serial
 while(client.available()){
  String line = client.readStringUntil('\r');
  Serial.print(line);
 }

 Serial.println();
 Serial.println("closing connection");
}

I've modified this to get the homepage of stackoverflow.com. Of course, you need to provide your SSID and SSID password and specify the host name.

If you need help installing the ESP8266/NodeMCU library for the Arduino IDE, check this out: https://www.teachmemicro.com/intro-nodemcu-arduino/