Taillieu.Info

More Than a Hobby..

Hacking ESP8285 4 Way relay controller

https://www.aliexpress.com/snapshot/0.html?spm=a2g0s.9042647.6.2.5b8e36fahVpPGn&orderId=97070001814467&productId=32858982855


 

How to implement your own firmware on the Itead 4 Channel ESP8285 based Relay board ( 7V to 32V-4 Jog Switch)

Since I found no how to in the internet how to flash an own firmware into this nice and cheap Itead device I decided to wrote one. There are some specials to notice:

-       This module is based on the ESP8285 (NOT ESP8266 – Take care when selecting board in Arduino ide)

-       There are no plugs where you can easily attach your FTDI programmer. You will have to connect directly to the PSF-B85 board that holds the esp. (For more information about this board please refer to https://www.itead.cc/wiki/PSF-B85

-       Please note that the show pin reference is meant as a view from below the board which is some kind of confusing. So please follow the following picture how to connect your ftdi.

-       This how to does not include how to use the Arduino IDE and how to use a FTDI programmer. Please google this. There is much documentation.

-       Actually it can be ordered at bang good. Here: http://www.banggood.com/SONOFF-USB-5V-Or-DC-7V-32V-DIY-4-Channel-Jog-Inching-Self-locking-WIFI-Wireless-Smart-Home-Switch-p-1157460.html

Flash firmware

-       At first you will have to connect you FTDI programmer directly to the board. The following picture shows how to connect the 4 FTDI cables:

-       You will only need to connect GND, VCC, RX, TX and GPIO 0. Please keep in mind that you have to crossover RX and TX. So connect RX to TX and TX to RF. You can skip GPIO 15 and GPIO 2

-       To get the ESP into bootloader mode you have to connect GPIO0 to GND and the power up the device. Afterwards you can download the firmware with Arduino IDE or ESP tool. Afterwards you have to disconnect GPIO0 to let the device start firmware instead of bootloader

Using the board peripherals

-       Relay 1-4 is connected to PIN 12, 5, 4, 15                                  (example for relay 1 in Arduino sketch use: pinMode(12, OUTPUT);  digitalWrite(12, LOW);)

-       The LED is connected to PIN 13                                                 (example for relay 1 in Arduino sketch use: pinMode(13, OUTPUT);  digitalWrite(13, LOW);)

-       The button right next to the led is connected to PIN 14               (example for relay 1 in Arduino sketch use: pinMode(14, INPUT);  int value = digitalRead(14);)

-       The second button cannot be accessed directly

Hints

-       This PCBA comes with some kind of mode switch that can be selected with button2 (the one right next to the micro usb connector). If your relay does not react to your commands press this button to change the mode and afterwards do not change it again.

-       This PCBA need more current than most of the usb ports or FTDI programmers can offer. Therefore you might have to additionally connect the USB power supply.


I’m not the one to give up quick, so I started to try things out. For the sake of your time, I have created the complete pinout for you. If you want to refer to the original datasheet be my guest.

ESP8285 pinout

https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-01-300x238.jpg 300w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-01-768x609.jpg 768w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-01-640x507.jpg 640w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-01-980x777.jpg 980w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-01-50x40.jpg 50w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-01.jpg 1362w" sizes="(max-width: 640px) 100vw, 640px" style="box-sizing: border-box; border: 0px; max-width: 100%; height: auto; text-align: center; clear: both; display: block; margin: 6px auto 21px;">

The pinout itself on the pictures was confusing so I took the liberty of redesigning it.

ESP8285 PSF-B04 Pinout
PIN NAME FUNCTION
1 ANT Antenna
2 ADC Interface, Input Range: 0 – 1V
3 CH_EN Chip Enable High: Active; Low: Off. Note: External pull-up 1~10K resistor, connect 100nF capacitor to ground
4 GPIO16  
5 GPIO14 5S Enter configuration mode”}”>Channel 4 switch pin, active low APP configuration pin, low level >5S Enter configuration mode
6 GPIO12 Channel 1 relay switch, active high Note: as a switch button, on The electric moment will be high for a period of time, need to pull down (1~4.7K) resistor to ground
7 GPIO13 Wi-Fi status indicator, connect LED series current limiting resistor to VCC
8 GPIO15 channel 4 relay switch, Active high: Chip configuration pin, need pull-down (1~4.7K) resistor to ground
9 GPIO02 can be used as flash memory UART1_TX
10 GPIO00 5S Enter configuration mode”}”>channel 1 switch pin, active low APP configuration Pin, low level>5S Enter configuration mode
11 GPIO4 Channel 3 relay switch, active high 1
12 GND  
13 GPIO09 5S Enter configuration mode”}”>Channel 2 switch pin, active low APP configuration pin, low level >5S Enter configuration mode
14 GPIO10 5S Enter configuration mode”}”>Channel 3 switch pin, active low APP configuration pin, low level >5S Enter configuration mode
15 GPIO11  
16 GPIO06  
17 GPIO07  
18 GPIO08  
19 GPIO05 Channel 2 relay switches, high active
20 GND  
21 RX when used for programming Flash UART_RX
22 TX at programming Flash UART_TX
23 3.3V (VCC) external power supply
24 RST reset signals: active low

