ESPHow ToIoT HardwaresTutorials/DIY

ESP8266 Tutorials | NodeMCU Programming | Arduino IDE

This tutorial dedicated for ESP8266 Tutorials or NodeMCU Tutorials. Nodemcu is not just a WiFi module, it also has a decent micro-controller in built. Nodemcu comes with 32-bit Tensilica Processor, Power-Saving Architecture, Compactness, High Durability. In this small tutorial, I will show you how easy it is to add Arduino Support.

What is ESP8266?

The ESP8266 series, or family, of Wi-Fi chips is produced by Espressif Systems, a fabless semiconductor company operating out of Shanghai, China. The ESP8266 series presently includes the ESP8266EX and ESP8285 chips.

ESP8266EX (simply referred to as ESP8266) is a system-on-chip (SoC) which integrates a 32-bit Tensilica microcontroller, standard digital peripheral interfaces, antenna switches, RF balun, power amplifier, low noise receive amplifier, filters and power management modules into a small package. It provides capabilities for 2.4 GHz Wi-Fi (802.11 b/g/n, supporting WPA/WPA2), general-purpose input/output (16 GPIO), Inter-Integrated Circuit (I²C), analog-to-digital conversion (10-bit ADC), Serial Peripheral Interface (SPI), I²S interfaces with DMA (sharing pins with GPIO), UART (on dedicated pins, plus a transmit-only UART can be enabled on GPIO2), and pulse-width modulation (PWM). The processor core, called “L106” by Espressif, is based on Tensilica’s Diamond Standard 106Micro 32-bit processor controller core and runs at 80 MHz (or overclocked to 160 MHz). It has a 64 KiB boot ROM, 32 KiB instruction RAM, and 80 KiB user data RAM. (Also, 32  KiB instruction cache RAM and 16 KiB ETS system data RAM.) External flash memory can be accessed through SPI. The silicon chip itself is housed within a 5 mm × 5 mm Quad Flat No-Leads package with 33 connection pads — 8 pads along each side and one large thermal/ground pad in the center.  Read about For Overview, Datasheet, Technical Reference.

ESP8285 is a variation of ESP8266 with 1 MiB of embedded flash memory.

The Modules

Vendors have consequently created a multitude of compact printed circuit board modules based around the ESP8266 chip. Some of these modules have specific identifiers, including monikers such as “ESP-WROOM-02” and and “ESP-01” through “ESP-14”; while other modules might be ill-labeled and merely referred to by a general description — e.g., “ESP8266 Wireless Transceiver.” ESP8266-based modules have demonstrated themselves as a capable, low-cost, networkable foundation for facilitating end-point IoT developments. Espressif’s official modules are presently ESP-WROOM-02 and ESP-WROOM-S2.

NodeMcu – Connect Things EASY

NodeMCU

is an open source IoT platform. It includes firmware which runs on the ESP8266 Wi-Fi SoC from Espressif Systems, and hardware which is based on the ESP-12 module. The term “NodeMCU” by default refers to the firmware rather than the development kits. The firmware uses the Lua scripting language. It is based on the eLua project, and built on the Espressif Non-OS SDK for ESP8266.

Features of NodeMCU

  • Arduino-like hardware IO – Advanced API for hardware IO, which can dramatically reduce the redundant work for configuring and manipulating hardware. Code like arduino, but interactively in Lua script.
  • Nodejs style network API – Event-driven API for network applicaitons, which faciliates developers writing code running on a 5mm*5mm sized MCU in Nodejs style. Greatly speed up your IOT application developing process.
  • Lowest cost WI-FI – Less than $2 WI-FI MCU ESP8266 integrated and esay to prototyping development kit. We provide the best platform for IOT application development at the lowest cost.
  • Development Kit – The Development Kit based on ESP8266, integates GPIO, PWM, IIC, 1-Wire and ADC all in one board. Power your developement in the fastest way combinating with NodeMcu Firmware!
NodeLua is the FIRST open source lua based firmware runs on ESP8266. The goal is to make IoT programming easier. Not only an interpreter, but with a Web IDE, Cloud APIs, Mobile App libraries, which makes you creating a real ‘thing’ running on your customers home more robustious and easier. It is currently running on ESP8266 and planned to support more chips, based on the lua language, nodejs-like APIs, but 10 times faster and 100 times smaller than nodejs.

Difference Between ESP8266 (NodeMCU) and Arduino UNO

Specification Arduino ESP8266
RAM 4K Bytes 80 Kilobytes
FLASH memory 32 Kilo bytes 4 Mega Bytes
Speed 16MHz 80MHz
GPIOs 14 11
IO Voltage Level 5V 3.3V
ADC 6 (10-bit) 1 (10-Bit)
Serial 1 1
I2C 1 1
SPI 1 Used by Flash Chip
PWM IOs 6 (8-Bit Resolution) All IO Pins with 10-Bit Resolution
WiFi NO YES 2 MBPS

ESP32 vs ESP8266

Esp32 And ESP8266 both most popular development boards. ESP32 and ESP8266 are cheap Wi-Fi modules perfectly suited for DIY projects in the Internet of Things (IoT) field. These modules come with GPIOs, support for a variety of protocols like SPI, I2C, UART, and more. The best part is that they come with wireless networking included, which makes them apart from other microcontrollers like the Arduino. This means that you can easily control and monitor devices remotely via Wi-Fi for a very low price.

Here you can see a table that adapted by AMICA IO. This table shows main differences between the ESP8266 and the ESP32 processors (table adapted from: AMICA_IO).

ESP8266
ESP32
MCU
Xtensa Single-core 32-bit L106
Xtensa Dual-Core 32-bit LX6 with 600 DMIPS
802.11 b/g/n Wi-Fi
HT20
HT40
Bluetooth
X
Bluetooth 4.2 and BLE
Typical Frequency
80 MHz
160 MHz
SRAM
X
Flash
X
GPIO
17
36
Hardware /Software PWM
None / 8 channels
None / 16 channels
SPI/I2C/I2S/UART
2/1/2/2
4/2/2/2
ADC
10-bit
12-bit
CAN
X
Ethernet MAC Interface
X
Touch Sensor
X
Temperature Sensor
X
Hall effect sensor
X
Working Temperature
-40ºC to 125ºC
-40ºC to 125ºC

GPIO pins of ESP8266

esp8266 Pinout

GPIO pins of ESP8266 and How to use efficiently

NodeMCU Pin Defining

NodeMCU has weird pin mapping. Pin numbers written on the board itself do not correspond to ESP8266 GPIO pin numbers. We have constants defined to make using this board easier:

#define PIN_WIRE_SDA (4)
#define PIN_WIRE_SCL (5)

static const uint8_t SDA = PIN_WIRE_SDA;
static const uint8_t SCL = PIN_WIRE_SCL;

static const uint8_t LED_BUILTIN = 16;
static const uint8_t BUILTIN_LED = 16;

static const uint8_t D0 = 16;
static const uint8_t D1 = 5;
static const uint8_t D2 = 4;
static const uint8_t D3 = 0;
static const uint8_t D4 = 2;
static const uint8_t D5 = 14;
static const uint8_t D6 = 12;
static const uint8_t D7 = 13;
static const uint8_t D8 = 15;
static const uint8_t D9 = 3;
static const uint8_t D10 = 1;

Never use GPIO0 (D3) as input pin, this pin is flash button. If it is low at power on state this will put ESP in programming mode.

GPIO Pin Description

Just like a normal Arduino, the ESP8266 has digital input/output pins (I/O or GPIO, General Purpose Input/Output pins). These digital input/outputs operate at 3.3V. NEVER CONNECT 5V TO ANY PIN OF ESP8266. The pins are not 5V tolerant, applying more than 3.6V on any pin will kill the chip. The maximum current that can be drawn from a single GPIO pin is 12mA.

ESP8266 has 17 GPIO pins (0-16), however, you can only use 11 of them, because 6 pins (GPIO 6 – 11) are used to connect the flash memory chip. This is the small 8-pin IC right next to the ESP8266. If you try to use one of these pins, you might crash your program.

GPIO 1 and 3 are used as TX and RX of the hardware Serial port (UART), so in most cases, you can’t use them as normal I/O while sending/receiving serial data.

Boot modes

Few I/O pins have a special function during boot: They select 1 of 3 boot modes:

GPIO15 GPIO0 GPIO2 Mode
0V 0V 3.3V Uart Bootloader
0V 3.3V 3.3V Boot sketch (SPI flash)
3.3V X X SDIO mode (not used for Arduino)

