Example sketches for the new Arduino IDE for ESP8266

Moderator: igrr

User avatar
By lajolo
#26391 Hello,
here is my source file.
I connect to www.example.com, but for the rest it is the WiFiClient example.

Thanks!
Marcello

---------------
// Import required libraries
#include <ESP8266WiFi.h>

// WiFi parameters
const char* ssid = "";
const char* password = "";

// Host
const char* host = "www.example.com";

void setup() {
// Start Serial
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() {

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;
}

// This will send the request to the server
client.print(String("GET /") + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(10);

Serial.print("client.status(): ");
Serial.println(client.status());
Serial.print("client.available(): ");
Serial.println(client.available());
Serial.print("client.connected(): ");
Serial.println(client.connected());

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

Serial.println();
Serial.println("closing connection");
delay(5000);

}
User avatar
By martinayotte
#26395 The reason why it didn't originally worked is the fact that this "www.example.com" doesn't send an CR or CRLF, it is only sending LF ... ;)

So, putting back the available() is working if we are printing lines ending with LF

Code: Select allwhile(client.available()){
String line = client.readStringUntil('\n'); // <---- look for LF here instead of CR
Serial.print(line);
}
User avatar
By torntrousers
#26410 Could it be that the response is being a bit slow so the code needs to first wait for it to be available? After the client.print try changing the delay(10) to this:
Code: Select all while(!client.available()){
    yield();
  }