Having the ESP8285 pinout is one thing, but mapping this to an existing board is another. While the AFE Firmware I’m going to use have most of the mapping done, knowing what’s what is crucial when it comes to writing a custom code. This is the board and the connections:

https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-00-300x188.jpg 300w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-00-768x482.jpg 768w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-00-640x402.jpg 640w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-00-980x615.jpg 980w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-00-50x31.jpg 50w" sizes="(max-width: 640px) 100vw, 640px" style="box-sizing: border-box; border: 0px; max-width: 100%; height: auto; text-align: center; clear: both; display: block; margin: 6px auto 21px;">

ESP8285 GeekCreit 4 Way relay controller Pinout
GPIO FUNCTION
GPIO00 connect to GND on boot to enter flash mode
GPIO04 control relay 03
GPIO05 control relay 02
GPIO12 control relay 01
GPIO14 control pairing button
GPIO15 control relay 04
TX connect to RX of the programmer
RX connect to TX of the programmer
GND connect to GND
3.3V connect to power

To flash a ready bin file or your own Arduino IDE code, you have to back up, wipe the flash and upload the new bin file or the Arduino code. The procedure is described in detail here.

Please note, this board has to be powered via serial adapter AND the USB power supply when flashing the bin files.

I’m going to cover the AFE Firmware, which is pretty easy to use, if you want to push your own code, just open the Arduino IDE and flash it using the ESP8285 module in the board manager.

Before you get irritated, the ESP8285 GeekCreit 4 Way relay controller has a function button which drives the board modes. There is only one mode in which the board will function properly so circle the mode couple of times and try it out.

https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-02-300x278.jpg 300w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-02-768x713.jpg 768w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-02-640x594.jpg 640w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-02-980x909.jpg 980w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-02-50x46.jpg 50w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-02.jpg 1164w" sizes="(max-width: 640px) 100vw, 640px" style="box-sizing: border-box; border: 0px; max-width: 100%; height: auto; text-align: center; clear: both; display: block; margin: 6px auto 21px;">

AFF Firmware on ESP8285 GeekCreit 4 Way relay controller

If you are feeling lazy, Adrian Czabanowski created the firmware for this (and other) controllers. You can find his firmware on the website www.smartnydom.pl but a lot of it is in Polish.

Fortunately, you have me, and I’m here to make it easy – and download the Firmware for your board with up to 4 relays (T4). There is a version for ESP8266 and ESP8285 so make sure you get the right one. Flash the firmware (rename it to something simple) so you don’t have to type all that in the PowerShell.

Once the firmware is flashed, hold the pairing button for about 10 sec. You will see the board’s LED blinking fast. The ESP8285 GeekGerit 4 Way relay controller will go into the AP mode. Check the SSIDs on your phone and you will see the AFE Device – connect to it and note the gateway IP – usually, it’s something like:

192.168.5.1