Note: Pull down of 1KOhm is required on GPIO0 and external pull-up resistor on GPIO2 is not required the internal pullup is enabled at boot.

  • GPIO15 is always pulled low, so you can’t use the internal pull-up resistor. You have to keep this in mind when using GPIO15 as an input to read a switch or connect it to a device with an open-collector (or open-drain) output, like I²C.
  • GPIO0 is pulled high during normal operation.
  • GPIO2 can’t be low at boot, so you can’t connect a switch to it.

Internal pull-up/-down resistors

GPIO 0-15 all have a built-in pull-up resistor, just like in an Arduino. GPIO16 has a built-in pull-down resistor.

Digital I/O

You can set the function of a pin using pinMode(pin, mode); where pin is the GPIO number*, and mode can be either INPUT, which is the default, OUTPUT, or INPUT_PULLUP to enable the built-in pull-up resistors for GPIO 0-15. To enable the pull-down resistor for GPIO16, you have to use INPUT_PULLDOWN_16.

(*) NodeMCU uses a different pin mapping, read more here. To address a NodeMCU pin, e.g. pin 5, use D5: for instance: pinMode(D5, OUTPUT);

To set an output pin high (3.3V) or low (0V), use digitalWrite(pin, value); where pin is the digital pin, and value either 1 or 0 (or HIGH and LOW).

To read an input, use digitalRead(pin);

PWM

ESP8266 supported PWM on all digital pins. The default PWM range is 10-bits @ 1kHz, but this can be changed. To enable PWM on a certain pin, use analogWrite(pin, value); where pin is the digital pin, and value a number between 0 and 1023. You can change the range (bit depth) of the PWM output by using analogWriteRange(range); The frequency can be changed by using analogWriteFreq(frequency);. frequency should be between 100 and 1000Hz.

Analog input

The ESP8266 has a single analog input, with an input range of 0 – 1.0V. If you supply 3.3V, for example, you will damage the chip. Some boards like the NodeMCU have an on-board resistive voltage divider, to get an easier 0 – 3.3V range. The ADC (analog to digital converter) has a resolution of 10 bits. The ESP can also use the ADC to measure the supply voltage (VCC). To do this, include ADC_MODE(ADC_VCC); at the top of your sketch, and use ESP.getVcc(); to actually get the voltage. If you use it to read the supply voltage, you can’t connect anything else to the analog pin.

Serial Communication

The ESP8266 has two hardware UARTS (Serial ports):
UART0 on pins 1 and 3 (TX0 and RX0 resp.), and UART1 on pins 2 and 8 (TX1 and RX1 resp.), however, GPIO8 is used to connect the flash chip. This means that UART1 can only transmit data.

UART0 also has hardware flow control on pins 15 and 13 (RTS0 and CTS0 resp.). These two pins can also be used as alternative TX0 and RX0 pins.

To use UART0 (TX = GPIO1, RX = GPIO3), you can use the Serial object, just like on an Arduino: Serial.begin(baud).

To use the alternative pins (TX = GPIO15, RX = GPIO13), use Serial.swap() after Serial.begin.

To use UART1 (TX = GPIO2), use the Serial1 object.

WiFi Communication

You can use ESP as a HotSpot mode and it can connect to hot spot. Both mode can work at a time.


ESP8266 Tutorials

In this article, You can find some best ESP8266 Tutorials for beginners

  • How to Use ESP8266/NodeMCU with Arduino IDE
  • DHT11 Temperature & Humidity sensor on NodeMCU using Arduino IDE
  • ESP8266 Tutorials : ESP8266 Web Server | ESP8266 Web Server AP (Access Point)
  • ESP8266 Tutorials : ESP8266 Static IP Address Using Arduino Example
  • ESP8266 Tutorials : ESP8266 PWM Example
  • ESP8266 Tutorials : NodeMCU ESP8266 with DHT11 and Firebase Real-Time Database
  • ESP8266 Tutorials : NodeMCU ESP8266 OTA (Over-the-Air) using Arduino IDE
  • ESP8266 Tutorials : RFID Reader MFRC522 interface with NodeMCU using Arduino IDE
  • ESP8266 Tutorials : LED using Blynk and ESP8266 (Node MCU)
  • ESP8266 Tutorials : NodeMcu to DHT Interface in Blynk app
  • ESP8266 Tutorials : GPS Module Interfacing with NodeMCU ESP8266
  • ESP8266 Tutorials : How To Make ESP8266 as a MQTT Broker
  • ESP8266 Tutorials : How To Use Grove-LCD RGB Backlight with NodeMCU
  • ESP8266 Tutorials : Controlled LED by Google voice assistant

ESP8266 Tutorials : How to Use ESP8266/NodeMCU with Arduino IDE

Arduino Support for ESP8266 with simple test code

Download Arduino IDE from https://www.arduino.cc/en/Main/SoftwareInstall the ESP8266 Board Package

Preference_json

  • Next, Select the Board manager under Tools.

Board_manager

  • Next, use the Board manager to install the ESP8266 package.

 ESP8266 Tutorials

  • Now last step Restart the Arduino IDE and Select the specific Board. Go to Tools =>Board and select “Generic ESP8266 Module” Now you can use ESP8266 with Arduino IDE.

Test Example of DHT11 Temperature & Humidity sensor on NodeMCU using Arduino IDE

The DHT11 is chosen because it is lab calibrated, accurate and stable and its signal output is digital. Most important of all, it is relatively inexpensive for the given performance. Below is the pinout of the sensor.

Installing Libraries

  • Click here to download the DHT sensor library.
  • Unzip the .zip folder and you should get DHT-sensor-library-master folder
  • Rename your folder from DHT-sensor-library-master to DHT
  • Move the DHT folder to your Arduino IDE installation libraries folder
  • You also need to install the Adafruit Unified Sensor Driver Library.
  • Unzip the .zip folder and you should get Adafruit_sensor-master folder
  • Rename your folder from Adafruit_sensor-master to Adafruit_sensor
  • Move the DHT_sensor folder to your Arduino IDE installation libraries folder
  • Finally, re-open your Arduino IDE

Copy the sketch below to your Arduino IDE. Replace the SSID and password with your own credentials.

// Including the ESP8266 WiFi library
#include <ESP8266WiFi.h>
#include "DHT.h"

// Uncomment one of the lines below for whatever DHT sensor type you're using!
#define DHTTYPE DHT11   // DHT 11

// Replace with your network details
const char* ssid = "YOUR_NETWORK_NAME";
const char* password = "YOUR_NETWORK_PASSWORD";

// Web Server on port 80
WiFiServer server(80);

// DHT Sensor
const int DHTPin = 5;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);

// Temporary variables
static char celsiusTemp[7];
static char fahrenheitTemp[7];
static char humidityTemp[7];

// only runs once on boot
void setup() {
  // Initializing serial port for debugging purposes
  Serial.begin(115200);
  delay(10);

  dht.begin();
  
  // Connecting to WiFi network
  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");
  
  // Starting the web server
  server.begin();
  Serial.println("Web server running. Waiting for the ESP IP...");
  delay(10000);
  
  // Printing the ESP IP address
  Serial.println(WiFi.localIP());
}

// runs over and over again
void loop() {
  // Listenning for new clients
  WiFiClient client = server.available();
  
  if (client) {
    Serial.println("New client");
    // bolean to locate when the http request ends
    boolean blank_line = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        
        if (c == '\n' && blank_line) {
            // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
            float h = dht.readHumidity();
            // Read temperature as Celsius (the default)
            float t = dht.readTemperature();
            // Read temperature as Fahrenheit (isFahrenheit = true)
            float f = dht.readTemperature(true);
            // Check if any reads failed and exit early (to try again).
            if (isnan(h) || isnan(t) || isnan(f)) {
              Serial.println("Failed to read from DHT sensor!");
              strcpy(celsiusTemp,"Failed");
              strcpy(fahrenheitTemp, "Failed");
              strcpy(humidityTemp, "Failed");         
            }
            else{
              // Computes temperature values in Celsius + Fahrenheit and Humidity
              float hic = dht.computeHeatIndex(t, h, false);       
              dtostrf(hic, 6, 2, celsiusTemp);             
              float hif = dht.computeHeatIndex(f, h);
              dtostrf(hif, 6, 2, fahrenheitTemp);         
              dtostrf(h, 6, 2, humidityTemp);
              // You can delete the following Serial.print's, it's just for debugging purposes
              Serial.print("Humidity: ");
              Serial.print(h);
              Serial.print(" %\t Temperature: ");
              Serial.print(t);
              Serial.print(" *C ");
              Serial.print(f);
              Serial.print(" *F\t Heat index: ");
              Serial.print(hic);
              Serial.print(" *C ");
              Serial.print(hif);
              Serial.print(" *F");
              Serial.print("Humidity: ");
              Serial.print(h);
              Serial.print(" %\t Temperature: ");
              Serial.print(t);
              Serial.print(" *C ");
              Serial.print(f);
              Serial.print(" *F\t Heat index: ");
              Serial.print(hic);
              Serial.print(" *C ");
              Serial.print(hif);
              Serial.println(" *F");
            }
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Type: text/html");
            client.println("Connection: close");
            client.println();
            // your actual web page that displays temperature and humidity
            client.println("<!DOCTYPE HTML>");
            client.println("<html>");
            client.println("<head></head><body><h1>ESP8266 - Temperature and Humidity</h1><h3>Temperature in Celsius: ");
            client.println(celsiusTemp);
            client.println("*C</h3><h3>Temperature in Fahrenheit: ");
            client.println(fahrenheitTemp);
            client.println("*F</h3><h3>Humidity: ");
            client.println(humidityTemp);
            client.println("%</h3><h3>");
            client.println("</body></html>");     
            break;
        }
        if (c == '\n') {
          // when starts reading a new line
          blank_line = true;
        }
        else if (c != '\r') {
          // when finds a character on the current line
          blank_line = false;
        }
      }
    }  
    // closing the client connection
    delay(1);
    client.stop();
    Serial.println("Client disconnected.");
  }
}   

Open the Arduino IDE serial monitor at a baud rate of 115200. After a few seconds your IP address should appear. Open any browser from a device that is connected to the same router that your ESP is. Then type the IP address and click Enter!, Now you can see temp and humd in browser.

Pin Diagram

  • DHT 11 vcc => 5V pin Nodemcu
  • DHT 11 GND => GND pin Nodemcu
  • DHT 11 Data => D1 pin Nodemcu

ESP8266 Tutorials : ESP8266 Web Server | ESP8266 Web Server AP (Access Point)

In this tutorial we are making ESP8266 Web Server and ESP as acces point. A web server is server software, or hardware dedicated to running said software, that can satisfy World Wide Web client requests. A web server can, in general, contain one or more websites. A web server processes incoming network requests over HTTP and several other related protocols.

To implement web server on ESP, there are two ways to make your first web server first connect to your WiFi router or make ESP as access point. You can use ESP8266 as access point and it can connect to access point or both.

ESP8266 Web Server Arduino IDE Sketch

We need these libraries to make web server.

ESP8266WiFi.h is required for doing all WiFi related functionalities such as connection, AP, etc.

WiFiClient.h this file is required to send request to web browser

ESP8266WebServer.h it handles all HTTP protocols
#include <ESP8266WiFi.h>;
#include <WiFiClient.h>;
#include <ESP8266WebServer.h>;

Now Define your SSID and Password of your WiFi router, where the ESP connects

//SSID and Password of your WiFi router
const char* ssid = "your_ssid";
const char* password = "password";

Web server is on port 80, you can use other ports also, default HTTP port is 80

ESP8266WebServer server(80); //Server on port 80

We have two ways to make web server one is to connect to WiFi hot spot or make ESP as hot spot (Access Point).

This command is used to connect to your WiFi Access point. The term Access Point (AP) is same as WiFi Hot Spot. If the network is open you can remove password field from command.

 WiFi.begin(ssid, password); //Connect to your WiFi router

After connection request we wait for WiFi to get connect. ESP8266 once connected and disconnected afterwards due to signal loss or any reason, there is no need to give this command again, it will try to connect again automatically.

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

To get IP address i.e. assigned to ESP8266 by your WiFi router use this command

WiFi.localIP();

When client request a web page by entering ESP IP address which data to be sent is handled by subroutine and that subroutine name is defined in server.on(path,subroutine_name).

 server.on("/", handleRoot); //Which routine to handle at root location

To start the server use this command

server.begin(); //Start server

handle client request

server.handleClient(); //Handle client requests

This subroutine is called when you enter IP address in web browser and hit enter. This routine sends the test “hello from esp8266” to web browser.

void handleRoot() {
server.send(200, "text/plain", "hello from esp8266!");
}
Complete Code

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

//SSID and Password of your WiFi router
const char* ssid = "Circuits4you.com";
const char* password = "9422212729";

ESP8266WebServer server(80); //Server on port 80

//===============================================================
// This rutine is exicuted when you open its IP in browser
//===============================================================void handleRoot() {
server.send(200, "text/plain", "hello from esp8266!");
}

//==============================================================
// SETUP
//==============================================================
void setup(void){
Serial.begin(9600);

WiFi.begin(ssid, password); //Connect to your WiFi router
Serial.println("");

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

//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP

server.on("/", handleRoot); //Which routine to handle at root location

server.begin(); //Start server
Serial.println("HTTP server started");
}
//==============================================================
// LOOP
//==============================================================
void loop(void){
server.handleClient(); //Handle client requests
}

To see the result first get the IP address from serial monitor, Open serial monitor and press reset. Open web browser and enter this IP (192.168.x.x), Make sure that your laptop or phone must be connected to the same network.

ESP as Access Point

First hide its AP (Access point) using this command at the beginning of setup.

WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi network

In some application you may find that both AP and connection to WiFi router are useful for making configuration you use ESP8266 AP and for data sending to cloud use WiFi connectivity in that case use this command and both connections. This way you can access ESP web page with two different IP address.

WiFi.mode(WIFI_AP_STA); //Both hotspot and client are enabled

Third way is only access point, default is all AP and STA are enabled, to get only AP use this command.

 WiFi.mode(WIFI_AP); //Only Access point

To start ESP as Access point you have to use this simple command

WiFi.softAP(ssid, password); //Start HOTspot removing password will disable security

To get IP address i.e. assigned to ESP8266 by your WiFi router use this command

IPAddress myIP = WiFi.softAPIP(); //Get IP address

Complete Program for as Access Point

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

//SSID and Password to your ESP Access Point
const char* ssid = "iotbyhvm";
const char* password = "iotbyhvm";

ESP8266WebServer server(80); //Server on port 80

//==============================================================
// This rutine is exicuted when you open its IP in browser
//==============================================================
void handleRoot() {
server.send(200, "text/plain", "hello from esp8266!");
}

//===============================================================
// SETUP
//===============================================================
void setup(void){
Serial.begin(9600);
Serial.println("");
WiFi.mode(WIFI_AP); //Only Access point
WiFi.softAP(ssid, password); //Start HOTspot removing password will disable security

IPAddress myIP = WiFi.softAPIP(); //Get IP address
Serial.print("HotSpt IP:");
Serial.println(myIP);

server.on("/", handleRoot); //Which routine to handle at root location

server.begin(); //Start server
Serial.println("HTTP server started");
}
//===============================================================
// LOOP
//===============================================================
void loop(void){
server.handleClient(); //Handle client requests
}

Output

After uploading program take your mobile turn on WiFi and in WiFi setting Scan for hot spot you will find “iotbyhvm” hot spot connect to it with password “iotbyhvm” as we have given in program. After connecting to ESP hot spot, Open web browser in mobile phone and enter IP 192.168.x.x you will see “hello from esp8266!” message. IP address can be found in serial monitor.


ESP8266 Tutorials : ESP8266 Static IP Address Using Arduino Example

1- Required Header files

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
//ESP Web Server Library to host a web page
#include <ESP8266WebServer.h>

2- WiFi IP configuration variables

Define Device IP address, Gateway (i.e. wifi router ip), subnet mask and dns. You can get this information from your laptops WiFi connection details.

 ESP8266 Tutorials

//Static IP address configuration
IPAddress staticIP(192, 168, 43, 90); //ESP8266 static ip
IPAddress gateway(192, 168, 43, 1); //IP Address of your WiFi Router (Gateway)
IPAddress subnet(255, 255, 255, 0); //Subnet mask
IPAddress dns(8, 8, 8, 8); //DNS
const char* deviceName = "iotbyhvm.ooo";

3- Connecting to WiFi Router with Above Configuration

Static IP configuration can be applied to ESP using WiFi.config statement.

WiFi.config(staticIP, subnet, gateway, DNS)

Use this command before WiFi begin. WiFi.hostname is optional, it is used to give name to ESP8266 to identify in WiFi router.

WiFi.disconnect(); //Prevent connecting to wifi based on previous configuration

WiFi.hostname(deviceName); // DHCP Hostname 
WiFi.config(staticIP, subnet, gateway, dns);
WiFi.begin(ssid, password);

WiFi.mode(WIFI_STA); //WiFi mode station (connect to wifi router only)

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

Complete Code of ESP8266 Static IP Address