And connect to it. Don’t bother with setting up everything on your mobile, unless you don’t have a PC around. Just update the Network details and finish configuration. Once this is done, the ESP8285 GeekCreit 4 Way relay controller will get a new IP assigned by your router.

https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-03-300x187.jpg 300w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-03-768x478.jpg 768w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-03-640x398.jpg 640w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-03-980x610.jpg 980w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-03-50x31.jpg 50w" sizes="(max-width: 640px) 100vw, 640px" style="box-sizing: border-box; border: 0px; max-width: 100%; height: auto; text-align: center; clear: both; display: block; margin: 6px auto 21px;">

Load the device page and enter settings again. From here you will be able to configure the device to your needs. Select the number of relays (4 – GPIO12,04,05,15), switches (1 – GPIO14) and LEDs (1 – GPIO13)

Enable the MQTT and HTTP protocols and check the general configuration. Make notes of anything you don’t think you can remember as we will need this to use the MQTT and HTTP protocols.

MQTT and HTTP

There are 2 protocols that can be used to interact with the ESP8285 GeekCreit 4 Way relay controller. Both have their own advantages and I will show you how to link these to a NodeRED server. If you want to learn more about MQTT and HTTP in NodeRED I have a fantastic tutorial for you.

MQTT

The ESP8285 GeekCreit 4 Way relay controller comes with 4 relays that we can toggle. The MQTT broker allows you to specify the topic for the device, but to control each of the relays we have to modify that topic more.

Let’s say I use the topic name /esp8285/ this means that to control the relays, I will have to add the name of each relay (from the config page) to the topic.

/esp8285/switch1/
/esp8285/switch2/
/esp8285/switch3/
/esp8285/switch4/

To issue the commands I have to modify the topic further:

MQTT commands
     
     
     
     
     
     
     
     
     
     
     
     
     
     

As you can see, this is fairly straight forward, and the control of each relay is done by modifying the topic and setting a correct payload.

HTTP requests

Another way of controlling the ESP8285 GeekCreit 4 Way relay controller is through the HTTP requests. Most of the time, you will be composing the URL which has embedded commands that will be issued to the board.

To build a valid URL you will need:

https://IP_Address/?device=relay&name=RelayName&command=command

Make sure to reserve the static IP address. The fields in my example are as follow:

command = on/off/get/toggle
RelayName = switch1/switch2/switch3/switch4

The responses given are sent in a JSON format. If you not sure how to handle JSON I have the tutorial explaining all you need to know here.

Here are a couple of JSON samples:

{ „device”:”ESP8285”, „name”:”switch1”, „command”:”on”, „value”:”on”, „status”:”success” }
{ „device”:”ESP8285”, „name”:”switch1”, „command”:”get”, „value”:”off”, „status”:”success” }
{ „command”:”reboot”, „status”:”success” }

Lastly, to control the MQTT, HTTP and other APIs links look like:

https://IP_Address/?device=DeviceName&name=ApiName&command=command

Where Apis names are: mqtt, http, domoticz.

Conclusion

https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-06-300x177.jpg 300w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-06-768x453.jpg 768w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-06-640x377.jpg 640w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-06-980x577.jpg 980w, https://notenoughtech.com/wp-content/uploads/2018/08/ESP8285-06-50x29.jpg 50w" sizes="(max-width: 640px) 100vw, 640px" style="box-sizing: border-box; border: 0px; max-width: 100%; height: auto; text-align: center; clear: both; display: block; margin: 6px auto 21px;">

The AFE Firmware is a cool solution if you don’t want to code the HTTP and MQTT protocols yourself. It’s robust enough to link it with the Alexa and Google Home skills. I’d love to see support for HTTPS and other integrations, but for now, this is a quick and easy way to integrate the ESP8285 and ESP8266 switches into your NodeRED environment. I wrote a very basic NodeRED flow to control and display the status of the relays on the dashboard. You can grab these files from below.

eWeLink Smart Home Center

eWeLinkSmart Home CentereWeLinkSmart Home Center

Only a simple tap at the APP will make your life easier

Standardized protocols, integrate without difficulty, device vendors just focus on their own business

 
 

na de knop 5-6 seconden, de LED knippert snel en het apparaat is toegevoegd aan de operationele apparaat

Productintroductie:

1. Relais Max Release Tijd: 5 ms
2. Met Signaal Indicator Lamp Relais Operationele Indicator Lamp
3. Stroomverbruik Ruststroom: 80mA; als alle relais zijn op, max 380mA
4.1-Kanaals Nominale Schakelaar Huidige :<= 10A; schakelaar spanning < = 250 V
5.4 Stks 10A Relais
6. Toepassingen: smart home, wifi controle, korte en lange afstand controle
7. Elektrische Schok Weerstaan Spanning: 1000 V
8. Relais Max Operationele Tijd: 15 ms

voordat configuratie, op-vraag key (dichtbij de LED button) voor meer dan 6 seconden, wanneer de LED begint knipperende, dan bedienen APP

download de foto van de app " eWeLink "

sluit APP,mobiele telefoon nummer geregistreerde Login,

1. klik op " set " de bijpassende knop, totdat het licht vrijgegeven na de flash;

2. Naam de apparaat voltooien bediening;

3. Voer de thuis naam en wachtwoord voor de WIFI;

4. Voeg een apparaat zoeken

A11081

IoT Over the Air Update (OTA) ESP8266

In This project I am going to explain steps of make ESP8266 ready for OTA update. We use here Arduino IDE for programe ESP8266 first time for giving support of OTA boot loader

Step 1: Install Python on Your System

You need to install python27 on your system in order to program ESP8266 from your system you need to run OTA script. Install python27 on System from where your going to upload firmware.

Step 2: Download and Install Arduino OTA Library

Download The library and tools required for OTA click here

Install "ArduinoOTa.zip" in arduino library.

Step 3: Upload Sketch With OTA Bootloader

Complile and Upload following sketch in ESP by our regular method through serial terminal. Its necessary to upload first time sketch with OTA suppot.


#include < esp8266wifi.h >

#include < esp8266mdns .h >

#include < wifiudp .h >

#include < arduinoota .h >

const char* ssid = "WIFI ROUTER NAME";

const char* password = "WIFI ROUTER PASSWORD";

void setup() {

Serial.begin(115200);

Serial.println("Booting");

WiFi.mode(WIFI_STA);

WiFi.begin(ssid, password);

while (WiFi.waitForConnectResult() != WL_CONNECTED) {

Serial.println("Connection Failed! Rebooting...");

delay(5000);

ESP.restart();

}

ArduinoOTA.onStart([]() {

String type;

if (ArduinoOTA.getCommand() == U_FLASH)

type = "sketch";

else // U_SPIFFS

type = "filesystem";

// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()

Serial.println("Start updating " + type);

});

ArduinoOTA.onEnd([]() {

Serial.println("\nEnd");

});

ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {

Serial.printf("Progress: %u%%\r", (progress / (total / 100)));

});

ArduinoOTA.onError([](ota_error_t error) {

Serial.printf("Error[%u]: ", error);

if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");

else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");

else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");

else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");

else if (error == OTA_END_ERROR) Serial.println("End Failed");

});

ArduinoOTA.begin();

Serial.println("Ready v1.0"); //Change version for every new modification in firmaware

Serial.print("IP address: ");

Serial.println(WiFi.localIP());

pinMode(2,OUTPUT);

}

void loop() {

ArduinoOTA.handle();

digitalWrite(2,HIGH);

delay(500);

digitalWrite(2,LOW);

delay(500);

}

Step 4: Create New Bin File for Test Working of OTA

 

Now your ESP8266is ready for OTA support.
How to test OTA is working ?

first you need new firm ware file OTA support two types of file i.e 1) .bin, 2 ) SPIFF

Here we are dealing with only .bin file.

modify above sketch withc some changes like

Serial.println("Ready v2.0"); //Change version for every new modification in firmaware

.

void loop() {

ArduinoOTA.handle();

digitalWrite(2,HIGH);

delay(2000);

digitalWrite(2,LOW);

delay(2000);

}

here we change version of firmware and make some changes in program. That can be reflect after OTA update.