This code makes a NodeMCU as webserver and controls onboard LED using web interface.

Change the IP settings, SSID and Password as per your WiFi router and upload.

/*
* ESP8266 NodeMCU LED Control over WiFi
* Using Static IP Address for ESP8266/NodeMCU
* https://iotbyhvm.ooo
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

//ESP Web Server Library to host a web page
#include <ESP8266WebServer.h>

//Our HTML webpage contents in program memory
const char MAIN_page[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<body>
<center>
<h1>WiFi LED on off demo: 1</h1><br>
Ciclk to turn <a href="ledOn">LED ON</a><br>
Ciclk to turn <a href="ledOff">LED OFF</a><br>
<hr>
<a href="https://iotbyhvm.ooo">IoTbyHVM.OOO</a>
</center>

</body>
</html>
)=====";

//Static IP address configuration
IPAddress staticIP(192, 168, 43, 90); //ESP static IP address
IPAddress gateway(192, 168, 43, 1); //IP Address of your WiFi Router (Gateway)
IPAddress subnet(255, 255, 255, 0); //Subnet mask
IPAddress dns(8, 8, 8, 8); //DNS


const char* deviceName = "iotbyhvm.ooo";

//On board LED Connected to GPIO2
#define LED 2

//SSID and Password of your WiFi router
const char* ssid = "yourssid";
const char* password = "yourpassword";

//Declare a global object variable from the ESP8266WebServer class.
ESP8266WebServer server(80); //Server on port 80

//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleRoot() {
Serial.println("You called root page");
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s); //Send web page
}

void handleLEDon() { 
Serial.println("LED on page");
digitalWrite(LED,LOW); //LED is connected in reverse
server.send(200, "text/html", "LED is ON"); //Send ADC value only to client ajax request
}

void handleLEDoff() { 
Serial.println("LED off page");
digitalWrite(LED,HIGH); //LED off
server.send(200, "text/html", "LED is OFF"); //Send ADC value only to client ajax request
}
//==============================================================
// SETUP
//==============================================================
void setup(void){
Serial.begin(115200);

WiFi.begin(ssid, password); //Connect to your WiFi router
Serial.println("");

//Onboard LED port Direction output
pinMode(LED,OUTPUT); 
//Power on LED state off
digitalWrite(LED,HIGH);

WiFi.disconnect(); //Prevent connecting to wifi based on previous configuration

WiFi.hostname(deviceName); // DHCP Hostname
WiFi.config(staticIP, subnet, gateway, dns);
WiFi.begin(ssid, password);

WiFi.mode(WIFI_STA); //WiFi mode station (connect to wifi router only)

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

//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP

server.on("/", handleRoot); //Which routine to handle at root location. This is display page
server.on("/ledOn", handleLEDon); //as Per <a href="ledOn">, Subroutine to be called
server.on("/ledOff", handleLEDoff);

server.begin(); //Start server
Serial.println("HTTP server started");
}
//==============================================================
// LOOP
//==============================================================
void loop(void){
server.handleClient(); //Handle client requests
}

Upload this code and observer serial monitor.


ESP8266 Tutorials : ESP8266 PWM Example

In This post ESP8266 PWM example explains how to use the Pulse Width Modulation (PWM)  with the ESP8266. We will use

analogWrite(PIN,VALUE);

ESP8266 can generate PWM on all IO pins. The ESP8266 analogWrite is different than the Arduino Uno. ESP8266 uses 10-bit resolution for PWM generation PWM value varries from 0 to 1023. Arduino Uses 8-Bit Resolution i.e.PWM range is 0-254.

analogWrite, Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal on most pins is approximately 1 KHz.

LED Fading Program using ESP8266 PWM

/* Generates PWM on Internal LED Pin GPIO 2 of ESP8266*/

#include <ESP8266WiFi.h>
#define LED 2

int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

// Power on setup
void setup() {
Serial.begin(115200);
pinMode(LED,OUTPUT);
}

// Main Program Loop
void loop() {
//PWM Value varries from 0 to 1023 
Serial.println("10 % PWM");
analogWrite(LED,102);
delay(2000);

Serial.println("20 % PWM");
analogWrite(LED,205);
delay(2000);

Serial.println("40 % PWM");
analogWrite(LED,410);
delay(2000);

Serial.println("70 % PWM");
analogWrite(LED,714);
delay(2000);

Serial.println("100 % PWM");
analogWrite(LED,1024);
delay(2000);

//Continuous Fading
Serial.println("Fadding Started");
while(1)
{
// set the brightness of pin 9:
analogWrite(LED, brightness);

// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 1023) {
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
delay(10);
}
}

Upload program in your ESP and open serial monitor.


ESP8266 Tutorials : NodeMCU ESP8266 with DHT11 and Firebase Real-Time Database

we’ll use a temperature & humidity sensor DHT11 and a NodeMCU ESP8266 Module to log the temperature and humidity in real time on Google’s Firebase database server.

MCU (Microcontrollers) have not enough memory to store sensors generated data for long time, either you have to use some external memory device or can save the data on some cloud using internet. The real time databases can be used in this scenario where we just have to interface some controller which can be connected to internet and can be able to exchange data with cloud server. The server data can be useful in monitoring real time system behavior, database analytics, statistical analysis and processing, and interpretation for future use case.


What is a Time Series Database?

A Time Series Database (TSDB) is a database optimized for time-stamped or time series data. Time series data are simply measurements or events that are tracked, monitored, downsampled, and aggregated over time. This could be server metrics, application performance monitoring, network data, sensor data, events, clicks, trades in a market, and many other types of analytics data.

=> https://iotbyhvm.ooo/influxdb-time-series-datbase/

Requirements

  1. NodeMCU ESP8266 Module
  2. DHT11 Temperature and Humidity sensor

Circuit Diagram

NodeMCU                     DHT11

3.3V                                VCC

GND                               GND

D4                                DATA

DHT11 Temperature and Humidity Sensor

DHT11 module features a humidity and temperature complex with a calibrated digital signal output means DHT11 sensor module is a combined module for sensing humidity and temperature which gives a calibrated digital output signal.

Read more about DHT 11 Sensors :  Visit this: DHT11 vs DHT22: Overview

NodeMCU ESP8266 with DHT11 and Firebase Real-Time Database

Firstly include the libraries for using ESP8266 and firebase.

#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>

Download and install the libraries by following the below links:

https://github.com/FirebaseExtended/firebase-arduino/blob/master/src/Firebase.h

https://github.com/bblanchon/ArduinoJson

While compiling, if you get error that ArduinoJson.h library is not installed then please install it using link given above.

We will program NodeMCU to take readings from DHT11 sensor and push it to Firebase every 5 seconds of interval.

These two parameters are very important to communicate with firebase. Setting these parameters will enable the data exchange between and ESP8266 and firebase.

#define FIREBASE_HOST "your-project.firebaseio.com"  // the project name address from firebase id
#define FIREBASE_AUTH "yuejx9ROxxxxxxxxxxxxxxxxfQDgfdhN" // the secret key generated from firebase

You can see all data in your firebase account. Just go to “Database” section in “Your Project” at “My console” In Firebase.

Arduino IDE Sketch

#include <ESP8266WiFi.h>    //esp8266 library
#include <FirebaseArduino.h>     //firebase library
#include <DHT.h>         // dht11 temperature and humidity sensor library
#define FIREBASE_HOST "your-project.firebaseio.com"  // the project name address from firebase id
#define FIREBASE_AUTH "Uejx9ROxxxxxxxxxxxxxxxxxxxxxxxxfQDDkhN"  // the secret key generated from firebase

#define WIFI_SSID "network_name"                  // wifi name 
#define WIFI_PASSWORD "password"                 //password of wifi 
 
#define DHTPIN D4                // what digital pin we're connected to
#define DHTTYPE DHT11              // select dht type as DHT 11 or DHT22
DHT dht(DHTPIN, DHTTYPE);                                                     

void setup() {
  Serial.begin(9600);
  delay(1000);                
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);    
  Serial.print("Connecting to ");
  Serial.print(WIFI_SSID);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("Connected to ");
  Serial.println(WIFI_SSID);
  Serial.print("IP Address is : ");
  Serial.println(WiFi.localIP());                  //print local IP address
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);     // connect to firebase
  dht.begin();                            //Start reading dht sensor
}