Now only Verify/Compile program in Arduino IDE do not Upload.

goto run > %temp% in temp folder find out your arduino build folder

Locate build folder

Locate .bin file

copy .bin file path which is used for espota tool.

Step 5: Upgrade Firmware OTA and Verify OTA Is Working

 

Now prepare system which can access ESP8266 in network.
In download rar file you will find espota.py script that can upload firmware in esp.

Open command prompt in espota.py file location by pressing shift key and right click > open command window here.

give this command

python espota.py -i 10.19.30.40 -p 8266 -f "C:\User\INDIA\AppData\Local\\Temp\builda0eb11f6003a2bd55895c96acd777afe.tmp\BasicOTA.ino.bin" -d -r

firmware up-gradation will start

For detail procedure follow this blog zenelectro.blogspot.in

ESP8266 Advanced

DNS Captive Portal

When using the ESP8266 in access point mode, you probably want to redirect users to the right page. You can do this by creating a captive portal, using DNS. It's basically just a DNS server that will convert all host names to the ESP's own IP address. 
This technique is also used by open Wi-Fi networks that redirect you to a login page before you can start browsing the internet.

Wi-Fi configuration

If you want to be able to change the Wi-Fi connection settings without re-uploading the code, you could take a look at the WiFiManager library by tzapu. This will try to connect to known networks, but if it fails, it will start a Wi-Fi access point. You can then connect to this access point, open the browser, and pick a network to connect to. The new configuration is saved.
The WiFiManager library uses a captive portal to present you with the right Wi-Fi settings page.
You could also implement a Wi-Fi manager yourself, or you can just check out the example that comes with the ESP8266 Arduino Core (Examples > DNSServer > CaptivePortalAdvanced).

I²S

The ESP8266 has an I²S bus on the RXD pin. It can run at 80MHz, and has DMA (direct memory access), so it's really fast. Its main purpose is to connect an I²S DAC (Digital to Analog Converter) to have an audio output, but you can use it for other things as well. 
For example, CNLohr managed to transmit analog television, by connecting an antenna wire to the I²S pin. You can also use it to control WS2812Bs LEDs. You can even use it to communicate over Ethernet (not really useful, and definitely not recommended, but it works).
Another great use for the I²S bus is outputting data to shift registers. This gives you extra outputs that are reasonably fast, for things like LEDs or stepper motors.

Other examples

You can find lots of other examples in the Arduino IDE, I'd recommend to check those out as well.

YouTube

There's some great channels on YouTube that do amazing things with the ESP8266. Here's a short list of the ones I'm currently following. If you've got more recommendation, just leave a comment!

ESP8266 Email notifier

Another great use for IoT devices is displaying things like traffic information, weather forecast, social media updates ... This requires us to send an HTTP GET request to the server of the service we'd like to access. Most popular services have API (Application Programming Interface) documents that explain that explain how you can retrieve certain information, and what format that information is in. In the following example, we'll look at Gmail specifically, but the code should be similar for other services.

Showing the number of unread emails

To communicate with Google's Gmail servers, we have to establish a secure connection to the server and send a secure HTTPS request with our email address and password. Gmail will then respond with an XML document containing all kinds of information, like (parts of) your most recent messages and the number of unread emails.
 
To make sure we don't send our Google password to a malicious server, we have to check the server's identity, using the SHA-1 fingerprint of the SSL certificate. This is a unique sequence of hexadecimal characters that identifies the server.

Allowing access to the email feed

The only way (I know of) to get email information from Google on the ESP currently is the Google Atom Feed. This is an older method, so you have to change your Gmail settings to allow access to the feed.
Go to https://www.google.com/settings/security/lesssecureapps to enable access for "less secure apps":blocked sign-in attempt-2.pngless secure apps-2.png
 
Until there's support for the new OAuth2 protocol on the ESP, we'll have to use the old, less secure method.

Hardware

Connect an LED (+ resistor) to pin 13, as an unread email indicator.

The Code

#include <WiFiClientSecure.h>   // Include the HTTPS library
#include <ESP8266WiFi.h>        // Include the Wi-Fi library
#include <ESP8266WiFiMulti.h>   // Include the Wi-Fi-Multi library

ESP8266WiFiMulti wifiMulti;     // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'

const char* host = "mail.google.com"; // the Gmail server
const char* url = "/mail/feed/atom";  // the Gmail feed url
const int httpsPort = 443;            // the port to connect to the email server

                                      // The SHA-1 fingerprint of the SSL certificate for the Gmail server (see below)
const char* fingerprint = "D3 90 FC 82 07 E6 0D C2 CE F9 9D 79 7F EC F6 E6 3E CB 8B B3";

                                      // The Base64 encoded version of your Gmail login credentials (see below)
const char* credentials = "ZW1haWwuYWRkcmVzc0BnbWFpbC5jb206cGFzc3dvcmQ=";

const byte led = 13;

void setup() {
  Serial.begin(115200);         // Start the Serial communication to send messages to the computer
  delay(10);
  Serial.println('\n');

  pinMode(led, OUTPUT);

  wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");   // add Wi-Fi networks you want to connect to
  wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
  wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");

  Serial.println("Connecting ...");
  int i = 0;
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }
  Serial.println('\n');
  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());              // Tell us what network we're connected to
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());           // Send the IP address of the ESP8266 to the computer
  Serial.println('\n');
}

void loop() {
  int unread = getUnread();
  if (unread == 0) {
    Serial.println("\r\nYou've got no unread emails");
    digitalWrite(led, LOW);
  } else if (unread > 0) {
    Serial.printf("\r\nYou've got %d new messages\r\n", unread);
    digitalWrite(led, HIGH);
  } else {
    Serial.println("Could not get unread mails");
  }
  Serial.println('\n');
  delay(5000);
}

int getUnread() {    // a function to get the number of unread emails in your Gmail inbox
  WiFiClientSecure client; // Use WiFiClientSecure class to create TLS (HTTPS) connection
  Serial.printf("Connecting to %s:%d ... \r\n", host, httpsPort);
  if (!client.connect(host, httpsPort)) {   // Connect to the Gmail server, on port 443
    Serial.println("Connection failed");    // If the connection fails, stop and return
    return -1;
  }

  if (client.verify(fingerprint, host)) {   // Check the SHA-1 fingerprint of the SSL certificate
    Serial.println("Certificate matches");
  } else {                                  // if it doesn't match, it's not safe to continue
    Serial.println("Certificate doesn't match");
    return -1;
  }

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

  client.print(String("GET ") + url + " HTTP/1.1\r\n" + 
               "Host: " + host + "\r\n" +
               "Authorization: Basic " + credentials + "\r\n" +
               "User-Agent: ESP8266\r\n" +
               "Connection: close\r\n\r\n"); // Send the HTTP request headers

  Serial.println("Request sent");

  int unread = -1;

  while (client.connected()) {                          // Wait for the response. The response is in XML format
    client.readStringUntil('<');                        // read until the first XML tag
    String tagname = client.readStringUntil('>');       // read until the end of this tag to get the tag name
    if (tagname == "fullcount") {                       // if the tag is <fullcount>, the next string will be the number of unread emails
      String unreadStr = client.readStringUntil('<');   // read until the closing tag (</fullcount>)
      unread = unreadStr.toInt();                       // convert from String to int
      break;                                            // stop reading
    }                                                   // if the tag is not <fullcount>, repeat and read the next tag
  }
  Serial.println("Connection closed");

  return unread;                                        // Return the number of unread emails
}

How it works

The setup should be pretty familiar by now. 
The only new thing is the getUnread() function:
First, it starts an HTTPS connection to the Gmail server on port 443. Then it checks if the fingerprint of the certificate matches, so it knows that it's the real Google server, and not some hacker. If the certificate doesn't match, it's not safe to send the credentials to the server.

If it matches, we send a HTTP GET request to the server:

GET /mail/feed/atom HTTP/1.1\r\n
Host: mail.google.com\r\n
Authorization: Basic aVeryLongStringOfBase64EncodedCharacters=\r\n
User-Agent: ESP8266\r\n
Connection: close\r\n\r\n
The request contains the URI we want to access (in this case this is the Atom feed URL), the host (which is mail.google.com), and the base64-encoded version of your login credentials.
As you can see, the different lines of the header are separated by a CRLF (Carriage Return + Line Feed, \r\n). Two CRLF's mark the end of the header.
The Gmail server will process our request, and send the feed as a response over the same HTTPS connection. This response is an XML document, that consists of tags with angled brackets, just like HTML. If you need a lot of data, it's recommended to use a proper XML parser library, but we only need one tag, so we can just skim through the response text until we find the <fullcount>x</fullcount> tag. The number inside this tag is the number of unread emails in the inbox.
We can just convert it to an integer, and stop reading.
 
This is the format of the XML feed, you can see the fullcount tag on line 5:
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://purl.org/atom/ns#" version="0.3">
    <title>Gmail - Inbox for Dit e-mailadres wordt beveiligd tegen spambots. JavaScript dient ingeschakeld te zijn om het te bekijken.;/title>
    <tagline>New messages in your Gmail Inbox</tagline>
    <fullcount>5</fullcount>
    <link rel="alternate" href="https://mail.google.com/mail" type="text/html" />
    <modified>2017-03-05T15:54:06Z</modified>
    <entry>
        <title>New sign-in from Firefox on Linux</title>
        <summary>New sign-in from Firefox on Linux Hi ESP8266, Your Google Account Dit e-mailadres wordt beveiligd tegen spambots. JavaScript dient ingeschakeld te zijn om het te bekijken. was just used to sign in from Firefox on Linux. ESP8266 Test Dit e-mailadres wordt beveiligd tegen spambots. JavaScript dient ingeschakeld te zijn om het te bekijken. Linux Sunday,</summary>
        <link rel="alternate" href="https://mail.google.com/mail?account_id=Dit e-mailadres wordt beveiligd tegen spambots. JavaScript dient ingeschakeld te zijn om het te bekijken.&;amp;message_id=123456789&amp;view=conv&amp;extsrc=atom" type="text/html" />
        <modified>2017-03-05T15:52:45Z</modified>
        <issued>2017-03-05T15:52:45Z</issued>
        <id>tag:gmail.google.com,2004:123456789123456789</id>
        <author>
            <name>Google</name>
            <email>Dit e-mailadres wordt beveiligd tegen spambots. JavaScript dient ingeschakeld te zijn om het te bekijken.;/email>
        </author>
    </entry>

    ...

</feed>

The loop just prints the number of unread emails, and turns on an LED if you have unread messages.

Getting the fingerprint of the Gmail server

Like I mentioned before, we need a fingerprint to check the identity of the server. To get this fingerprint, execute the following command in a terminal (Linux & Mac):
openssl s_client -connect mail.google.com:443 < /dev/null 2>/dev/null | openssl x509 -fingerprint -noout -in /dev/stdin | sed 's/:/ /g'
Copy the hexadecimal fingerprint string and paste it into the sketch on line 12. For example:
const char* fingerprint = "D3 90 FC 82 07 E6 0D C2 CE F9 9D 79 7F EC F6 E6 3E CB 8B B3";

Encoding your login credentials

To get access to the feed, you have to enter your email address and password. You can't send them as plain text, you have to encode them to base64 first. Use the following command in a terminal (Linux & Mac):
echo -n "Dit e-mailadres wordt beveiligd tegen spambots. JavaScript dient ingeschakeld te zijn om het te bekijken.:password" | base64
Then add it to line 15 of the sketch. For example:
const char* credentials = "ZW1haWwuYWRkcmVzc0BnbWFpbC5jb206cGFzc3dvcmQ=";

Other APIs

Many services send their data in JSON format. If you just need one piece of information, you may be able to use the same approach of scanning the entire JSON text for a certain word, but it's much easier to use a JSON parser, like the ArduinoJson library. It will deserialize the JSON text, and create a JSON object, you could compare it to an associative array. You can browse the entire tree structure, and easily find the data you're looking for.
The downside is that it uses more memory.