void loop() { 
  float h = dht.readHumidity();       // Reading temperature or humidity 
  float t = dht.readTemperature();   // Read temperature as Celsius (the default)
    
  if (isnan(h) || isnan(t)) {  // Check if any reads failed and exit early (to try again).
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
  
  Serial.print("Humidity: ");  Serial.print(h);
  String fireHumid = String(h) + String("%");    //convert integer humidity to string humidity 
  Serial.print("%  Temperature: ");  Serial.print(t);  Serial.println("°C ");
  String fireTemp = String(t) + String("°C"); //convert integer temperature to string temperature
  delay(4000);
  
  Firebase.pushString("/DHT11/Humidity", fireHumid);         //setup path and send readings
  Firebase.pushString("/DHT11/Temperature", fireTemp);        //setup path and send readings
   
}

ESP8266 Tutorials : NodeMCU ESP8266 OTA (Over-the-Air) using Arduino IDE

OTA Programming

OTA Programming

(Over the Air) is a process which allows devices to upgrade their firmware or software wirelessly without any physical access. It uses wireless technology like Wi-Fi, Bluetooth, GPRS or 4G/3G rather than wired serial communication. OTA is used to reprogram the node devices etc. OTA updates are generally sent for updating the software, resolving the bugs, adding some features etc. Here in this tutorial, we will send OTA update to ESP8266 NodeMCU to blink an LED.

Preparing NodeMCU to receive OTA Update Wirelessly

First connect the NodeMCU ESP8266 with the PC using micro USB cable. Then, to upload the firmware using OTA, we need to upload the sketch serially using micro USB to generate the ESP IP address. This is the necessary step to upload the firmware wirelessly next time. Select the serial port to which cable is attached from Tools -> Port.

ESP8266 comes with libraries and examples which can be directly accessed from Arduino IDE. Open Arduino IDE and then Open BasicOTA example.

(Visit this post : Arduino Support for ESP8266 with simple test code If your NodeMCU bord is not configured with Arduino IDE.)

Edit the sketch by replacing “your-ssid” and “your-password” by your Wi-Fi SSID and password and then upload the sketch.

Open serial monitor after uploading the program successfully. Set the Baud Rate of 115200 on Serial Monitor and press Reset button on NodeMCU ESP8266.

Now NodeMCU ESP8266 will get connected to Wi-Fi and IP address of the ESP will display on the serial monitor.

ESP8266 Blinking LED program for OTA Transfer

Before uploading the OTA blinking LED sketch go to Tools and change PORT to ESP IP address for uploading the firmware wirelessly to the NodeMCU.

ota

Now upload the below given sketch of blinking LED on NodeMCU wirelessly using Arduino IDE and make sure that your PC and ESP are connected to same Wi-Fi network. Connect a LED With D0 pin.

After uploading the code successfully, LED on NodeMCU ESP8266 will start blinking every 1 second. You can also set host name and password in the sketch for security while uploading firmware on ESP.

Arduino IDE Sketch

#include <ESP8266WiFi.h>         //provides ESP8266 specific Wi-Fi routines we are calling to connect to network.
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>  // OTA library

#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK  "your-password"
#endif

const char* ssid = STASSID; 
const char* password = STAPSK;

const int blink_led = D0;  // LED pin on NodeMCU ESP8266

void setup() {
  pinMode(blink_led,OUTPUT); 
  
  Serial.begin(115200);           //Set Baud Rate
  Serial.println("Booting");
                                                   // Step to connect ESP with the Wi-Fi
  WiFi.mode(WIFI_STA);               //Set ESP as station mode
  WiFi.begin(ssid, password);      //Wi-Fi Credentials

  while (WiFi.waitForConnectResult() != WL_CONNECTED)      //Connecting  ESP to wi-fi takes some time, so wait till it gets connected
{
    Serial.println("Connection Failed! Rebooting...");
    delay(1000);
    ESP.restart();
  }

  // Port defaults to 8266
  // ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  // ArduinoOTA.setHostname("myesp8266");

  // No authentication by default
  // ArduinoOTA.setPassword("admin");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  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();          //OTA initialization 
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());     // Display the IP address of the ESP on the serial monitor
}

void loop() {
  ArduinoOTA.handle();

 // code to blink led every 1 second
  digitalWrite(blink_led,HIGH);
  delay(1000);  
  digitalWrite(blink_led,LOW);
  delay(1000);
}

ESP8266 Tutorials : RFID Reader MFRC522 interface with NodeMCU using Arduino IDE

In this tutorial we will learn How to interface NodeMCU with RC522 RF ID Reader using Arduino library for MFRC522 and other RFID RC522 based modules. This library read and write different types of Radio-Frequency IDentification (RFID) cards on your Arduino or NodeMCU using a RC522 based reader connected via the Serial Peripheral Interface (SPI) interface.

What is RFID?

Radio-frequency identification

(RFID) uses electromagnetic fields to automatically identify and track tags attached to objects. The tags contain electronically stored information. Passive tags collect energy from a nearby RFID reader’s interrogating radio waves. Active tags have a local power source (such as a battery) and may operate hundreds of meters from the RFID reader. Unlike a barcode, the tag need not be within the line of sight of the reader, so it may be embedded in the tracked object. RFID is one method of automatic identification and data capture (AIDC).

Requirements

  • NodeMCU
  • MFRC522 RFID Reader
  • RFID Tags ( 13.56 MHz )
  • Bread Board
  • Jumper Wires
  • Micro USB Cable
  • Arduino IDE

Connections of MFRC522 RF ID Reader With Node MCU

             MFRC522      Node     
             Reader/PCD   MCU      
 Signal      Pin          Pin      
 ----------------------------------
 RST/Reset   RST          D1 (GPIO5)        
 SPI SS      SDA(SS)      D2 (GPIO4)       
 SPI MOSI    MOSI         D7 (GPIO13)
 SPI MISO    MISO         D6 (GPIO12)
 SPI SCK     SCK          D5 (GPIO14)
 3.3V        3.3V         3.3V
 GND         GND          GND

Arduino Code for MFRC522 RF ID Reader

For this program we need RF ID Library Download it from here.rfid-master

#include <SPI.h>
#include <MFRC522.h>

constexpr uint8_t RST_PIN = 5;     // Configurable, see typical pin layout above
constexpr uint8_t SS_PIN = 4;     // Configurable, see typical pin layout above
 
MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class

MFRC522::MIFARE_Key key; 

// Init array that will store new NUID 
byte nuidPICC[4];

void setup() { 
  Serial.begin(115200);
  SPI.begin(); // Init SPI bus
  rfid.PCD_Init(); // Init MFRC522 

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }

  Serial.println(F("This code scan the MIFARE Classsic NUID."));
  Serial.print(F("Using the following key:"));
  printHex(key.keyByte, MFRC522::MF_KEY_SIZE);
}
 
void loop() {

  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    return;

  Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  Serial.println(rfid.PICC_GetTypeName(piccType));

  // Check is the PICC of Classic MIFARE type
  if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&  
    piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
    piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
    Serial.println(F("Your tag is not of type MIFARE Classic."));
    return;
  }

  if (rfid.uid.uidByte[0] != nuidPICC[0] || 
    rfid.uid.uidByte[1] != nuidPICC[1] || 
    rfid.uid.uidByte[2] != nuidPICC[2] || 
    rfid.uid.uidByte[3] != nuidPICC[3] ) {
    Serial.println(F("A new card has been detected."));

    // Store NUID into nuidPICC array
    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }
   
    Serial.println(F("The NUID tag is:"));
    Serial.print(F("In hex: "));
    printHex(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
    Serial.print(F("In dec: "));
    printDec(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
  }
  else Serial.println(F("Card read previously."));

  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}


/**
 * Helper routine to dump a byte array as hex values to Serial. 
 */
void printHex(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

/**
 * Helper routine to dump a byte array as dec values to Serial.
 */
void printDec(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], DEC);
  }
}

ESP8266 Tutorials : LED using Blynk and ESP8266 (Node MCU)

Here, in this project we are controlling a LED using Blynk and Esp8266. Blynk was designed for the Internet of Things. It is most popular IoT Platform. It can control hardware remotely, it can display sensor data, it can store data, vizualize it and do many other cool things. With Blynk Library you can connect over 400 hardware models (including ESP8266, ESP32, NodeMCU, all Arduinos, Raspberry Pi, Particle, Texas Instruments, etc.)to the Blynk Cloud. Full list of supported hardware can be found here.

For more information about Blynk :

Visit this : Blynk IoT Platform

Components Required

  1. BYNK APP (Download from Play Store)
  2. ESP8266 NODEMCU

Blynk App Dashboard Setup for Controlling LED

To control LED with Blynk app, download and install the Blynk app from Google or Apple app store.

After sign up click on ‘New Project’ to start your project. Now provide your project a name and as blynk app works with diffferent hardware models.

Thus opt for your device from choices. Here, we are using ESP8266 nodeMCU.

While selecting your board opt for your association sort whether or not it’s Wi-Fi or LAN or USB association.

After these steps click on ‘Create’ button to form your project.

As, the blank project opens, add Widgets to it by clicking on Add button (Plus sign button)

Now after this click on ‘Button’ to add a button in your project.

Now in button settings provide a name to your button. After assign the pin number to the ‘OUTPUT’. Also, give names to your On/Off labels.

NODE MCU Setup for Blynk App

Open this link your browser https://examples.blynk.cc/ .  Select your board “ESP8266” and example code “LED Blink”.

 ESP8266 Tutorials

Now copy the example code from the browser as mentioned above and paste in Arduino IDE.

Arduino Sketch code Explanation

The complete code for Controlling LED using Blynk App and ESP8266 is given at the end. Includeall the required libraries for ESP8266 and Blynk App in the code, as shown below:

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

Enter the Auth Token in the code, which you can get from the Blynk App or from the mail you have received from Blynk.

char auth[ ] = "YourAuthToken";

To connect with WIFI enter your SSID name and password

char ssid[ ] = "YourNetworkName";
char pass[ ] = "YourPassword";

Here, void blinkLedWidget() function is used for switching ON and OFF the LED.

void blinkLedWidget() 
{
  if (led1.getValue()) {
    led1.off();
    Serial.println("LED on V1: off");
  } else {
    led1.on();
    Serial.println("LED on V1: on");
  }
}

In void setup( ) function, we will initialize the baud rate, LED output and will connect the module with the Wi-Fi using Blynk.begin(auth,ssid,password); function. This function begins the Wi-Fi connection.

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, blinkLedWidget);
}

Testing LED Control using Blynk App and ESP

Now, copy and paste the complete code into Arduino IDE. Then upload the code into the ESP8266. Then, open the Blynk App for controlling the LED from the button widget.

Complete Code

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).

char auth[ ] = "YourAuthToken";

// Your WiFi credentials.
// Set password to "" for open networks.

char ssid[ ] = "YourNetworkName";
char pass[ ] = "YourPassword";

WidgetLED led1(V1);
BlynkTimer timer;

// V1 LED Widget is blinking
void blinkLedWidget()  // function for switching off and on LED
{
  if (led1.getValue()) {
    led1.off();
    Serial.println("LED on V1: off");
  } else {
    led1.on();
    Serial.println("LED on V1: on");
  }
}

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, blinkLedWidget);
}

//In the loop function include Blynk.run() command.
void loop()
{
  Blynk.run();
  timer.run();
}

ESP8266 Tutorials : NodeMcu to DHT Interface in Blynk app

Things used in this project

DHT11 sensor measures and provides humidity and temperature values serially over a single wire. First read this article and prepare arduino for ESP8266 Arduino Support for ESP8266 with simple test code

PIN Connection:

 ESP8266 Tutorials

 

Create a Project use Blynk apps Following Instruction First LogIn your Blynk App Then Flow the Step By Step

Video Player

NOTE – You got your AUTH TOKEN it send to your email address.

Now Flash this code in ESP8266. Here Replace SSID, SSID PASSWORD and Auth TOKEN. You need to Some library.

So Download by this link https://github.com/blynkkk/blynk-library/archive/master.zip

Adafruit DHT sensor libraries:
https://github.com/adafruit/Adafruit_Sensor
https://github.com/adafruit/DHT-sensor-library

Download these library and extract it. Now open Arduino and go to File>Properties. Here you find path of Arduino.

Now go to Arduino path and paste all extracted libraries folder in Libraries Folder. Select Board “Nodemcu 1.0” in Tool tab of Arduino IDE and Select right Port for Nodemcu. Now Flash this code given below.

Code

/*************************************************************

WARNING :
For this example you’ll need Adafruit DHT sensor libraries:
https://github.com/adafruit/Adafruit_Sensor
https://github.com/adafruit/DHT-sensor-library

App project setup:
Value Display widget attached to V5
Value Display widget attached to V6
*************************************************************/

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <DHT.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = “AUTH TOKEN”;      // replace with your auth token, You got your AUTH TOKEN it send to your email.

// Your WiFi credentials.
// Set password to “” for open networks.
char ssid[] = “YOUR SSID”;                                                                     // replace with your SSID
char pass[] = “SSID PASSWORD”;                                                          // SSID Password

#define DHTPIN 2 // What digital pin we’re connected to

// Uncomment whatever type you’re using!
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22, AM2302, AM2321
//#define DHTTYPE DHT21 // DHT 21, AM2301

DHT dht(DHTPIN, DHTTYPE);
BlynkTimer timer;

// This function sends Arduino’s up time every second to Virtual Pin (5).
// In the app, Widget’s reading frequency should be set to PUSH. This means
// that you define how often to send data to Blynk App.
void sendSensor()
{
float h = dht.readHumidity();
float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit

if (isnan(h) || isnan(t)) {
Serial.println(“Failed to read from DHT sensor!”);
return;
}
// You can send any value at any time.
// Please don’t send more that 10 values per second.
Blynk.virtualWrite(V5, h);
Blynk.virtualWrite(V6, t);
}

void setup()
{
// Debug console
Serial.begin(9600);

Blynk.begin(auth, ssid, pass);
// You can also specify server:
//Blynk.begin(auth, ssid, pass, “blynk-cloud.com”, 80);
//Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);

dht.begin();

// Setup a function to be called every second
timer.setInterval(1000L, sendSensor);
}

void loop()
{
Blynk.run();
timer.run();
}

 ESP8266 Tutorials


ESP8266 Tutorials : GPS Module Interfacing with NodeMCU ESP8266

Components Required

  • NodeMCU ESP8266
  • GPS module- Ublox 6m
  • Jumper wires

Circuit Diagram

pin connection

Connect the Ublox Neo 6m GPS module directly to NodeMCU board by connecting GND pin of neo 6m to GND pin of NodeMCU and VCC pin to 3v3 pin. Also connect RXD to D1 and TXD to D2.

Programming NodeMCU with Arduino IDE for sending GPS data to Local server

First download and install TinyGPS library into Arduino IDE by Arduino IDE going into Sketch>>Include library>>Add .ZIP library. The library can be downloaded from this link. Then include all the required libraries and define all the variables in program as shown below:

#include <TinyGPS++.h> // library for GPS module
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
TinyGPSPlus gps;  // The TinyGPS++ object
SoftwareSerial ss(4, 5); // The serial connection to the GPS device
const char* ssid = "SSID name"; //ssid of your wifi
const char* password = "password"; //password of your wifi
float latitude , longitude;
int year , month , date, hour , minute , second;
String date_str , time_str , lat_str , lng_str;
int pm;
WiFiServer server(80);

To connect NodeMCU to your WiFi network we need to add the WiFi network’s SSID and Password inside the code.

Inside the setup() function, begin with the baud rate as 115200. After this initialize the WiFi connection using the WiFi SSID and password. Once the NodeMCU is connected to the WiFi network a local IP address will be generated and displayed on the serial monitor. This IP address will be used to access the GPS location data from your phone or laptop.

void setup()
{
  Serial.begin(115200);
  ss.begin(9600);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password); //connecting to wifi
  while (WiFi.status() != WL_CONNECTED)// while wifi not connected
  {
    delay(500);
    Serial.print("."); //print "...."
  }
  Serial.println("");
  Serial.println("WiFi connected");
  server.begin();
  Serial.println("Server started");
  Serial.println(WiFi.localIP());  // Print the IP address
}

Inside the loop() function, we are continuously checking if the GPS data is available and if it is available we extract the latitude, longitude, date and time from the NMEA string received from the GPS module.

The data from the GPS module is continue string of 28 characters which will contain Latitude, Longitude, Date, Time and many other information. It is called NMEA string, to learn more about it, follow the link.

$GPGGA,104534.000,7791.0381,N,06727.4434,E,1,08,0.9,510.4,M,43.9,M,,*47
$GPGGA,HHMMSS.SSS,latitude,N,longitude,E,FQ,NOS,HDP,altitude,M,height,M,,checksum data

TinyGPS library has inbuilt function to get the required data from the NMEA string. So here in the below code we extract the latitude, longitude, date and time from the string and stored the values in the variables “lat_str”, “lng_str, “date_str” and “time_str” respectively.

Time that we get from the GPS module will be in GMT format. So first separate the time data from the long string then convert this to local time format

void loop()
{
  while (ss.available() > 0) //while data is available
    if (gps.encode(ss.read())) //read gps data
    {
      if (gps.location.isValid()) //check whether gps location is valid
      {
        latitude = gps.location.lat();
        lat_str = String(latitude , 6); // latitude location is stored in a string
        longitude = gps.location.lng();
        lng_str = String(longitude , 6); //longitude location is stored in a string
      }
      if (gps.date.isValid()) //check whether gps date is valid
      {
        date_str = "";
        date = gps.date.day();
        month = gps.date.month();
        year = gps.date.year();
        if (date < 10)
         date_str = '0';
        date_str += String(date);// values of date,month and year are stored in a string
        date_str += " / ";
       ………………..
……………………………..

Now add HTML code to display the GPS data on the webpage. So here all the HTML code is embedded into a variable called “s”, then this variable is printed using client.print(s) to send all embedded HTML code to webpage.

 WiFiClient client = server.available(); // Check if a client has connected
  if (!client)
  {
    return;
  }
  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n <!DOCTYPE html> <html> <head> <title>GPS DATA</title> <style>";
  s += "a:link {background-color: YELLOW;text-decoration: none;}";
  s += "table, th, td </style> </head> <body> <h1  style=";
  s += "font-size:300%;";
  s += " ALIGN=CENTER> GPS DATA  **IoTbyHVM.OOO**</h1>";
  s += "<p ALIGN=CENTER style=""font-size:150%;""";
  s += "> <b>Location Details</b></p> <table ALIGN=CENTER style=";
  s += "width:50%";
  s += "> <tr> <th>Latitude</th>";
  s += "<td ALIGN=CENTER >";
  s += lat_str;
  s += "</td> </tr> <tr> <th>Longitude</th> <td ALIGN=CENTER >";
  s += lng_str;
  s += "</td> </tr> <tr>  <th>Date</th> <td ALIGN=CENTER >";
  s += date_str;
  s += "</td></tr> <tr> <th>Time</th> <td ALIGN=CENTER >";
  s += time_str;
  s += "</td>  </tr> </table> ";
  s += "</body> </html> \n";
  client.print(s); // all the values are send to the webpage
  delay(100);
}

Now once the code is uploaded into NodeMCU open the serial monitor. In the serial monitor you will be able to see some information like whether the WiFi is connected or not. If it is connected you will get the local IP address, here it is 192.168.1.09 (This be different for you). Note down the one that displayed on your serial monitor. If the serial monitor is showing blank then press RESET button on NodeMCU board.

Sometimes it takes a couple of minutes to connect the GPS module to the satellite. Once it get connected a blue LED will start to blink on the module.

Now open a webpage from your computer (just open a page in Google chrome, Firefox or any browser) and type the IP address that we collected from the serial monitor in the address bar and press ENTER. Now you will be able to see the location,date and time displayed on your computer screen.

Full Code

#include <TinyGPS++.h> // library for GPS module
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
TinyGPSPlus gps;  // The TinyGPS++ object
SoftwareSerial ss(4, 5); // The serial connection to the GPS device
const char* ssid = "ssid name"; //ssid of your wifi
const char* password = "password"; //password of your wifi
float latitude , longitude;
int year , month , date, hour , minute , second;
String date_str , time_str , lat_str , lng_str;
int pm;
WiFiServer server(80);

void setup()
{
  Serial.begin(115200);
  ss.begin(9600);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password); //connecting to wifi
  while (WiFi.status() != WL_CONNECTED)// while wifi not connected
  {
    delay(500);
    Serial.print("."); //print "...."
  }
  Serial.println("");
  Serial.println("WiFi connected");
  server.begin();
  Serial.println("Server started");
  Serial.println(WiFi.localIP());  // Print the IP address
}


void loop()
{
  while (ss.available() > 0) //while data is available
    if (gps.encode(ss.read())) //read gps data
    {
      if (gps.location.isValid()) //check whether gps location is valid
      {
        latitude = gps.location.lat();
        lat_str = String(latitude , 6); // latitude location is stored in a string
        longitude = gps.location.lng();
        lng_str = String(longitude , 6); //longitude location is stored in a string
      }
      if (gps.date.isValid()) //check whether gps date is valid
      {
        date_str = "";
        date = gps.date.day();
        month = gps.date.month();
        year = gps.date.year();
        if (date < 10)
          date_str = '0';
        date_str += String(date);// values of date,month and year are stored in a string
        date_str += " / ";

        if (month < 10)
          date_str += '0';
        date_str += String(month); // values of date,month and year are stored in a string
        date_str += " / ";
        if (year < 10)
          date_str += '0';
        date_str += String(year); // values of date,month and year are stored in a string
      }
      if (gps.time.isValid())  //check whether gps time is valid
      {
        time_str = "";
        hour = gps.time.hour();
        minute = gps.time.minute();
        second = gps.time.second();
        minute = (minute + 30); // converting to IST
        if (minute > 59)
        {
          minute = minute - 60;
          hour = hour + 1;
        }
        hour = (hour + 5) ;
        if (hour > 23)
          hour = hour - 24;   // converting to IST
        if (hour >= 12)  // checking whether AM or PM
          pm = 1;
        else
          pm = 0;
        hour = hour % 12;
        if (hour < 10)
          time_str = '0';
        time_str += String(hour); //values of hour,minute and time are stored in a string
        time_str += " : ";
        if (minute < 10)
          time_str += '0';
        time_str += String(minute); //values of hour,minute and time are stored in a string
        time_str += " : ";
        if (second < 10)
          time_str += '0';
        time_str += String(second); //values of hour,minute and time are stored in a string
        if (pm == 1)
          time_str += " PM ";
        else
          time_str += " AM ";
      }
    }
 
 WiFiClient client = server.available(); // Check if a client has connected
  if (!client)
  {
    return;
  }
  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n <!DOCTYPE html> <html> <head> <title>GPS DATA</title> <style>";
  s += "a:link {background-color: YELLOW;text-decoration: none;}";
  s += "table, th, td </style> </head> <body> <h1  style=";
  s += "font-size:300%;";
  s += " ALIGN=CENTER> GPS DATA **IoTbyHVM.OOO**</h1>";
  s += "<p ALIGN=CENTER style=""font-size:150%;""";
  s += "> <b>Location Details</b></p> <table ALIGN=CENTER style=";
  s += "width:50%";
  s += "> <tr> <th>Latitude</th>";
  s += "<td ALIGN=CENTER >";
  s += lat_str;
  s += "</td> </tr> <tr> <th>Longitude</th> <td ALIGN=CENTER >";
  s += lng_str;
  s += "</td> </tr> <tr>  <th>Date</th> <td ALIGN=CENTER >";
  s += date_str;
  s += "</td></tr> <tr> <th>Time</th> <td ALIGN=CENTER >";
  s += time_str;
  s += "</td>  </tr> </table> ";
 
  s += "</body> </html>

  client.print(s); // all the values are send to the webpage
  delay(100);
}

Recommended: Dynamic WLAN configuration for ESP32 Board | AutoConnect


ESP8266 Tutorials : How To Make ESP8266 as a MQTT Broker

First Download uMQTT Broker library from Github. Download Now.  Create new sketch and paste given below code.

/*
 * uMQTTBroker demo for Arduino
 * 
 * Minimal Demo: the program simply starts a broker and waits for any client to connect.
 */

#include 
#include "uMQTTBroker.h"

uMQTTBroker myBroker;

/*
 * Your WiFi config here
 */
char ssid[] = "iotbyhvm";      // Replace with your network SSID (name)
char pass[] = "asdf7890"; // Replace with your network password

/*
 * WiFi init stuff
 */
void startWiFiClient()
{
  Serial.println("Connecting to "+(String)ssid);
  WiFi.begin(ssid, pass);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  
  Serial.println("WiFi connected");
  Serial.println("IP address: " + WiFi.localIP().toString());
}

void startWiFiAP()
{
  WiFi.softAP(ssid, pass);
  Serial.println("AP started");
  Serial.println("IP address: " + WiFi.softAPIP().toString());
}

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.println();

  // Connect to a WiFi network
  startWiFiClient();

  // Or start the ESP as AP
//startWiFiAP();

  // Start the broker
  Serial.println("Starting MQTT broker");
  myBroker.init();
}

void loop()
{   
  // do anything here
  delay(1000);
}

Now connect your ESP8266 development board with your PC. Select Board and Port. Flash this code.Open Your Serial Monitor, Here you can found a IP address. this IP address is your MQTT Broker address.

If Serial Monitor is not displaying IP address then press RST button of ESP8266 Board.

What is uMQTTBroker ?

This is a MQTT Broker library for ESP8266 Arduino. You can start an MQTT broker in any ESP Arduino project. Just clone (or download the zip-file and extract it) into the libraries directory of your Arduino ESP8266 installation.

The broker does support:

  • MQTT protocoll versions v3.1 and v3.1.1 simultaniously
  • a smaller number of clients (at least 8 have been tested, memory is the issue)
  • retained messages
  • LWT
  • QoS level 0
  • username/password authentication

The broker does not yet support:

  • QoS levels other than 0
  • many TCP(=MQTT) clients
  • non-clear sessions
  • TLS

For API information Visit this: https://github.com/martin-ger/uMQTTBroker


If you are searching for a complete ready-to-run MQTT broker for the ESP8266 with additional features (persistent configuration, scripting support and much more) have a look at https://github.com/martin-ger/esp_mqtt .

esp_uMQTT_broker

This is a MQTT Broker/Client with scripting support on the ESP8266. This program enables the ESP8266 to become the central node in a small distributed IoT system. It implements an MQTT Broker and a simple scripted rule engine with event/action statements that links together the MQTT sensors and actors. It can act as STA, as AP, or as both and it can connect to another MQTT broker (i.e. in the cloud). Here it can also be bridge that forwards and rewrites topics in both directions. Also it can parse JSON structures, send basic HTTP GET requests and do basic I/O: i.e. read and write to local GPIO pins, react on timers and GPIO interrupts, drive GPIO pins with PWM, and read the ADC.


ESP8266 Tutorials : How To Use Grove-LCD RGB Backlight with NodeMCU

This Grove-LCD RGB Backlight enables you to set the color to whatever you like via the simple and concise Grove interface. It takes I2C as communication method with your microcontroller. So number of pins required for data exchange and backlight control shrinks from ~10 to 2, relieving IOs for other challenging tasks. Besides, Grove – LCD RGB Backlight supports user-defined characters. Want to get a love heart or some other foreign characters?

Features

  • RGB Backlight
  • I2C communication
  • Built-in English fonts
  • 16×2 LCD

Specification

Item Value
Input Voltage 5V
Operating Current <60mA
CGROM 10880 bit
CGRAM 64×8 bit
LCD I2C Address 0X3E
RGB I2C Address 0X62

 

  • Open Arduino IDE.
  •  Download the Grove-LCD RGB Backlight Library from Github.
  •  Since you have downloaded the zip Library, open your Arduino IDE, click on Sketch > Include Library > Add .ZIP Library
  • Here are 12 examples in the library as below.
    • Autoscroll
    • Blink
    • Cursor
    • CustomCharacter
    • Display
    • fade
    • HelloWorld
    • Scroll
    • SerialDisplay
    • setColor
    • setCursor
    • TextDirection
  • Please follow below picture to select example HelloWorld and upload the arduino.

 ESP8266 Tutorials

Here is the code of HelloWorld.ino.

#include <Wire.h>
#include "rgb_lcd.h"

rgb_lcd lcd;

const int colorR = 255;
const int colorG = 0;
const int colorB = 0;

void setup() 
{
    // set up the LCD's number of columns and rows:
    lcd.begin(16, 2);

    lcd.setRGB(colorR, colorG, colorB);

    // Print a message to the LCD.
    lcd.print("hello, world!");

    delay(1000);
}

void loop() 
{
    // set the cursor to column 0, line 1
    // (note: line 1 is the second row, since counting begins with 0):
    lcd.setCursor(0, 1);
    // print the number of seconds since reset:
    lcd.print(millis()/1000);

    delay(100);
}
  • We will see the hello world on LCD.

Pin Connection

 ESP8266 Tutorials

Use Vin Pin for Power supply to Grove LCD RGB Backlight. Because Grove LCD RGB Backlight needs 5V power supply.

Video Player


ESP8266 Tutorials : Controlled LED by Google voice assistant

In this ESP8266 tutorial we learn How To Controlled LED by Google voice assistant with help of Adafruit IoT Platform and IFTTT.  Adafruit Industries is an open-source hardware company based in New York City. IFTTT is a free platform that helps you do more with all your apps and devices

Adafruit was founded in 2005 by MIT hacker & engineer, Limor “Ladyada” Fried. Her goal was to create the best place online for learning electronics and making the best designed products for makers of all ages and skill levels. Adafruit has grown to over 100+ employees in the heart of NYC with a 50,000+ sq ft. factory. Adafruit has expanded offerings to include tools, equipment, and electronics that Limor personally selects, tests, and approves before going in to the Adafruit store. Adafruit is a 100% woman owned company. –By Adafruit.com

IFTTT is the free way to get all your apps and devices talking to each other. Not everything on the internet plays nice, so we’re on a mission to build a more connected world.

Controlled LED by Google voice assistant

Things used in this tutorial

  • NODEMCU -ESP8266
  • White LED bulb
  • Two Connecting wires

1 – Setup Adafruit IO account

Visit https://io.adafruit.com and sign up. Now create a Feed and dashboard. You can give any name for feed and dashboard.

Click on dashboard and create a new block by clink on plus sign button for configuration. Select a toggle and select feed what you create. Now click on next step. Here you can give any name for block, fill ON in the button on text and fill OFF in the button off text.

Note your AIO key, username and feed name for Led Program.

2 – Arduino Sktech

Flash this code in ESP8266 help of Arduino IDE.

#include "Adafruit_MQTT.h" // Adafruit APIs for MQTT server talks
#include "Adafruit_MQTT_Client.h" // Board Specification APIs are defined inside this one
#include <ESP8266WiFi.h>

WiFiClient client1;
/*------------------------------------------------------------
* Arguments:
* 1. Address of WiFiClient Object
* 2. Port Address : 1883 or 8883
* 3. Username of the Adafruit A/c (String)
* 4. API Key value from the A/c (String)
*-------------------------------------------------------------*/
char NAME[]="Your adafruit username";    // replace
char API_KEY[]=" Your AIO key";               // repalce
char URL[]="io.adafruit.com";
Adafruit_MQTT_Client mqtt(&client1,URL,1883,NAME,API_KEY);

/*-----------------------------------------------------------
* Arguments
* 1. Address of the Adafruit_MQTT_Client
* 2. Adafruit Username
* 3. link of the 'Feeds' we have cretaed in Adafruit
* 4. MQTT_QoS_0/1/2 => Quality of Service (Optional)
*------------------------------------------------------------*/
Adafruit_MQTT_Publish mypub=Adafruit_MQTT_Publish(&mqtt,"ADAfruitusername/feeds/adafruitfeedname");   //replace

Adafruit_MQTT_Subscribe mysub=Adafruit_MQTT_Subscribe(&mqtt,"DAfruitusername/feeds/adafruitfeedname");  //replace

void setup() {
// put your setup code here, to run once:
pinMode(D0,OUTPUT);

WiFi.begin("wifi hotspot name","password");    //replace
Serial.begin(115200);

while(WiFi.status() != WL_CONNECTED)
{
Serial.println("Connecting");
delay(1000);
}

Serial.println(LED_BUILTIN);
/*--------------------------------------------------------------
* String Pool Note
* Serail.println(F("")) will be stored in Flash memory
*/

//Printg the Local IP
Serial.println(WiFi.localIP());

//Subcsribe to topic Feed
mqtt.subscribe(&mysub);

mqtt.connect();
}

void loop() {
// put your main code here, to run repeatedly:

if(mqtt.connected())
{
/*---------------------------------------------------------
* publisher code:
* 5 Max subscription
* To change goto HEader file
* "#define MAXSUBSCRIBE 5"
*/
Serial.println("MQTT Connected");
}
else if(mqtt.connect()==0)
{
Serial.println("Connecting to the MQTT....");
}
Serial.println("MQTT Connected");
//mypub.publish("hi");
Adafruit_MQTT_Subscribe *sub;
while(sub=mqtt.readSubscription(5000))
{
if(sub==&mysub)
{
if(strcmp((char *)mysub.lastread,"ON")==0)
{

Serial.println("LED is on");
Serial.println((char*)mysub.lastread);
digitalWrite(D0,HIGH);
}
else
{
Serial.println("LED off");
analogWrite(D0,LOW);
}
}
}
Serial.println(".");
delay(1000);
}

3 – Setup IFTTT App

Download IFTTT android app and create two applets. First applet for ON LED and second applet for OFF LED. Open IFTTT app and select google voice assistant and adafruit for creating applet. Remember – write ON in the DATA TO SAVE field in adafruit section.

Circuit diagram

 ESP8266 TutorialsNow You can control LED bulb by Google voice assistant using your smartphone.

You may also like : What Are 10k Resistors and Their Advantages?


I hope you like this post “ESP8266 Tutorials ”. Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin