You are on page 1of 141

Table of Contents

INTRODUCTION
ESP8266 application subject
General Purpose IO
ESP8266 Modules:
Flashing ESP8266 or Nodemcu with latest lua firmware
Getting Started With ESPlorer
Nodemcu API for Lua
GPIO API
gpio.mode()
gpio.read():
gpio.write()
gpio.trig()
ADC API
adc.read() :
Bit API
Node API
FILE API
Wi-Fi API
wifi.getchannel()
wifi.setmode()
wifi.getmode()
wifi.setphymode()
wifi.getphymode()
wifi.sleeptype()
wifi.sta.config()
wifi.sta.connect()
Wifi.sta.disconnect()
wifi.sta.getbroadcast()
wifi.sta.getconfig()
wifi.sta.gethostname()
wifi.sta.getip()
wifi.sta.getmac()
Wifi.sta.sethostname()
wifi.sta.setip()
wifi.sta.setmac()
wifi.sta.status()
wifi.ap.config()
wifi.ap.getbroadcast()
wifi.ap.getclient()
wifi.ap.getip()
wifi.ap.getmac()
wifi.ap.setip()
wifi.ap.setmac()
wifi.ap.dhcip.config()
wifi.ap.dhcp.start()
wifi.ap.dhcp.stop()
Timer API
tmr.alarm()
tmr.delay()
tmr.interval()
tmr.now()
tmr.time()
tmr.wdclr()
tmr.unregister()
tmr.stop()
tmr.register()
tmr.softwd()
tmr.state()
tmr.start()
PWM API
pwm.setup()
pwm.start()
pwm.stop()
pwm.setduty()
NET API
Constants
net.createConnection()
net.createServer()
net.server.close()
net.server.listen()
net.socket.close()
net.socket.connect()
Net.socket.dns()
net.socket.on()
net.socket.send()
net.dns.resolve()
net.dns.setdnsserver()
HTTP API
http.delete()
http.get()
http.post()
http.put()
http.request()
Turn On and OFF an LED
Working with LED
Blink an LED
Using the PWM function for the LED
RGB LED with NodeMCU
Connect to WiFi Router
Simple Web Server
Blink LED through Web Server
Control Electrical devices from Webserver
Temperature and Humidity Sensor support in NodeMCU
DHT API
Sensors Data To Thingspeak
Working with I2C device.
I2C API
i2c.address()
i2c.read()
i2c.setup()
i2c.start()
i2c.write()
I2C Temperature and Pressure Sensor
Temperature and Pressure Sensor Web server
Lua basics
Variables
Numbers
Strings
Boolean
nil
Operators/ conditionals
If statements
Loops
While loop
For loop
Functions
Getting Started on OSX (solution by NodeMCU)
Port Forwarding Example
Building Custom Firmware for NodeMCU
Components Need for this book
Contact
 

INTRODUCTION
The ESP8266 is a highly integrated chip designed by Espressif Systems for the needs of an
increasingly demand for low cost IOT solutions. The manufacturer advertises it offers a
complete and self-contained Wi-Fi networking solution, allowing it to either host applications
or offload all Wi-Fi networking functions from another application processor.
The ESP8266 has powerful on-board processing and storage capabilities that allow it to be
used with sensor and other application specific devices through it GPIOs with minimal
development up-front and minimal loading during runtime. Its high degree of on-chip
integration allows for minimal external circuitry. The entire solution, including the modules, is
designed to occupy minimal PCB area.
The ESP8266 was originally marketed as a low cost add-on to Arduino boards which was in
need of such devices to connect to external world, when people started to work the low cost
chip with arduino they realised that they can eliminate the Arduino boards and understand this
chip can be used as a stand-alone device. In less than a year, the ESP8266 has rocketed in
popularity, and is now so well supported and developed.
Technical Features
•              802.11 b/g/n
•              WiFi Direct (P2P), soft-AP
•              Integrated TCP/IP protocol stack
•              Integrated TR switch, balun, LNA, power amplifier and matching network
•              Integrated PLLs, regulators, DCXO and power management units
•              +19.5dBm output power in 802.11b mode
•              Power down leakage current of <10uA
•              Integrated low power 32-bit CPU could be used as application processor
•              SDIO 1.1/2.0, SPI, UART
•              STBC, 1×1 MIMO, 2×1 MIMO
•              A-MPDU & A-MSDU aggregation & 0.4ms guard interval
•              Wake up and transmit packets in < 2ms
•              Standby power consumption of < 1.0mW (DTIM3)
•              Operating temperature range -40C ~ 125C.
The ESP8266 chip should be powered by a 3.3V Power supply, it can consume 10uA to
170mA, the vast difference can be explained, when transmitting at full power, it can consume
170mA but when in a deep sleep, it only need 10uA. That is a difference between current
consumption. This means that the runtime of an ESP8266 on a fixed current reservoir is not
just a function of time but also of what it is doing during that time and it depend upon on the
function it is going to do during the run time of the device.
ESP8266 can be used as an external Wi-Fi module, using the standard AT command set
Firmware by connecting it to any microcontroller using the serial UART, or directly serves as
a Wi-Fi enabled microcontroller, by programming a new firmware using the SDK.  The
ESP8266 is designed to be used with a partner memory module and this is most commonly
flash memory. Most of the modules come with some flash associated with them.
ESP8266 application subject
            Smart Power Plug
            Home Automation

            mesh network

            industrial wireless control

            Baby Monitor

            Network Camera

            sensor networks

            wearable electronics

            wireless location-aware devices

            Security ID tag

            wireless positioning system signals

 
General Purpose IO
A total of up to 16 GPIO pins. The firmware can assign them different functions. Each GPIO
can be configured internal pullup / pulldown resistors available software registers sampled
input, triggering edge or level CPU interrupt input, trigger level wake-up interrupt input,
open-drain or complementary push-pull output drivers, software register output source or
sigma-delta PWM DAC. These pins are multiplexed with other functions, such as the main
interface, UART, SI, Bluetooth co-existence and so on.
 
ESP8266 Modules:
However the first introduced board which not much breadboard friendly integrated circuit
comes in a small package. Obviously, unless you are a master in soldering you are not going
to do much with that. The good news is ESP8266-based boards are available from several
vendors with different breakout boards that make the job much easier for us. Here is the list of
some of the more common modules.

 
ESP-01

 
This is the first and simplest board using the ESP8266. It allows attaching serial lines, and
only breaks out two GPIO pins for native usage. This is also the cheapest and can be
purchased from many Chinese suppliers at $2
ESP-12
The current most popular and hot topic is the ESP-12 which has flexible configuration
available today. It exposes the most GPIO pins for use. The basic ESP-12 module really needs
its own expander module to make it breadboard and 0.1” strip board friendly. If you are
currently using Arduino, you need to stand up and take note. Buy a ESP8266 12 based Wi-Fi
module, I have used a board called NodeMCU development board, which has an on board
ESP8266 and everything we need to get started with awesome Wi-Fi chip, this board
eliminates the need to have external USB serialconvertor to connect with your PC or Laptop
to program it and also comes with on board 3.3v Voltage regulator.

There are many ESP 12 development kit available on the market, some of the other
development board from popular vendors are listed below.
Adafruit HUZZAH ESP8266 breakout

The Adafruit Huzzah is a breakout board for the ESP8266. This was designed to make
working with ESP8266 chip super easy. This device comes with an on-board antenna, and
plenty of pins.
Wemos D1
This board is like arduino breakout board for ESP8266, which looks like an Arduino and it
has got everything to get start with. The arduino like feature allows the user to use this board
easily; this board has the entire pin marking as Nodemcu boards. Behind the board we can
find the real GPIO pin number which makes very easy to use this board with any compiler for
programming.
I have used Nodemcu development kit for the experiments that done in this book, let’s get into
deeper with this board, you can also use any other vendor board, I highly recommend for the
novice user to get start with development board, instead of generic chips, where the generic
chips needs proper regulated voltage and it also requires a USB programmer to upload the
program into its memory.
Pin Definition of Nodemcu Development kit
 
 
 
 
 
 
 
 
 
 
 
 
Nodemcu Development kit circuit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 
Flashing ESP8266 or Nodemcu with latest lua firmware
Step 1: open your web browser and type https://github.com/nodemcu/nodemcu-
firmware/releases or click on the link.

Step 2: Click on the firmware links to download, download both the firmware wire.

Step 3: download lua IDE from the link here , for this tutorial we going to use ESPlorer one of
the stable version for uploading lua files to ESP8266 chips, there are other lua loaders
available which are limited to windows or still in development, as the ESPlorer is not a great
IDE but it is most suitable for learning lua programming with ESP8266 devices.
Step 4: Extract the Nodemcu Flasher which downloaded in the first step, if you have yet to
download, download it first before proceeding with this tutorial.

Step 5: Connect your Nodemcu or ESP8266 to your laptop or PC, if you are using a generic
ESP8266 device you need to connected with FTDI USB to serial adapter or any other USB to
serial adapter devices, if you are a beginner it is not advisable to use a generic module as it
may frustrate some beginner if they want to quick start with this device.
Step 6: Open the extracted nodemcu-flasher-master file and select Win64 or Win32 based on
your system configuration, I use windows x64, and I choose the folder Win64, open ESP8266
Flasher.

Click on Config and click on the gear, and navigate to the bin file (lua latest firmware) that
you downloaded in the step 2,

In the step 2, we have downloaded 2 firmware one is float and another one is integer, select
the second one integer type and click open.
These two firmware should flash to the ESP8266 based on requirement , if you use Float
firmware DHT library will not work with ESP8266 device, that’s the reason we are choosing
the integer type later on tutorials we will use the device with DHT sensor and read
temperature and humidity data.
 
Check on the Config tab, correct firmware has selected or not, if the firmware path is correct it
will display in green color else the color would turn to red.
On the advance tab restore it to default and don’t change it unnecessary
Step 7: Click on the Operation tab and select the correct COM port, if you have connected
only one device it will automatically detect the COM port if there are any devices connected
to your computer make sure to select the correct COM port, if you are not sure about which
COM port your device is currently connected, right click on the My computer icon and select
properties, choose device manager and click on ports, it will display the available or currently
connected devices to your computer.

 
Click on Flash in the Operation tab, after you make sure that you selected correct COM port in
the ESP8266 flasher.

Once you hit the flash button in the Operation tab your ESP8266 Flasher will start to upload
the firmware to your Nodemcu device, you see this by checking the progress bar in your
ESP8266 Flasher screen.

Click on the log file and make sure you have successfully uploaded the firmware, and you can
also see a green color check arrow to indicate the successful upload of the firmware, if there is
a problem when uploading the firmware check the log file and check the reason for uploading
failed, mostly this problem occurs when the ESP8266 device not responding when uploading
firmware you can disconnect and reconnect the device and try to upload the firmware again, if
still the problem continues check your device as it may have fault. If you are using generic
type and getting problem when you upload your firmware, make sure you are power supply is
providing enough power and not oscillating.

Getting Started With ESPlorer


The ESPlorer is an IDE ESP8266 devices. It’s a multiplatform IDE can be used in any
environment it is not developed for a target system as it was created in JAVA, this simply
means that it runs on Windows, Mac OS X or Linux.
Supported platforms:
Windows(x86, x86-64)
Linux(x86, x86-64, ARM soft & hard float)
Solaris(x86, x86-64)
Mac OS X(x86, x86-64, PPC, PPC64)
This software allows you to establish a serial communications with your ESP8266, send
commands, and upload code and much more.

Extract the files that you have downloaded previously and open Esplorere.jar file. If you are
using MAC or linux type the following command in your terminal to run ESPlorer.
Sudo java –jar Esplorer.jar
As the ESPlorer Ide created using JAVA it requires a java run time environment for working,
if you have not installed JAVA on your computer, downloaded it and run the ESPlorer IDE, in
some cases the jar files will be opened with the WinRAR, in such cases you need to change
some settings in your computer.
Method 1:
Go to your control panel and select default programs, and click associate a file type or
protocol with specific a specific program and wait for the programs to get loaded in the
window.

Navigate to .jar and select change program and choose java from there.
 
 
Method 2:
Open your WinRAR, and select options and click on settings.

On the setting, click on the Integration tab and uncheck JAR in the Associate WinRAR with.

 
 
 
 
ESPlorer IDE overview
When you first open the ESPlorer IDE, it looks exactly shown below.
On the top right of ESP8266 choose Nodemcu+MicroPython tab, as we going to use lua
program we need to choose this section when communicating with ESP8266 device or
Nodemcu dev kit. Under Nodemcu+MicroPython tab there are many sub tabs you can see,
Scripts tab is the place where all the Programming are done, program can be opened, save and
close using the functions available in the Scripts tab.
Next to this Main tab on the Left side you can see functions which enable serial
communication between Nodemcu dev kit and the IDE.
This functions allow to choose COM port of
the ESP8266 device that is currently connected
to your computer, after selecting the Com port ,
Open button helps to establish communication
with the ESP8266 device that is associated
with the selected COM port, baud rate can also
be choose by selecting the drop down button available next to the Open button.

The window below the above functions tab is exactly work as the serial monitor, which helps
to visibly check communication with ESP8266 devices, display the output result and also
show the error if there is any during the execution of program.

Nodemcu API for Lua


GPIO API
This GPIO(General Purpose Input/Output) allows us to access to pins of ESP8266 , all the
pins of ESP8266 accessed using the command GPIO, all the access is based on the I/O index
number on the NoddMCU dev kits, not the internal GPIO pin, for example, the pin ‘D7’ on
the NodeMCU dev kit is mapped to the internal GPIO pin 13, if you want to turn ‘High’ or
‘Low’ that particular pin you need to called the pin number ‘7’ no the internal GPIO of the
pin. When you are programming with generic ESP8266 these confusion will arise which pin
needs to be called during programming, if you are using NodeMCU dev kit, it has come
prepared for working with Lua interpreter which can easily program by looking the pin names
associated on the lua board.
If you are using generic ESP8266 device or any other vendor boards please refer to the table
below to know which IO index is associated to the internal GPIO of ESP8266.
Nodemcu dev kit ESP8266 Pin Nodemcu dev kit ESP8266 Pin
D0 GPIO16 D7 GPIO13
D1 GPIO5 D8 GPIO15
D2 GPIO4 D9 GPIO3
D3 GPIO0 D10 GPIO1
D4 GPIO2 D11 GPIO9
D5 GPIO14 D12 GPIO10
D6 GPIO12    
 
D0 or GPIO16 can be used only as a read and write pin, no other options like PWM/I2C are
supported by this pin.
gpio.mode() : This command will initialize the GPIO mode and also used for setting the
input/output direction of the pin
Syntax :  gpio.mode(pin, mode)
Pin : select any of the available gpio pins
Mode: set the selected pin mode to input or output.
Example:  gpio.mode(7, gpio.OUTPUT)
 
gpio.read(): This command will read the pin value, whether the pin is in High state or Low
state will be returned when use this command.
Syntax: gpio.read(pin)
On the function type the pin number to read, this will return a number based on the High or
Low on the pin side, if the pin is in high state this will return 1 and if it is low state this will
return 0.
Example: gpio.read(7)
gpio.write() : This command will makes the pin to go High or Low, we use this command to
set a pin to go High or Low, if you want to turn on and off an LED this command can be
used in such situations.
Syntax: gpio.write(pin, state)
Pin : enter the pin that you want to change the state to high or Low
State: High or Low, gpio.HIGH or gpio.LOW
Example:
              pin = 7
              gpio.mode(pin, gpio.OUTPUT)
              gpio.write(pin, gpio.HIGH)
above program will set the D7 pin of Nodemcu to go High, on the first line pin is assigned to
variable 7, and on the second line ‘D7’ pin as set to Output and on the third line ‘D7’ pin has
made to HIGH which will write value 1 to the pin, which will make to to glow if you
connect a LED to the pin ‘D7’,
 
gpio.trig() : This command act as interrupt function during programming, using this
command can cause the program to execute certain function when the particular pin is
triggered , this function will not be available if GPIO_INTERRPUT_ENABLE was
undefined at the time of compile.
Syntax:  gpio.trig(pin, type [, function(level)])
Choose pin 1 to 12, as the pin D0 or GPIO16 is not support interrupt or any other function.
Type: “up”, “down”, “both”, “low”, “high” which represent rising edge, falling edge, both
edge, low level, high level trigger mode, if you want to choose the interrupt to occur when
the pin goes low, you should choose low as type, which means the pin will be actively high,
when the pin goes to low state it should stop the function and call the function to execute
during interrupt.
Function(level) callback function when triggered.
Example:
              local pin = 5   
function pinValue ()
    print('The pin value'..gpio.read(pin))
end
gpio.mode(pin, gpio.INT)
gpio.trig(pin, 'HIGH', pinValue)
The above example will return the pin value if the pin ‘D5’ goes high, for example if you
connected a push button to the pin ‘D7’, and whenever you push the pushbutton, program will
call the function pinValue, the pinValue function executes the current value of the PIN 5, so it
will return the value as ‘1’ on the serial monitor.
ADC API
              ADC API provides access to the inbuilt ADC, ESP-12 has an inbuilt ADC pin, only
pin is available and it is not much stable with the Generic ESP-12, you should also aware that
it can read only upto 1v. if you are using Generic ESP devices you should use voltage divider
in order to make it work, NodeMCU has inbuilt voltage divider for the ADC pin and we can
connected analog devices directly to this device.
The ESP8266 v7 and v12 include an ADC( analog to digital converter)pin. This means that
the ESP8266 module can process inputs from analog sensors. Light sensors, analog
temperature sensors, force sensor, sound sensors etc,. can be interfaced with ESP8266 but the
disadvantage is that it can support only one ADC which means only one analog pin is
available in ESP8266 v12 and Nodemcu. The ADC pin is having 10 bit resolution, which can
read 0 to 1024, you will get a value somewhere within this range. The ADC pin only reads
upto 1V only. Any reading over that, say 1.1V to Vcc of 3.3V will be maxed out to 1024.
The Nodemcu has inbuilt voltage divider that has connected to A0 pin, which means any pin
connected to this will be corrected automatically we don't need to provide any voltage divider
or any other resistor but if you are using any other ESP8266 make sure which has inbuilt
voltage divider or you need to make an voltage divider to make this example to work with
your ESP8266.

For R1, I used a 220R and for R2, I used 100R resistors. On my voltmeter the actual
resistance was 225 and 103.7 respectfully. The math indicates that 220R and 100R should
divide 3.3v to 1.03v. 225R and 103.7 should be ~1.04v. All very close. On the breadboard, my
voltmeter is reading .98v. This relationship should hold true for 22R and 10R as well as 20K
and 10K. However, caution! The small ones heat up.
adc.read() : samples the ADC.
Syntax : adc.read(channel)
There is only one channel available with esp devices so always choose 0, may in future
device we can expect more ADC with ESP chips. This will return the sampled value in
number.
Example :   val = adc.read(0)
Bit API
NodeMCU supports Bit manipulation on 32bit integers.
bit.arshift() , bit.rshift(), bit.lshift()
Returns either the bitwise logical left-shift, bitwise logical right-shift, or bitwisearithmetic
right-shift of its first argument by the number of bits given by the second argument.
Logical shifts treat the first argument as an unsigned number and shift in 0-bits. Arithmetic
right-shift treats the most-significant bit as a sign bit and replicates it.

Only the lower 5 bits of the shift count are used (reduces to the range [0..31]).
Syntax: bit.arshift(value,shift)
Enter value to shift and how many positions to shift, it returns the number shifted right
(arithmetically)
Syntax: bit.rshift(value,shift)
Enter a value to shift and how many positons to shift, it returns the number shifted right
(logically)
Syntax: bit.lshift(value,shift)
Enter a value to shift and how many positions to shift, it returns the number shifted to left.
Example:
print(bit.lshift(1, 0))               1
print(bit.lshift(1, 8))               256
print(bit.lshift(1, 40))              256
print(bit.rshift(256, 8))             1
print(bit.rshift(-256, 8))            16777215
print(bit.arshift(256, 8))            1
print(bit.arshift(-256, 8))           -1
printx(bit.lshift(0x87654321, 12))    0x54321000
printx(bit.rshift(0x87654321, 12))    0x00087654
printx(bit.arshift(0x87654321, 12))   0xfff87654
 
bit.band(), bit.bor(), bit.bxor()
Returns either the bitwise or, bitwise and, or bitwise xor of all of its arguments. Note that
more than two arguments are allowed.
Syntax : bit.band(val1, val2 [,……valn])
Val1 is the first AND argument Val2 is the Second AND argument and Valn is the Nth AND
argument, this will return the bitwise AND of all the arguments in number.
Syntax: bit.bor(val1, val2 [,….valn])
Val1 is the first OR argument Val2 is the Second OR argument and Valn is the Nth OR
argument, this will return the bitwise OR of all the arguments in number.
Syntax: bit.bxor(val1, val2 [,….valn])
Val1 is the first XOR argument Val2 is the Second XOR argument and Valn is the Nth XOR
argument, this will return the bitwise XOR of all the arguments in number.
Example:
              print(bit.bor(1, 2, 4, 8))                15
printx(bit.band(0x12345678, 0xff))        0x00000078
printx(bit.bxor(0xa5a5f0f0, 0xaa55ff00))   0x0ff00ff0
 
bit.bit()
Generate a number with a 1 bit (used for mask generation).
Syntax: bit.bit(position)
Example:
              bit.bit(3)           0x00000008
bit.clear()
Clear bits in a number
Syntax: bit.clear(value, pos1, pos2, …. posn)
Value is the base number and pos1 is the first bit to clear and posn is the nth bit to clear and
this will return the number with the bits cleared in the given positions.
V1 = 0x000000ff
bit.clear(V1, 4, 5, 6, 7)      0x000000f
bit.isset() : This function will test if a given bit is set or not.
Syntax: bit.isset(value, position)
The value is to test the bit position. This will returns true if the bit at the given position is 0,
else it will return as false if the bit at the position is non zero.
V1 = 0x000000ff
bit.clear(V1, 1)   result: true
Node API
              Node API’s allow the user to provide access to system level features such as restart,
sleep and ID’s, which include ESP chip ID, flash chip ID.
node.bootreason()
              This functions inspect boot cause and returns the boot reason and extended rest info.
When you call this function this will return the raw code and the values are
Value Reset Information
1 Power-On
2 Reset (software)
3 Hardware reset via reset pin
4 WDT reset (watchdog timeout)
 
Second value returned is the extended reset cause and the values are given below:
Value Reset Information
1 Power on
2 Hardware watchdog reset
3 Exception reset
4 Software watchdog reset
5 Wake from deep sleep
6 External reset.
 
In general, the extended reset cause supercedes the raw code. The raw code is kept for
backwards compatibility only. For new applications it is highly recommended to use the
extended reset cause instead.
In case of extended reset cause 3 (exception reset), additional values are returned containing
the crash information. These are, in order, EXCCAUSE, EPC1, EPC2, EPC3, EXCVADDR,
and DEPC.
Syntax : node.bootreason()
It returns rawcode, reason [, exccause, epc1, epc2, epc3, excvaddr, depc]
Example:
flag=node.bootreason()

print("reasonis:")

print(flag)
 
This added to the firmware developed in the date 2015-06-27, Make sure you have firmware
which supports this function.
 
 
node.chipid()
This function returns the chip id, when you call this function in the program it will store the
chip id.
Syntax: node.chipid()
Example:
Chipid = node.chipid()
Print(“ chip id:”..Chipid)
node.compile()
This functions compiles a Lua text file into Lua bytecode, and it also saves it as .lc file
extension.
Syntax: node.compile(“filename.lua”)
The filename should be the name that you saved your Lua file.
Example:
file.open(“Myfile.lua”, “w+”)
file.writeline([[print( “Nodemcu”)]])
file.writeline([[print(node.heap())]])
file.close()
node.compile(“Myfile.lua”)
dofile(“Myfile.lua”)
dofile(“Myfile.lc”)
Above example will create file called Myfile.lua in the file “Nodemcu” will be written and in
the next line it returns the heap size or the balance memory in your NodeMCU dev or
ESP8266 device, and the file will be closed.
node.compile command open the file name Myfile.lua and compiles the file and save the file
in the .lc extension format.
node.dsleep()
The above function will make the ESP8266 device to enter into deep sleep mode till the
device timed out. Maximum sleep time for the device is 70 minutes, you cannot extended the
time limit as it was the limitation in the software , if you have older Firmware the maximum
sleep is less than 35.
This function can use in ESP device when it meet certain conditions, esp8266 PIN (RST) and
PIN8 (GPIO16) should connected together. Using sleep (0) will make the device to set no
wake up timer, connect a GPIO to pin RST, the chip will wake up by falling-edge on the RST
pin. You should follow these steps for proper working of this function.
Syntax: node.dsleep(us, option)
us is the sleep time in microsecond, if us == 0, it will sleep forever, if us ==nil, will not set
sleep time.
Example:
-- sleep time is 10s
    sleep_time = 10 * 1000 * 1000
 
    -- Do not forget to connect PIN32 and PIN8
    node.dsleep(sleep_time);
0, init data byte 108 is valuable
> 0, init data byte 108 is valueless
0, RF_CAL or not after deep-sleep wake up, depends on init data byte 108
1, RF_CAL after deep-sleep wake up, there will be large current
2, no RF_CAL after deep-sleep wake up, there will only be small current
4, disable RF after deep-sleep wake up, just like modem sleep, there will be the smallest
current
node.heap()
              This function returns the current available heap size in bytes, this will not return
exact heap size due to fragmentation and actual allocation due to this this will return data but
it should not take it as an exact required information.
Syntax: node.heap()
 
node.flashid()
              This function returns the ID of the flash chip.
Syntax: node.flashid()
 
node.info()
              This function returns firmware version, chipid, flashid, flash size, flash mode and
flash speed.
Syntax: node.info()
 
 
node.restart()
This function allow the chip to restart
Syntax: node.restart()
 
node.setcpufreq()
This function will change the CPU working frequency.
Syntax: node.secpufreq(speed)
Speed should be constant either 80MHZ or 160MHZ, should be careful when changing this
function as it may affect the chip working behaviour during the execution of the program.
Example:
node.setcpufreq(node.CPU80MHZ)
                            or
node.setcupfreq(node.CPU160MHZ)
 
FILE API
File API provides access to the file system and its individual files, this allows user to create a
file inside a program and edit information on the file and save the file using file API, only one
file is possible to open at a time and it will not allow to access multiple files, the file system
follows a flat file system with no notion of directories or folders.
file.open()
This function allows to open any file in the system for editing or creating a new file, this
function access to all the existing files in the system, if we want to create any new file using
this function can only be done, for creating a new file , we need to open a file in write mode.
All the file.open() function must be closed with file.close function.
Syntax: file.open(filename, mode)
Filename, the file to be opened. There are different mode available to work on the files.
“r”: read mode (default mode in the file access)
“w”: write mode
“a” : append mode ( adding data to existing file)
“r+”: update mode. All previous data are preserved
“w+”: update mode, all previous data is erased
“a+”: append update mode, previous data is preserved, writing is only allowed at the end of
file.
              Example:
                                          file.open(“init.lua”, “r”)
                                          print(file.readline())
                                          file.close()
 
file.close()
              This function closes any of the opened file, this function should be used with the
function file.open() at the end.
Syntax: file.close()
 
file.flush()
Flushes any pending writes to the file system, ensuring no data is lost on a restart.
Syntax: file.flush()
Example:
              file.open(“script.lua”, “a+”)
              file.write(‘ hello’)
              file.flush()
              file.write(‘world’)
              file.close()
 
file.format()
              This function will erases all the existing files in the system and writes a new one,
depending on the size of the available flash chip in the ESP, it takes time depend on its flash
ID.
Syntax: file.format()
 
file.fsinfo()
This returns the file size information for the file system, in bytes.
Syntax: file.fsinfo()
 
 
file.list()
This function lists all the available files in the system.
Syntax: file.list()
 
file.write()
This function writes a string to the open file.
Syntax: file.write(string)
 
file.writeline()
This function will write a string to the opened file and append ‘\n’ at the end of the file which
will add a new line after append string.
Syntax: file.writeline(string)
Example:
              file.open(“newfile.lua”, “a+”)
              file.writeline(‘ this will add a new line at the end’)
              file.close()
 
file.seek()
This function sets and gets the file position,
Syntax: file.seek([whence[, offset]])
 
file.rename()
Renames a file, if the file to be changed to some other name this function is used for such
cases.
Syntax: file.rename(oldname, newname)
 
file.remove()
This functions allows us to remove a file from system, to do this the file that needs to
remove should not be currently opened as a file anywhere.
Syntax: file.remove(filename)
 
Wi-Fi API
Very important API’s available with NodeMCU firmware, this allows NodeMCU dev kit or
ESP8266 chips to connect with other devices and access information from internet and allow a
user to control a device from any part of the world, on chip Wi-Fi SoC is what made the ESP
most popular among hobbyist and it grows to phenomenal rate at this time.
wifi.getchannel()
This function gets current wifi channel that is currently connected. When this function called
in program this will return the wifi channel name.
Syntax: wifi.getchannel()
Example:
              print(wifi.getchannel())
 
wifi.setmode()
This function configures the Wi-Fi mode to use, NodeMCU can run in four different modes:
1)    Station mode, where the NodeMCU device joins an existing network
2)    Access point mode, where it creates its own network that other can join, it serves
as the Wi-Fi router for other devices.
3)    Station + Access point mode
4)    WiFi off
 
Syntax: wifisetmode(mode)
Mode value should one of the mode as follows
I)                   wifi.STATION this will mode set it to the first available mode,
that is station mode which allow the device connected to a WiFi router,
this mode is often used to access internet with ESP device.
II)                 wifi.SOFTAP this mode will set NodeMCU dev kit as an access
point.
III)              wifi.STATIONAP this mode is the combination of both 1 and 2.
When using the combined station + AP mode, the same channel will be
used for both networks as the radio can only listen on a single channel.
IV)             wifi.NULLMODE this mode will turn off WiFi.
 
wifi.getmode()
This function will gets wifi operation mode, this will make us to know which mode the wifi
has currently set to. Just above the screen you can see the number of available mode.
Syntax: wifi.getmode()
This will return as one of the following wifi.STATION, wifi.SOFTAP, wifi.STATIONAP or
wifi.NULLMODE constants.
 
wifi.setphymode()
This function will sets WiFi physical mode.
1)    wifi.PHYMODE_B 802.11b, more range, llow Transfer rate, more current draw
2)    wifi.PHYMODE_G 802.11g, medium range, medium transfer rate, medium current
draw
3)      wifi.PHYMODE_N 802.11n, least range, fast transfer rate, least current draw
(STATION ONLY) information from the Espressif datasheet v4.3
 
Parameters Typical Power Usage
Tx802.11b, CCK 11Mbps, P OUT= 170mA
+17dBm
Tx802.11g, OFDM 54Mbps, P OUT 140mA
= +15dBm
Tx802.11n, MCS7 65Mbps, P OUT 120mA
= +13dBm
Rx802.11b, 1024 bytes packet 50mA
length, -80dBm
Rx 802.11g, 1024 bytes packet 56 mA
length, - 70dBm
Rx802.11n, 1024 bytes packet 56mA
length, -65dBm
 
Syntax
              wifi.setphymode(mode)
Mode one of the following parameters below
1)    wifi.PHYMODE_B
2)    wifi.PHYMODE_G
3)    wifi.PHYMODE_N
 
wifi.getphymode()
This function returns WiFi physical mode that is currently set to the device.
Syntax: wifi.getpymode()
The above syntax will return wifi.PHYMODE_B, wifi.PHYMODE_G or
wifi.PHYMODE_N.
 
wifi.sleeptype()
This function configures the WiFi modem into sleep type.
Syntax: wifi.sleeptype(type_wanted)
Type wanted should be as follows
1)    wifi.NONE_SLEEP to keep the modem on at all times
2)      wifi.LIGHT_SLEEP to allow the modem to power down under some
circumstances.
3)    wifi.MODEM_SLEEP to power down the modem as much as possible.
 
wifi.sta.config()
This function sets the WiFi station configuration.
Syntax: wifi.sta.config(ssid, password[, auto[, bssid]])
Ssid is the name of WiFi router and the string name should be less than 32 bytes.
Password is the wifi router password which is 8-64 or 0 bytes. Empty string indicates an open
WiFi access point.
Auto value of 0 or 1 (default value is 1)
0 will disable auto connect and remain disconnected from access point.
1 will enable auto connect and connect to access point.
bssid this string contains the MAC address of the access point and it is not mandotary it is an
option to be used.
You can set BSSID if you have multiple access points with the same SSID.
Note: if you set BSSID for a specific SSID and would like to configure station to connect to
the same SSID only without the BSSID requirement, you MUST first configure to station to a
different SSID first, then connect to the desired SSID
The following formats are valid:
"DE-C1-A5-51-F1-ED"
"AC-1D-1C-B1-0B-22"
"DE AD BE EF 7A C0"
Examples:
--Connect to access point automatically when in range
wifi.sta.config("myssid", "password")
 
--Connect to Unsecured access point automatically when in range
wifi.sta.config("myssid", "")
 
--Connect to access point, User decides when to connect/disconnect to/from AP
wifi.sta.config("myssid", "mypassword", 0)
wifi.sta.connect()
-- ... do some WiFi stuff
wifi.sta.disconnect()
 
--Connect to specific access point automatically when in range
wifi.sta.config("myssid", "mypassword", "12:34:56:78:90:12")
 
--Connect to specific access point, User decides when to connect/disconnect to/from AP
wifi.sta.config("myssid", "mypassword", 0, "12:34:56:78:90:12")
wifi.sta.connect()
-- ... do some WiFi stuff
wifi.sta.disconnect()

 
wifi.sta.connect()
This functions connect to access point in station mode.
Syntax: wifi.sta.connect()
 
Wifi.sta.disconnect()
This function disconnect from access point in station mode.
Syntax: wifi.sta.disconnect()
 
wifi.sta.getbroadcast()
This function gets the broadcast address in station mode.
Syntax: wifi.sta.getbroadcast()
This will broadcast the address as string, for example “192.168.0.105”
 
wifi.sta.getconfig()
This function will gets the Wi-Fi station configuration.
Syntax: wifi.sta.getconfig()
When this function called in program this will return ssid, password, bssid_set, bssid, if
bssid_set is equal to 0 then bssid is irrelevant.
Example:
--Get current Station configuration
ssid, password, bssid_set, bssid=wifi.sta.getconfig()
print("\nCurrent Station configuration:\nSSID : "..ssid
.."\nPassword  : "..password
.."\nBSSID_set  : "..bssid_set
.."\nBSSID: "..bssid.."\n")
ssid, password, bssid_set, bssid=nil, nil, nil, nil

 
 
 
wifi.sta.gethostname()
This function will returns the currently connected hostname station.
Syntax: wifi.sta.gethostname()
When this function called in program, this will returns currently configured hostname.
Example:
print("Current hostname is: \""..wifi.sta.gethostname().."\"")

 
wifi.sta.getip()
This function will gets IP address, netmask, and gateway address in station mode.
Syntax: wifi.sta.getip()
Example:
-- print current IP address, netmask, gateway
print(wifi.sta.getip())
-- 192.168.0.111  255.255.255.0  192.168.0.1
ip = wifi.sta.getip()
print(ip)
-- 192.168.0.111
ip, nm = wifi.sta.getip()
print(nm)
-- 255.255.255.0

 
wifi.sta.getmac()
This function get mac address in station mode.
Syntax: wifi.sta.getmac()
The above syntax when called in program will returns MAC address as string.
 
Wifi.sta.sethostname()
This function will sets station hostname.
Syntax: wifi.sta.sethostname(hostname)
Hostname must only contain letters, numbers and hyphens('-') and be 32 characters or less
with first and last character being alphanumeric, and the function will return true if the
hostname has successfully set, else it will return false if the hostname was not succeed.
 
 
 
Example:
if (wifi.sta.sethostname("NodeMCU") == true) then
    print("hostname was successfully changed")
else
    print("hostname was not changed")
end

 
wifi.sta.setip()
This function sets IP address, netmask, gateway address in station mode, if this function has
not used wifi router will automatically set the IP address, netmask and gateway address, make
sure the assigning IP address is not using by any other device that has currently connected to
the router.
Syntax: wifi.sta.setip(cfg)
Cfg table contain IP address, netmask and gateway
{
ip= “192.168.0.100”
Netmask = “255.255.255.0”,
gateway = “192.168.0.1”
}
If the function is successful it returns true else it will return false.
 
wifi.sta.setmac()
This function sets MAC address in station mode.
Syntax: wifi.sta.setmac(mac)
MAC address should be in string, this function returns true if success else this will return
false if the address was not successfully assigned.
 
 
 
 
 
 
 
wifi.sta.status()
This function will get the current status in station mode.
Syntax: wifi.sta.status()
This will return the number 0-5.
0: STATION_IDLE
1: STATION_              CONNECTING
2: STATION_WRONG_PASSWORD
3: STATION_NO_AP_FOUND,
4: STATION_CONNECT_FAIL
5: STATION_GOT_IP.
 
wifi.ap.config()
This function will set SSID and password in Access Point mode, make sure to choose
password as 8 characters or more if you fail to do this, device will automatically set to default
mode where it will automatically assign SSID and password will be none.
Syntax: wifi.ap.config(cfg)
Ssid SSID chars should be 1-32 characters long.
Password should be more than 8 characters.
Authentication one of AUTH_OPEN, AUTH_WPA_PSK, AUTH_WPA2_PSK,
AUTH_WPA_WPA2_PSK,               default = AUTH_OPEN
Channel number 1-14 default = 6
Hidden, if it is 0 then not hidden, if it is 1 it is set to hidden by default it is set to 0.
Maximum number of connections 1-4 by default = 4.
Beacon interval time in range 100 – 60000, default = 100.
Example:
Cfg ={}
Cfg.ssid = “myssid”
Cfg.pwd = “mypassword”
Wifi.ap.config(cfg)
 
 
wifi.ap.getbroadcast()
This function will gets broadcast address in access point mode.
Syntax: wifi.ap.getbroadcast()
This function will return broadcast address in string .
Example:
broadcast = wifi.ap.getbroadccast()
print(broadcast)
 
wifi.ap.getclient()
This function will get table of clients connected to the NodeMCU dev kit when the kit act as
an Access point to other devices.
Syntax: wifi.ap.getclient()
Examples:
              table={}
table=wifi.ap.getclient()
for mac,ip in pairs(table) do
    print(mac,ip)
end
 
-- or shorter
for mac,ip in pairs(wifi.ap.getclient()) do
    print(mac,ip)
end

 
wifi.ap.getip()
This function will gets IP address, netmask and gateway in access point mode.
Syntax: wifi.ap.getip()
Example:
print current ip, netmask, gateway
print(wifi.ap.getip())
-- 192.168.4.1  255.255.255.0  192.168.4.1
ip = wifi.ap.getip()
print(ip)
-- 192.168.4.1
ip, nm = wifi.ap.getip()
print(nm)
-- 255.255.255.0
ip, nm, gw = wifi.ap.getip()
print(gw)
-- 192.168.4.1

 
wifi.ap.getmac()
This function will gets MAC address in access point mode.
Syntax: wifi.ap.getmac()
 
 
 
wifi.ap.setip()
This function will set IP address, gateway and netmask in access point mode.
Syntax: wifi.ap.setip(cfg)
 
wifi.ap.setmac()
This function will set MAC address in Access point mode.
Syntax: wifi.ap.setmac(mac)
 
wifi.ap.dhcip.config()
This function will configure the dhcp service.
Syntax: wifi.ap.dhcp.config(dhcp_config)
Example:
dhcp_config ={}
dhcp_config.start = "192.168.1.100"
wifi.ap.dhcp.config(dhcp_config)

wifi.ap.dhcp.start()
This function will starts the DHCP service
Syntax: wifi.ap.dhcp.start()
 
wifi.ap.dhcp.stop()
This function will stops the DHCP service.
Syntax: wifi.ap.dhcp.stop()

Timer API
                          The lua firmware provides an API with which can be used to set timeouts and
intervals, functions that execute after a period of time, either once or over and over again.
However, the modules only have capacity to have seven timers or intervals running at the
same time. Therefore, you need to reference them by index (0 to 6) and make sure that
different parts of your program don’t override the same timer.
tmr.alarm()
This is a convenience function combining  tmr.register( )  and  tmr.start( )  into a single call.
To free up the resources with this timer when done using it, call  tmr.unregister( )  on it. For one-
shot timers this is not necessary, unless they were stopped before they expired. We use the
same function to create both timeouts and intervals,  tmr.alarm(). We differentiate
which type of timer we want to create using the third argument;   0   = timeout,  1 =
interval:
Syntax: tmr.alarm(id, interval, mode, function do())
Id is the timer id (0-6)
interval is the timer interval in milliseconds, Maximum value is 12884901
mode timer mode:
tmr.ALARM_SINGLE a one-shot alarm (and no need to call tmr.unregister())
tmr.ALARM_SEMI manually repeating alarm (call tmr.start() to restart)
tmr.ALARM_AUTO automatically repeating alarm
 
Example:
function sayHello ()
    print 'Hello'
end
tmr.alarm(0, 2500, 0, sayHello)
Here we are creating a timeout at timer index zero and setting it to call the  sayHello()
function after 2.5 seconds.
If we were to create another timeout (or interval) at index zero before this timer executed, it
would simply overwrite it and sayHello() would never be called.
 
 
 
 
 
tmr.delay()
Busyloops the processor for a specified number of microseconds.
This is in general a bad idea, because nothing else gets to run, and the networking stack (and
other things) can fall over as a result. The only time  tmr.delay( )  may be appropriate to use is if
dealing with a peripheral device which needs a (very) brief delay between commands, or
similar. Use with caution!
Also note that the actual amount of time delayed for may be noticeably greater, both as a
result of timing inaccuracies as well as interrupts which may run during this time.
Syntax: tmr.delay(us)
us is the microseconds to delay the loop.
 
tmr.interval()
This function changes a registerd timer’s expiry interval.
Syntax: tmr.interval(id, interval)
Example:
tmr.register(0, 60000, tmr.ALARM_SINGLE, function() print (“ Timer function”) end)
tmr.inerval (0, 3000)
 
tmr.now()
This functions returns the system counter, which counts in microseconds. Limited to 31 bits,
after that it wraps around back to zero.
Syntax: tmr.now()
Example:
Print(tmr.now)
 
tmr.time()
This function returns the system uptime, in seconds, limited to 31 bits after that it wraps
around back to zero
Syntax: tmr.time()
Example: print(“uptime:”, tmr.time())
 
 
 
tmr.wdclr()
This function feed the system watchdog.
In general, if you ever need to use this function, you are doing it wrong.
The event-driven model of NodeMCU means that there is no need to be sitting in hard loops
waiting for things to occur. Rather, simply use the callbacks to get notified when somethings
happens. With this approach, there should never be a need to manually feed the system
watchdog.
Syntax: tmr.wdclr()
 
tmr.unregister()
Stops the timer (if running) and unregisters the associated callback.
This isn't necessary for one-shot timers (tmr.ALARM_SINGLE), as those automatically
unregister themselves when fired.
Syntax: tmr.unregister(id)
Id is the timer id between (0-6)
Example: tmr.unregister(0)
 
tmr.stop()
This functions stops a running timer, but does not unregister it, A stopped timer can be
restarted with tmr.start()
Syntax: tmr.stop(id)
Example:
If not
tmr.stop(2)
Then
Print (“ timer 2 not supped, not regisetered”)
end

tmr.register()
Configures a timer and registers the callback function to call on expiry.
To free up the resources with this timer when done using it, call  tmr.unregister()  on it. For
one-shot timers this is not necessary, unless they were stopped before they expired.
Syntax: tmr.register(id, interval, mode, func)
 
tmr.softwd()
This function provides a simple software watchdog, which needs to be re-armed or disabled
before it expires, or the system will be restarted.
Syntax: tmr.softwd(timeout_s)
Timeout_s is the watchdog timeout, in seconds, to disable the watchdog use -1.
Example:
function on_success_callback()
  tmr.softwd(-1)
  print("Complex task done, soft watchdog disabled!")
end
tmr.softwd(5)
-- go off and attempt to do whatever might need a restart to recover from
complex_stuff_which_might_never_call_the_callback(on_success_callback
 
 
tmr.state()
This function checks the state of a timer.
Syntax: tmr.state(id)
This fucntions returns if the specified timer is registered, returns whether it is currently
started and its mode, if the timer is not registered, this function will return nil.
Example:
              Running, mode = tmr.state(0)
 
 
 
 
tmr.start()
This functions starts or restarts a previously configured timer.
Syntax: tmr.start(id)
This function will return true if the timer was started and gives false if there is an error on
starting the timer.
Example:
Tmr.register(0, 500, tmr.ALARM_SINGLE, function() print( “hello”) end)
If not tmr.start(0) then print (“yes”)end
 
PWM API
Pulse Width Modulation API’s allows us to use any of the I/O pin as PWM pin except the D0
pin of NodeMCU DEV KIT, this API will be very useful when controlling LED’s , Motors
and many more devices which require PWM functions to do crazy things.
pwm.setup()
This function allows to set a pin to PWM mode, only 6 pins can be set to PWM mode at the
most case.
Syntax: pwm.setup(pin, clock, duty)
Pins from 1 to 12 can be choose for PWM
Clock frequency should be set between 1- 1000, pwm frequency.
Duty cycle should be between 0-1023 , max is 1023(10bit)
Example: pwm.setup(1, 100, 512)  this example set the ‘D1’ pin as pwm output and
frequency is 100 hz and duty cycle is 512.
 
pwm.start()
This function starts the PWM, the waveform is applied to the GPIO pin.
Syntax: pwm.start(pin)
 
pwm.stop()
This function pause the output of the PWM waveform.
Syntax: pwm.stop(pin)
 
 
 
pwm.setduty()
This function allows to set the duty cycle for a pin.
Syntax: pwm.setduty(pin, duty)
Example:
pwm.setup(1, 500, 512)
pwm.setup(2, 500, 512)
pwm.setup(3, 500, 512)
pwm.start(1)
pwm.start(2)
pwm.start(3)
function led(r, g, b)
    pwm.setduty(1, g)
    pwm.setduty(2, b)
    pwm.setduty(3, r)
end
led(512, 0, 0) --  set led to red
led(0, 0, 512) -- set led to blue.

 
NET API
Constants
net.TCP, net.UDP
net.createConnection()
This function creates a client connection.
Syntax: net.createConnection(type, secure)
Type must be net.TCP or net.UDP
Secure 1 for encrypted connection and 0 for plain connection.
Example:
              net.createConnection(net.UDP,0)
 
net.createServer()
This function creates a server. Server is the base class for all the ESP8266 server calls.
Syntax: net.createServer(type, timeout)
Timeout for a TCP server timeout is 1-28,000 seconds ( for an inactive client to be
disconnected) this function will returns net.server sub module.
Example:
              net.createServer(net.TCP, 30)

net.server.close()
This function closes the server.
Syntax: net.server.close()
Example:
              Sc = net.createServer(net.TCP, 30)
              Sc:close()
 
net.server.listen()
This function listen on port from IP address.
Syntax: net.server.listen(port, [ip], function (net.socket))
Port is the port number
Ip address string, this can be omitted
Function (net.socket) callback function, pass to caller function as param if a connection is
created successfully.
Example:
-- 30s time out for a inactive client
sv = net.createServer(net.TCP, 30)
-- server listens on 80, if data received, print data to console and send "hello world" back to caller
sv:listen(80, function(c)
    c:on("receive", function(c, pl)
        print(pl)
    end)
    c:send("hello world")
end)

 
net.socket.close()
This function closes socket connection
Syntax: net.socket.close()
 
net.socket.connect()
This function connect to a remote server.
Syntax: connect(port, ip| domain)
Port is the port number and ip address or domain name string
 
 
Net.socket.dns()
This function provides DNS resolution for a hostname
Syntax: dns(domain, function(net.socket, ip))
Domain name is the domain for the host, function(net.socket,ip) callback function, this first
parameter is the socket, the second parameter is the IP address as a string.
Example:
sk = net.createConnection(net.TCP, 0)
sk:dns("www.nodemcu.com", function(conn, ip) print(ip) end)
sk = nil
 
net.socket.on()
This function register callback funtions for specific events.
Syntax: on(event, function())
Event is a string, which can be “ connection” , “ reconnection”, “ disconnection”, “ receive”
or “ sent” . function(net.socket[, string]) callback function, the first parameter is the socket,
if event is “ receive” the second parameter is the received data as string.
Example:
sk = net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c) print(c) end )
sk:connect(80,"192.168.0.66")
sk:on("connection", function(sck,c)
    -- Wait for connection before sending.
    sk:send("GET / HTTP/1.1\r\nHost: 192.168.0.66\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
end)

 
net.socket.send()
This function sends data to server.
Syntax: send(string, function(sent))
String is the data in string which will be sent to server and function(sent) callback function
for sending string.
net.dns.getdnsserver()
This function gets the IP address of the DNS server used to resolve hostnames.
Syntax: net.dns.getdnsserver(dns_index)
dns_index which DNS server to get (range 0 -1) this function returns IP address(string) on
DNS server.
Example:
print(net.dns.getdnsserver(0)) -- 208.67.222.222
print(net.dns.getdnsserver(1)) -- nil
 
net.dns.setdnsserver("8.8.8.8", 0)
net.dns.setdnsserver("192.168.1.252", 1)
 
print(net.dns.getdnsserver(0)) -- 8.8.8.8
print(net.dns.getdnsserver(1)) -- 192.168.1.252

 
net.dns.resolve()
This function resolve a hostname to an IP address. Doesn’t require a socket like
net.socket.dns()
Syntax: net.dns.resolve(host, function(ip))
Example:
net.dns.resolve("www.google.com", function(sk, ip)
    if (ip == nil) then print("DNS fail!") else print(ip) end
end)

 
net.dns.setdnsserver()
sets the IP of the DNS server used to resolve hostnames.
Default:resolver1.opendns.com(208.67.222.222). you can specify up to 2 DNS servers.
Syntax: net.dns.setdnsserver(dns_ip_addr, dns_index)
dns_ip_addr is the IP address of a DNS server and dns_index is which DNS server to set
(range 0-1). Hence it supports max 2 servers.
HTTP API
Basic HTTP client module.
Provides an interface to do basic GET/POST/PUT/DELETE over HTTP(S), as well as
customized requests. Due to the memory constraints on ESP8266, the supported page/body
size is limited by available memory. Attempting to receive pages larger than this will fail. If
larger page/body sizes are necessary, consider using net.createConnection() and stream in the
data.
Each request method takes a callback which is invoked when the response has been received
from the server. The first argument is the status code, which is either a regular HTTP status
code, or -1 to denote a DNS, connection or out-of-memory failure, or a timeout (currently at
10 seconds).
For each operation it is also possible to include custom headers. Note that following
headers cannot be overridden however: - Host - Connection - User-Agent
The  Host  header is taken from the URL itself, the  Connection  is always set to  close, and
theUser-Agent is ESP8266.
Note that it is not possible to execute concurrent HTTP requests using this module. Starting a
new request before the previous has completed will result in undefined behaviour.
http.delete()
This functions executes a HTTP delete request.
Syntax: http.delete(url, headers, body, callback)
The URL to fetch, including the http:// or https:// prefix
Headers are optional and additional headers to append, including \r \n;
The body to post, must already be encoded in the appropriate format, but may be empty
Callback function to be invoked when the response has been received. It is invoked with
arguments status_code and body.
Example:
http.delete('https://www.example.com/ask',
  "",
  "",
  function(code, data)
    if (code < 0) then
      print("HTTP request failed")
    else
      print(code, data)
    end
  end)

 
http.get()
This function executes a HTTP get request to the server.
Syntax: http.get(url, headers, callback)
url to fetch including the http:// or https://
headers are optional, Callback function to be invoked when the response has been received. It
is invoked with arguments status_code and body.
Example:
http.get("https://www.vowstar.com/nodemcu/", nil, function(code, data)
    if (code < 0) then
      print("HTTP request failed")
    else
      print(code, data)
    end
  end)

 
 
 
http.post()
This function executes a HTTP post request.
Syntax: http.post(url, headers, body, callback)
Exmple:
http.post('http://json.example.com/something',
  'Content-Type: application/json\r\n',
  '{"hello":"world"}',
  function(code, data)
    if (code < 0) then
      print("HTTP request failed")
    else
      print(code, data)
    end
  end)

 
http.put()
This function executes a HTTP PUT request
Syntax: http.put(url, headers, body, callback)
Example:
http.put('http://db.example.com/items.php?key=deckard',
  'Content-Type: text/plain\r\n',
  'Hello!\nStay a while, and listen...\n',
  function(code, data)
    if (code < 0) then
      print("HTTP request failed")
    else
      print(code, data)
    end
  end)

 
http.request()
This function executes a custom HTTP request for any HTTP method.
Syntax: http.request(url, method, headers, body, callback)
Example:
http.request("https://www.example.com", "HEAD", "", "", function(code, data)
  function(code, data)
    if (code < 0) then
      print("HTTP request failed")
    else
      print(code, data)
    end
  end)

 
Turn On and OFF an LED
In this chapter we will see how to turn on and off an LED connected to NodeMCU dev kit or
an ESP8266 generic device.
Requirement for this project
1)    an LED
2)    NodeMCU or ESP8266 board
3)    Connecting wires.

as you can see in your LED it has two pins,


the longer pin is known as Anode and the
shorter pin is known as cathode, connect
longer pin to the 7th pin of Nodemcu dev kit,
if you are using generic ESP8266 module
connect it to GPIO13, if you still have not
sure about GPIO’s available with generic
ESP8266 chips check the lookup table for the
chip. It is not necessary to connect a resistor between the NodeMCU dev kit and the LED.
Connect your NodeMCU to computer.
Open ESPlorer IDE.

Click on the refresh button, it will automatically detect the COM port your Nodemcu has
currently connected, set the baud rate to 9600 for communicating with your device check the
port currently connected which display at the top right of your ESPlorer, click the open button
to establish communication with your NodeMCU.

 
After clicking the Open button, check on
the serial monitor of the ESPlorer, if the
serial monitor displays continues dots,
without any message like the one attached
in the screen below.

Click on the reset button on your NodeMCU dev kit if your dev kit not connecting to your
ESPlorer.
Reset button available on the left side near the USB
connector, press it once and you can see your device
communicating with your ESPlorer.
 

Once the connection establish with the NodeMCU dev kit, you can see the same message that
appears in your ESPlorer serial monitor.
gpio.mode( 7, gpio.OUTPUT )
-- turn on
gpio.write( 7, gpio.LOW )
tmr.delay( 1500000 ) -- delay 1.5 second
gpio.write( 7, gpio.HIGH )
tmr.delay( 1500000 ) -- delay 1.5 second
gpio.write( 7, gpio.LOW )
tmr.delay( 1500000 ) -- delay 1.5 second
gpio.write( 7, gpio.HIGH )
tmr.delay( 1500000 ) -- delay 1.5 second
gpio.write( 7, gpio.LOW )
tmr.delay( 1500000 ) -- delay 1.5 second
gpio.write( 7, gpio.HIGH )
tmr.delay( 1500000 ) -- delay 1.5 second
gpio.write( 7, gpio.LOW )
tmr.delay( 1500000 ) -- delay 1.5 second
 
Type the above program in your ESPlorer
After completing the program click on the send to ESP button on the bottom left of your
ESPlorer.

When you click the send to ESP button , you can view on your serial monitor code is sending
to ESP line by line, when the first line send to ESP you can view on your Nodemcu dev kit,
the connected LED will go High and Low based on the line of code that currently sending to
the ESPlorer.
 
 
 
Lua program explanation:
gpio.mode(7,gpio.OUTPUT)
This command will initialize pin to GPIO mode, set the pin as Input or Output based on our
setting to the pin, the compiler will assign the state of the pin. When you using this
command the function should consist of pin to configure and the mode of the pin,
gpio.OUTPUT or gpio.INPUT, this command will also assign a pin as a pullup. , if we not
choose the pullup option by default all the gpio pin will set to Float.
 
gpio.write(7, gpio.LOW)
This command will set the digital GPIO pin value either high or low, based on the output
level selected by the programmer. In the above command digital pin ‘D7’ of NodeMCU has
assigned to LOW level, this will make the connected LED to go LOW or OFF state.
 
tmr.delay(1500000)
This command will delay the function for the period that is entered into the function ( )
1000000 which equals 1 sec.
As you can see the in the program same set of codes has repeated throughout the completion
of program, which is easy to understand by knowing the above command, the program has not
consist of any loop so the program will execute only a single time and stops, if you see the
LED connected to NodeMCU, LED will go High for 3 times and Low for 4 times and stops
forever.
To do:
Add more number of lines to the code and check how the process is going on, change the
delay timer and check the LED output and note how the delay function causing the program to
change.
 
Working with LED
Blink an LED
              In the previous chapter we have seen how to turn on and off an LED, in this chapter
we will see how to blink an LED using NodeMCU,
Easy blink function make you cry 
while 1 do
gpio.write(0, gpio.HIGH)
tmr.delay(1000000) -- wait 1,000,000 us = 1 second
gpio.write(0, gpio.LOW)
tmr.delay(1000000) -- wait 1,000,000 us = 1 second
end)
The above is the simple blink function which can go wrong if you don’t know what it can
done to your ESP8266, as the code is infinite loop and if you save the code to NodeMCU or
any other ESP8266 device, this code will run forever after uploading this code, your
NodeMCU will not respond to you if you try to establish communication with your ESPlorer,
if you ever happened to caught in a situation like this flash the firmware again and do all the
process from the beginning.
For this example we going to use the same setup which we have used for the previous
example.

Connect your LED to the 7th pin of NodeMCU and check you are connecting the LED pins
properly to the 7th pin and the ground, if you interchange your anode and cathode then it may
lead to damage your LED.
Connect NodeMCU to your computer using USB cable.
Open ESPlorer and start type your program to the ESPlorer.
 
 
LUA program:
lighton=0
pin=7
gpio.mode(pin,gpio.OUTPUT)
tmr.alarm(1,1000,1,function()
    if lighton==0 then
        lighton=1
        gpio.write(pin,gpio.HIGH)
    else
        lighton=0
         gpio.write(pin,gpio.LOW)
    end
end)
 

 
After completing the program click on the send to ESP button on the bottom left of your
ESPlorer.
When you click the send to ESP button , you can view on your serial monitor code is sending
to ESP line by line, after sending the code to ESP8266 device or NodeMCU dev kit you can
see the LED goes On and Off between the 1sec interval.
Program Explanation:
lighton = 0
Lighton is a variable and you can use any of the name you would like for the variable and
the variable currently holds 0 as the value to its memory.
 
Pin = 7
This is also a variable, which we can assign a name to the pin number and instead of the pin
number we can call the pin number by the name that is assigned to the pin.
 
gpio.mode(pin, gpio.OUTPUT)
We have already seen about this function, this function will set a digital pin to either input or
output.
 
tmr.alarm (1, 1000, 1, function()
When using timer function we are limited to use only 7 timers in the function this is a
limitation when using tmr function in NodeMCU. , to keep track of how many functions we
are using in the program we can use timer ID, 1 in the begging of the function before 1000 is
the track ID for the timer function, and the number 1000 is the time interval in milliseconds,
and call the function every 1 second.
 
 
 
 
if lighton==0 then
        lighton=1
        gpio.write(pin,gpio.HIGH)
    else
        lighton=0
         gpio.write(pin,gpio.LOW)
    end
command which follows the tmr.alram is the function inside the tmr.alram function(), this
code will execute the function , it will turn make the ‘D7’ pin to go high for 1 sec and set the
Lighton = 1 and this will make the ‘D7’ pin to go low when lighton = 0;
 
Init.lua
Save the above program as init.lua
After saving the file in the name init and
upload it to the ESP8266 or NodeMCU
dev kit. Whenever a file named as init
and uploaded to ESP8266 that program
will first run when the ESP8266 booted
up. Usually this init function is used for
storing wifi ssid and password, which
will make this device connected to a wifi
when the ESP booted up.
 
To do:
Try to change the timer interval in the tmr.alarm function and change the timer ID, and check
how it works, and also create another tmr.alarm with same ID and check whether the
tmr.alarm function with same ID is executing or not.
Connect another pin and write a program for 2 LED’s and also create two separate functions
and give different interval between these functions.

Using the PWM function for the LED


              In this section we will look into the PWM options available with NodeMCU, Using
PWM function it is possible to control the brightness of the LED. Pins from 1 to 12 can be
used as a PWM pin. For this we going to use the same setup as we used for blinking an LED.
Program to control brightness of LED connected to digital pin ‘D7’ of Nodemcu dev kit.
pwmpin=7
pwm.setup(pwmpin,500,1020)
pwm.start(pwmpin)
for i = 1020,0,-20 do
    pwm.setduty(pwmpin,i)
    tmr.delay(30000)
end
tmr.delay(1000000)
for i=0,1020,20 do
    pwm.setduty(pwmpin,i)
    tmr.delay(30000)
end
pwm.setduty(pwmpin, 1023) -- turn off the ledpin
pwm.close(pwmpin)

 
Type the program into ESPlorer and send the program to NodeMCU dev kit and check how
the brightness of the LED pin changes, initially the brightness of the LED increase and
decrease and then increase and stands there, as this program doesn’t contain any loop, this
function will run only once and stops.
Try interchanging the loop like the one below and save the program to ESP8266 device. When
you saving program, save it as pwm or any other name don’t use init.lua,

Observe the changes between two program, and save this to NodeMCU dev kit. This time we
are not sending data, directly programming to ESP8266 flash memory.
Click reset button on the ESPlorer.

And wait for your device to restart and check what is happening with the LED.
 
 
 
 
Click on the run button on the ESPlorer
 
Now save the same file as init.lua and save it to ESP8266 and click the restart button on the
ESPlorer.
Now observer the difference between the file name you saved previously and now, you need
to manually click run when you save the file in different name, but if you save the file name in
init.lua the program will automatically executes.
Program Explanation.
pwmpin=7
pwmpin is the variable which holds the pin number, which help us to use pwmpin in the
program instead of directly inputting the pin number.
 
pwm.setup(pwmpin,500,1020)
This function will set the pin 7 to pwm mode,  500 followed by pin is the clock which can be
set from 1 to 1000, this is the PWM frequency, and the 1020 is the duty cycle and max 1023
can be set as duty cycle.
 
pwm.start(pwmpin)
This function will starts the waveform to be applied to the GPIO pin.
 
for i = 0,1020,20 do
    pwm.setduty(pwmpin,i)
    tmr.delay(30000)
end
This is for loop which will count the value of i from 0 to 1020 in the increment of 20 counts,
initially the i is set to zero so the loop counts from 0. During the count it will executes the
following function under the loop.
 
Pwm.setduty(pwmpin,i)
This function set the duty cycle to the pin, here the pin ‘D7’ will be set initially to duty cycle
0 and it will increment by 20 until 1020.
tmr.delay()
This function makes delay during the execution of the program.
end
which notifies the end of the for loop.
As the loop repeat again with decrement order and it does the same function
pwm.close(pwmpin)
This function will quit from the PWM mode
 
RGB LED with NodeMCU
In this section we will see how to use RGB led with NodeMCU, as we have seen in the earlier
section how to work with LED’s , RGB also an LED, it is like a combination of red green and
blue LED.
 
 
 
 
 
 
 
 
 
 
 
 
 
RGB LED used for this tutorial is common cathode which should be connected to GND of
NodeMCU, if you are using common anode type, program needs to be changed. Connect R
pin to 8th pin of NodeMCU and G pin to 6th pin of NodeMCU and the last B pin to 7th pin of
NodeMCU.
NodeMCU Program.
  pwm.setup(8, 500, 512)
  pwm.setup(6, 500, 512)
  pwm.setup(7, 500, 512)
  pwm.start(8)
  pwm.start(6)
  pwm.start(7)
  led(512, 0, 0) – red led, call the function and set pwm duty to pin 8
  tmr.delay(1000000)
  led(0, 0, 512) -- blue led, call the function and set pwm duty to pin 7
  tmr.delay(1000000)
  led(0,512,0)-- green led, call the function and set pwm duty to pin 6
  tmr.delay(1000000)
  led(0,0,0) – set 0 pwm duty to all the pins
 
   function led(r, g, b)
    pwm.setduty(8, r)
    pwm.setduty(6, g)
    pwm.setduty(7, b)
  end
Upload the program to Nodemcu from ESPlorer and check the result, this will turn On and
Off a single LED at a time, much like turning On and Off a led.
Most of the function used for this examples are previously discussed, if you have any doubts
please check the previous chapters.

Connect to WiFi Router


              In this chapter we will see how to establish connection between router and ESP8266.
Simple Program to connect to router and return the IP address:
wifi.setmode(wifi.STATION)
    wifi.sta.config("Magesh", "jayakumar")
    ip = wifi.sta.getip()
    print(ip)
Type the program type your router name in the place “magesh” and your password to the
place “jayakumar” that’s my router id and password, save the file to ESP8266, this function
will return ip address that as currently connected to your home router.

Program Explanation:
Wifi.setmode(wifi.STATION)
This function configures the wifi mode to use in program, NodeMCU supports 4 modes,
Station mode, Access point, Station + Access point and the last one Wifi off. In the above
function wifi mode is set to STATION, station mode should be choose when the device is
connected to a WiFi router.
 
Wifi.sta.config(“ssid”, “password”)
This function sets the Wifi station configuration. Ssid is the router Name and password is the
router password.
Wifi.sta.getip()
This function returns the Ip address that is currently connected.
Ip = wifi.sta.getip()
Ip address is stored in the variable ip, print(ip) , the value stored in the variable will print on
the serial monitor.
Simple Web Server
              In this chapter we will create a simple webserver. We going to use the functions from
the previous connect WiFi router chapter. If you haven’t gone through the chapter, take a look
and come back here.
Program for webserver
wifi.setmode(wifi.STATION)
    wifi.sta.config("Magesh", "jayakumar")
    ip = wifi.sta.getip()
    print(ip)
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive",function(conn,payload)
        print(payload)
        conn:send("<h1> Congrats, you have created a WebServer </h1>")
    end)
    conn:on("sent",function(conn) conn:close() end)
end)
Type the above code in your ESPlorer IDE and Save it to ESP8266 chip

When you save the code to NodeMCU dev kit or ESP8266 device check on the serial monitor
of your ESPlorer, it will return the ip address it has currently connected.
If you have not saved the file name as Init, click on the run command in the ESPlorer window.

Copy and paste the IP address in your browser.


 
Program Explanation:
wifi.setmode(wifi.STATION)
    wifi.sta.config("Magesh", "jayakumar54321")
    ip = wifi.sta.getip()
    print(ip)
we have already seen what is the function of above code in the previous chapter, check it
before you proceed further.
srv=net.createServer(net.TCP)
This function creates a server, and the type of server we have to define there are two type
one is net.TCP and another one net.UDP
 
 
 
 
srv:listen(80,function(conn)
server listens on port 80, if data received, print data to console
print(payload)
received data will be displayed on the Serial monitor of ESPlorer.

conn:send("<h1> Congrats, you have created a WebServer </h1>")


Blink LED through Web Server


                          In this chapter we will see how to control a LED from a web server, we use
NodeMCU to connect to an access point, by connecting the Nodemcu to an access point we
can set up the NodeMCU as a wireless access point and host a webserver on NodeMCU, that
allow device to connect to it through TCP/IP, and we can access it from any devices which are
currently connected to local router. You should go through previous chapters to complete this
tutorial as we going to use codes that we see in the last chapter.

Connect your LED to 7th pin of NodeMCU and connect your NodeMCU to computer.
Open your ESPlorer and type the code which shown below, don’t copy past the code if you
want to understand the inner meaning of program.
wifi.setmode(wifi.STATION)
wifi.sta.config("Magesh", "jayakumar")
print('Attempting connection')
print("Connected on " .. wifi.sta.getip())
wifi.sta.connect()
tmr.alarm(0, 1000, 1, checkWifiStatus)
 
gpio.mode(7, gpio.OUTPUT)
-- Let's start off with the light off
gpio.write(7, gpio.LOW)
 
srv=net.createServer(net.TCP, 3)
    print("Server created on " .. wifi.sta.getip())
srv:listen(80,function(conn)
    conn:on("receive",function(conn,request)
    print(request)
    _, j = string.find(request, 'led_light_switch=')
    if j ~= nil then
        command = string.sub(request, j + 1)
            if command == 'on' then
                gpio.write(7, gpio.HIGH)
            else
                gpio.write(7, gpio.LOW)
            end
    end
    conn:send('<!DOCTYPE html>')
    conn:send('<html lang="en">')
    conn:send('<head><meta charset="utf-8" />')
    conn:send('<title>Hello, World!</title></head>')
    conn:send('<body><h1>Hello, World!</h1>')
    -- Send the current status of the LED
    if gpio.read(7) == gpio.HIGH then
        led = "ON"
    else
        led = "OFF"
    end
    conn:send('<p>The light is ' .. led .. '</p>')
    conn:send('<form method="post">')
      conn:send('<input type="radio" name="led_light_switch" value="on">ON</input><br
/>')
      conn:send('<input type="radio" name="led_light_switch" value="off">OFF</input><br
/>')
    conn:send('<input type="submit" value="Light Switch" />')
    conn:send('</form></body></html>')
    end)
end)
above program is the combination of Connect to wifi router and Simple web server, in this
program we have added code to create html functions, and also we retrieve data from the
webserver and check for the command received from the webserver, if the command matches
with our predefined command then it should do some particular function, we assigned value to
the “led_light_switch” when button ‘ON” clicked it will assign to “on” and if the button off
clicked “off” value will be assigned to led_light_switch, we have also included in the program
that if we receive value “on” we have to turn on the LED connected to pin “D7” else the pin
should be turned off.
After completion of program upload the file to ESP8266, if you are not assigning the name as
init.lua you have hit the run button to read the file by ESP8266 device. Press the reset button
on NodeMCU after you uploaded the code to your device. Make note of the IP address
returned in the Serial monitor of ESPlorer.

Control Electrical devices from Webserver


                          This is the extended version of last chapter, the same program can be used for
controlling electrical appliances like AC lights, fans, heater, thermostat etc., can be controlled
from a webserver. If you can port forward your IP address then you can control the devices
from any part of the world through webpage. Your local webserver will act as a minimal
webpage to control and monitor your things from any part of the world.

 
You should have enough experience before you doing this tutorial practically, if you planning
to control devices of high voltage, you should take all the precautions and necessary
knowledge about working of these high voltage devices.
We going to use an electrical device called relay to Turn on and off electrical appliances, there
is no change in the programming part of this tutorial, it is same as we turn on and off LED in
the previous chapter, instead of connecting the output pin to the LED we have to connect to
the relay to turn on and off high voltage devices. Connect the relay pins to 5,6,7,8 digital pins
of NodeMCU dev kit, and upload the program to ESP8266, wait for the IP address returned by
the device on serial monitor and paste the IP address on your web browser and control your
electrical devices.
Program to control Electrical devices.
wifi.setmode(wifi.STATION)
wifi.sta.config("Magesh","jayakumar")
print(wifi.sta.getip())
gpio.mode(5, gpio.OUTPUT)
gpio.mode(6, gpio.OUTPUT)
gpio.mode(7, gpio.OUTPUT)
gpio.mode(8, gpio.OUTPUT)
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive", function(client,request)
        local buf = "";
        local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
        if(method == nil)then
            _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
        end
        local _GET = {}
        if (vars ~= nil)then
            for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
                _GET[k] = v
            end
        end
        buf = buf.."<h1> Web Server</h1>";
        buf = buf.."<p>LIGHT 1 <a href=\"?pin=ON1\"><button>ON</button></a>&nbsp;<a
href=\"?pin=OFF1\"><button>OFF</button></a></p>";
        buf = buf.."<p>LIGHT 2 <a href=\"?pin=ON2\"><button>ON</button></a>&nbsp;<a
href=\"?pin=OFF2\"><button>OFF</button></a></p>";
        buf = buf.."<p>LIGHT 3 <a href=\"?pin=ON3\"><button>ON</button></a>&nbsp;<a
href=\"?pin=OFF3\"><button>OFF</button></a></p>";
        buf = buf.."<p>LIGHT 4 <a href=\"?pin=ON4\"><button>ON</button></a>&nbsp;<a
href=\"?pin=OFF4\"><button>OFF</button></a></p>";
              local _on,_off = "",""
        if(_GET.pin == "ON1")then
              gpio.write(5, gpio.HIGH);
        elseif(_GET.pin == "OFF1")then
              gpio.write(5, gpio.LOW);
        elseif(_GET.pin == "ON2")then
              gpio.write(6, gpio.HIGH);
        elseif(_GET.pin == "OFF2")then
              gpio.write(6, gpio.LOW);
              elseif(_GET.pin == "ON3")then
              gpio.write(7, gpio.HIGH);
        elseif(_GET.pin == "OFF3")then
              gpio.write(7, gpio.LOW);
              elseif(_GET.pin == "ON4")then
              gpio.write(8, gpio.HIGH);
        elseif(_GET.pin == "OFF4")then
              gpio.write(8, gpio.LOW);
        end
        client:send(buf);
        client:close();
        collectgarbage();
    end)
end)
 
after successful upload of your code to NodeMCU you can check in your browser to get hold
of control your electrical devices.
 

Temperature and Humidity Sensor support in NodeMCU


              NodeMCU for Lua natively supports DHTxx sensors, in this chapter we going to use
DHT22 as it is more accurate and stable when compare to the DHT11 for measuring
Temperature and Humidity.

Connect the sensor as shown in the fritzing circuit, connect VCC to Vin pin of NodeMCU ,
connect the signal pin to ‘D5’ pin of NodeMCU and connect sensor Gnd to Gnd of
NodeMCU.
Program to read Temperature and Humidity
pin = 5
status,temp,humi,temp_decimial,humi_decimial = dht.readxx(pin)
if( status == dht.OK ) then
  -- Integer firmware using this example
  print(
    string.format(
      "DHT Temperature:%d.%03d;Humidity:%d.%03d\r\n",
      math.floor(temp),
      temp_decimial,
      math.floor(humi),
      humi_decimial
    )
 )
  -- Float firmware using this example
  print("DHT Temperature:"..temp..";".."Humidity:"..humi)
elseif( status == dht.ERROR_CHECKSUM ) then
  print( "DHT Checksum error." );
elseif( status == dht.ERROR_TIMEOUT ) then
  print( "DHT Time out." );
end
Save the file into ESP flash memory, and click run button this will execute the program and
temperature and humidity results will be displayed on Serial monitor of ESPlorer.
Note: Make sure you have selected integer type firmware during the initial stage when
uploading the firmware to NodeMCU. As this example uses integer firmware for calculating
temperature and humidity data.
If using float firmware then temp and humi are floating point numbers. On an integer
firmware, the final values have to be concatenated from temp and temp_dec / humi and
hum_dec.
OUTPUT:

 
DHT API
Constants:
dht.ok, dht.ERROR_CHECKSUM, dht.ERROR_TIMEOUT, these represents the potential
values for the DHT read status.
 
dht.read()
This function read all kinds of DHT sensors, including DHT11,21,22,33,44 humidity
temperature and combo sensor.
 
Syntax: dht.read(pin)
This function returns status as defined in constants and temperature and humidity data.
 
dht.read11()
This function read dht11 humidity and temperature data.
 
dht.readxx()
This function reads all kind of DHT sensors, except DHT11, hence if you want to read
DHT11 sensor data, you should use dht.read11() function.
 
DHT11 sensor with NodeMCU

Program for DHT11 Sensor


pin = 5
status,temp,humi,temp_decimial,humi_decimial = dht.read11(pin)
if( status == dht.OK ) then
  -- Integer firmware using this example
  print(
    string.format(
      "DHT Temperature:%d.%03d;Humidity:%d.%03d\r\n",
      math.floor(temp),
      temp_decimial,
      math.floor(humi),
      humi_decimial
    )
 )
  -- Float firmware using this example
  print("DHT Temperature:"..temp..";".."Humidity:"..humi)
elseif( status == dht.ERROR_CHECKSUM ) then
  print( "DHT Checksum error." );
elseif( status == dht.ERROR_TIMEOUT ) then
  print( "DHT Time out." );
end
 
OUTPUT:
 

Sensors Data To Thingspeak


              ThingSpeak is an open source “Internet of Things” application and API to store and
retrieve data from things using HTTP over the Internet or via a Local Area Network.
With ThingSpeak, you can create sensor logging applications, location tracking applications,
and a social network of things with status updates. In this tutorial you going to learn about
how temperature data can be uploaded to thingspeak.com using Nodemcu.

We going to use only two components for this tutorial one is Nodemcu and other one is
DHT11 temperature and humidity sensor, One more thing you need to do for this tutorial is to
register to thingspeak.com to get your api key, the api key must to upload your data to
thingspeak.com
 
Steps to be followed to upload data to thingspeak.
1. Go to https://thingspeak.com/
2. Log in with your ID and Password.
 
 
 
 
 
3. Click the Create New channel Icon
 
 
 
4. Give Name to your new channel and edit the description for your channel and create the
Names for your field, fields are going to hold the sensor data's, if your uploading temperature
data give the name as temperature to the field and choose how many field you require for your
project.

5. After completing the above steps save your channel.


6. Go to API keys and copy the Write API key.
 
 
 
 
 

Replace the key with the newly created key.


 
 
 
 
Program to send Temperature and Humidity data to Thingspeak.com
print("Setting up WIFI...")
wifi.setmode(wifi.STATION)
wifi.sta.config("Magesh","jayakumar")
wifi.sta.connect();
print(wifi.sta.getip())
 
pin = 5
 
function getTemp()
status,temp,humi,temp_decimial,humi_decimial = dht.read11(pin)
if( status == dht.OK ) then
  -- Integer firmware using this example
  print(    
    string.format(
      "DHT Temperature:%d.%03d;Humidity:%d.%03d\r\n",
      math.floor(temp),
      temp_decimial,
      math.floor(humi),
      humi_decimial
    )
 )
 
--
end
end
 
function sendData()
getTemp();
-- conection to thingspeak.com
print("Sending data to thingspeak.com")
conn=net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload) print(payload) end)
-- api.thingspeak.com 184.106.153.149
conn:connect(80,'184.106.153.149')
conn:send("GET /update?
key=DBKBFHIR0L020NIQ&field1="..temp.."."..temp_decimial.."&field2="..humi.."."..hum
i_decimial.." HTTP/1.1\r\n")
conn:send("Host: api.thingspeak.com\r\n")
conn:send("Accept: */*\r\n")
conn:send("User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n")
conn:send("\r\n")
conn:on("sent",function(conn)
                      print("Closing connection")
                      conn:close()
                  end)
conn:on("disconnection", function(conn)
                      print("Got disconnection...")
  end)
end
--sendData();
-- send data every X ms to thing speak
tmr.alarm(2, 60000, 1, function() sendData() end )
 
before uploading the program to NodeMCU dev kit make sure to edit wifi name and password
and also the API key that you copied from Thingspeak.com , save the file as init.lua and
upload to NodeMCU dev kit.
You can check on your Serial monitor, when your Nodemcu trying to establish
communication with your router and send Temperature and Humidty data to Thingspeak.com
If you getting any trouble during the process make sure to check whether you have entered
correct API key, if NodeMCU facing any trouble communicating with ESPlorer disconnect
and reconnect it this solve the problem.
 

Working with I2C device.


              The Inter-integrated Circuit (I2C) Protocol developed by Philips and is a protocol
intended to allow multiple “slave” digital integrated circuits (“chips”) to communicate with
one or more “master” chips. Like the Serial Peripheral Interface (SPI), it is a two-wire
protocol where you can hook up multiple slaves to the same communication lines in any order
you want, since all the slaves are given an unique ID to keep track of them, keeping track of
the communication is the master job so no more than one slave can communicate at a time. In
the case of this example, we only have two devices, the nodemcu which will be acting as a
master and the LCD acting as a slave, this protocol only intended for short distance
communications within a single device. Like Asynchronous Serial Interfaces (such as RS-232
or UARTs), it only requires two signal wires to exchange information.
I2C API
i2c.address()
This functions setup I2C address and read/ write mode for the next transfer of data from
sensor.
Syntax: i2c.address(id,device_addr, direction)
id in the function should always be 0, followed by device_addr this you can find in the
device data sheet, and the device address followed by the direction either transmit data
(i2c.TRANSMITTER) that is writing mode or receive data (i2c.RECEIVER) also know an
reading mode.
 
i2c.read()
This function read number of bytes available in the i2c device that is currently called to read
by this function.
Syntax: i2c.read(id, len)
Id should always be 0 and it should be followed by the number of data bytes to read. Thing
function string of received data.
 
i2c.setup()
This function initialize the i2c function, this will let know the compiler that i2c function is
going to use in the program.
Syntax: i2c.setup(id, pinSDA, pinSCL, speed)
Id should always be 0, any pin from 0-12 can be used as SDA, and same as SDA any pin can
be used as SCL pin, make sure you are choosing different pins for SCL and SDA, and speed
of the i2c should be select i2c.slow that is the only function supported by the nodemcu
currently.
 
 
i2c.start()
This function send an i2c start condition.
Syntax: i2c.start(id)
Id should always be zero.
 
i2c.stop()
This function stops the i2c function, this function should always call when you complete the
i2c communication with device gets over.
 
i2c.write()
Write data to i2c bus, data items can be multiple numbers, strings or lua tables.
Syntax: i2c.write(id, data1, data2, ….datan)
Id should always be zero, any data can be write into the bus.
 
I2C Temperature and Pressure Sensor
              In this section we will see how to use a BMP085 pressure and temperature sensor
with NodeMCU dev kit, in NodeMCU it has a prebuilt library for this sensor, and this library
can also work with BMP180 type sensor.

Connect the BMP180 or BMP085 sensor to NodeMCU dev kit as follows.


SDA to ‘D5’ pin and SCL to ‘D6’ pin. Gnd to Gnd and Vcc pin to 3.3v of Nodemcu dev kit.
 
 
Program to read Temperature data:
bmp085.init(5, 6)
local t = bmp085.temperature()
print(string.format("Temperature: %s.%s degrees C", t / 10, t % 10))
Program to read Pressure data:
bmp085.init(5, 6)
local p = bmp085.pressure()
print(string.format("Pressure: %s.%s mbar", p / 100, p % 100))
 
Program explanation:
Bmp085.init(5,6)
This function initialize the module and sets the pin configuration, 5 is the SDA pin and 6 is
the SCL pin , any pin from 0 to 12 can be configured for SCA and SCL
 
Bmp.085.temperature()
This function samples the sensor and returns the temperature in Celsius as an integer
multiplied with 10(integer)
 
Bmp085.pressure()
This function samples the sensor and returns the pressure in Pascal as an integer.
 
The predefined library that comes with Nodemcu firmware will not give appropriate results at
times, which become a frustration when we need the most, when we call the function it returns
error to avoid that we can use a library for this function which is available in the link here

Temperature and Pressure Sensor Web server


              In this section we will create a temperature and pressure sensor webserver using the
library which we downloaded for BMP180 sensor in the previous section.
Use the same circuit connection in the previous section for this tutorial.
Library file for BMP180 or BMP085 sensor
--
***************************************************************************
-- BMP180 module for ESP8266 with nodeMCU
-- BMP085 compatible but not tested
--
-- Written by Javier Yanez
--
-- MIT license, http://opensource.org/licenses/MIT
--
***************************************************************************
 
local moduleName = ...
local M = {}
_G[moduleName] = M
 
local ADDR = 0x77 --BMP180 address
local REG_CALIBRATION = 0xAA
local REG_CONTROL = 0xF4
local REG_RESULT = 0xF6
 
local COMMAND_TEMPERATURE = 0x2E
local COMMAND_PRESSURE = {0x34, 0x74, 0xB4, 0xF4}
 
-- calibration coefficients
local AC1, AC2, AC3, AC4, AC5, AC6, B1, B2, MB, MC, MD
 
-- temperature and pressure
local t,p
 
local init = false
 
-- i2c interface ID
local id = 0
 
-- 16-bit  two's complement
-- value: 16-bit integer
local function twoCompl(value)
if value > 32767 then value = -(65535 - value + 1)
end
return value
end
 
-- read data register
-- reg_addr: address of the register in BMP180
-- lenght: bytes to read
local function read_reg(reg_addr, length)
  i2c.start(id)
  i2c.address(id, ADDR, i2c.TRANSMITTER)
  i2c.write(id, reg_addr)
  i2c.stop(id)
  i2c.start(id)
  i2c.address(id, ADDR,i2c.RECEIVER)
  c = i2c.read(id, length)
  i2c.stop(id)
  return c
end
 
-- write data register
-- reg_addr: address of the register in BMP180
-- reg_val: value to write to the register
local function write_reg(reg_addr, reg_val)
  i2c.start(id)
  i2c.address(id, ADDR, i2c.TRANSMITTER)
  i2c.write(id, reg_addr)
  i2c.write(id, reg_val)
  i2c.stop(id)
end
 
-- initialize module
-- sda: SDA pin
-- scl SCL pin
function M.init(sda, scl)
  i2c.setup(id, sda, scl, i2c.SLOW)
  local calibration = read_reg(REG_CALIBRATION, 22)
 
  AC1 = twoCompl(string.byte(calibration, 1) * 256 + string.byte(calibration, 2))
  AC2 = twoCompl(string.byte(calibration, 3) * 256 + string.byte(calibration, 4))
  AC3 = twoCompl(string.byte(calibration, 5) * 256 + string.byte(calibration, 6))
  AC4 = string.byte(calibration, 7) * 256 + string.byte(calibration, 8)
  AC5 = string.byte(calibration, 9) * 256 + string.byte(calibration, 10)
  AC6 = string.byte(calibration, 11) * 256 + string.byte(calibration, 12)
  B1 = twoCompl(string.byte(calibration, 13) * 256 + string.byte(calibration, 14))
  B2 = twoCompl(string.byte(calibration, 15) * 256 + string.byte(calibration, 16))
  MB = twoCompl(string.byte(calibration, 17) * 256 + string.byte(calibration, 18))
  MC = twoCompl(string.byte(calibration, 19) * 256 + string.byte(calibration, 20))
  MD = twoCompl(string.byte(calibration, 21) * 256 + string.byte(calibration, 22))
 
  init = true
end
 
-- read temperature from BMP180
local function read_temp()
  write_reg(REG_CONTROL, COMMAND_TEMPERATURE)
  tmr.delay(5000)
  local dataT = read_reg(REG_RESULT, 2)
  UT = string.byte(dataT, 1) * 256 + string.byte(dataT, 2)
  local X1 = (UT - AC6) * AC5 / 32768
  local X2 = MC * 2048 / (X1 + MD)
  B5 = X1 + X2
  t = (B5 + 8) / 16
  return(t)
end
 
-- read pressure from BMP180
-- must be read after read temperature
local function read_pressure(oss)
  write_reg(REG_CONTROL, COMMAND_PRESSURE[oss + 1]);
  tmr.delay(30000);
  local dataP = read_reg(0xF6, 3)
  local UP = string.byte(dataP, 1) * 65536 + string.byte(dataP, 2) * 256 + string.byte(dataP, 1)
  UP = UP / 2 ^ (8 - oss)
  local B6 = B5 - 4000
  local X1 = B2 * (B6 * B6 / 4096) / 2048
  local X2 = AC2 * B6 / 2048
  local X3 = X1 + X2
  local B3 = ((AC1 * 4 + X3) * 2 ^ oss + 2) / 4
  X1 = AC3 * B6 / 8192
  X2 = (B1 * (B6 * B6 / 4096)) / 65536
  X3 = (X1 + X2 + 2) / 4
  local B4 = AC4 * (X3 + 32768) / 32768
  local B7 = (UP - B3) * (50000/2 ^ oss)
  p = (B7 / B4) * 2
  X1 = (p / 256) * (p / 256)
  X1 = (X1 * 3038) / 65536
  X2 = (-7357 * p) / 65536
  p = p +(X1 + X2 + 3791) / 16
  return (p)
end
 
-- read temperature and pressure from BMP180
-- oss: oversampling setting. 0-3
function M.read(oss)
  if (oss == nil) then
     oss = 0
  end
  if (not init) then
     print("init() must be called before read.")
  else 
     read_temp()
     read_pressure(oss)
  end
end;
 
-- get temperature
function M.getTemperature()
  return t
end
 
-- get pressure
function M.getPressure()
  return p
end
 
return M
 
Copy and paste the library file save the file as bmp180.lua and upload the file to Nodemcu dev
kit.
We have already created a webserver for controlling an LED in the past tutorials, this
webserver will display the Temperature and Pressure data, and we can view this by looking
into the Ip address of the webserver that is returned during the program.
Program for Temperature and Pressure Webserver
--**************************************************************
    alti=170 -- set correction for your altitude location in meters
--**************************************************************
 
   wifi.setmode(wifi.STATION)
   wifi.sta.config("Magesh","jayakumar")
   wifi.sta.connect()
   print("Connected on " .. wifi.sta.getip())
    sda=2   -- GPIO2 connect to SDA BMP180
    scl=1   -- GPIO0 connect to SCL BMP180
    pres=0  -- pressure
    temp=0  -- temperature
    fare=0  -- temperature
    oss=0   -- over sampling setting
 
--load BMP module for reading sensor
function ReadBMP()
    bmp180 = require("bmp180")
    bmp180.init(sda, scl)
    bmp180.read(oss)
    pres = bmp180.getPressure()/100+alti/8.43
    temp = bmp180.getTemperature()/10
    fare=(temp*9/5+32)
    print("Pressure:    "..string.format("%.1f",pres).." hPa")
    print("Temperature: "..string.format("%.1f",temp).." deg C")
    print("Temperature: "..string.format("%.1f",fare).." deg F")
    print(" ")
    -- release module
    bmp180 = nil
    package.loaded["bmp180"]=nil
end
-- First reading data
ReadBMP()
-- Periodic reading of the sensor
tmr.alarm(1,10000,1, function()ReadBMP()end)
 
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive",function(conn,payload)
        --print(payload) -- for debugging only
        strstr={string.find(payload,"GET / HTTP/1.1")}
        if(strstr[1]~=nil)then
        --generates HTML web site
        conn:send('HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nCache-Control: private, no-
store\r\n\r\n\
        <!DOCTYPE HTML>\
        <html><head><meta content="text/html;charset=utf-8"><title>ESP8266</title>\
        <meta http-equiv="refresh" content="10;url=/"></head>\
              <body bgcolor="#ffe4c4"><h2>Barometer with I2C sensor<br>BMP180 or
BMP85</h2>\
        <h3><font color="green">\
              <IMG SRC="http://esp8266.fancon.cz/bmp180/bar.gif"WIDTH="64"HEIGHT="64">
<br>\
              <input style="text-align: center"type="text"size=6
name="j"value="'..string.format("%.1f",pres)..'"> Atmos. pressure hPa<br><br>\
        <IMG SRC="http://esp8266.fancon.cz/bmp180/tmp.gif"WIDTH="64"HEIGHT="64">
<br>\
              <input style="text-align: center"type="text"size=4
name="p"value="'..string.format("%.1f",temp)..'"> Temperature grade C<br>\
              <input style="text-align: center"type="text"size=4
name="s"value="'..string.format("%.1f",fare)..'"> Temperature grade F</font></h3>\
        <h6>Tested with Lua NodeMCU<br> 0.9.6 build 20150704 float!</h6>')
        end
    conn:on("sent",function(conn) conn:close() end)
   end)
end)
Save the above program as init.lua file, first you should save the library file to NodeMCU dev
kit, then upload the init file. Make sure to edit your router name and password in the program,
you can also change the altitude based on the region, after uploading both program press the
reset button on the NodeMCU module.

After uploading two files to NodeMCU dev kit you can see the message like the one attached
above on your ESPlorer serial monitor. Copy the IP address and paste on your browser.
 
You can open your browser to check your Temperature and Humidity data, Images in the web
browser are served from external sources you can use some other images to look more
attractive.

Lua basics
Variables
Variable names must be single words containing only characters, numbers or underscores.
They can be local or global. As Lua is type free, there is no need to specify a type before the
variable name (as in C languages). Lua supports the following variable types;
Numbers
As Lua is type free, you do not need to worry about ints or floats etc. Lua will handle the
precision as needed.
For negatives, use the '-'(minus) character BEFORE the number.
For decimals, use the '.'(dot) character at the decimal place, NOT the ','(comma) character.
Strings
Strings, ("a string"). Using double or single quotes is fine, but end with the same one as
started with.
ESCAPE Sequence Use
\a Bell
\b Backspace
\f Formfeed
\n New line
\r Carriage return
\t Tab
\v Vertical tab
\ Backslash
\” Double quotes
\’ Single quotes
[ Left square bracket
] Right square bracket
 
String Methods
String.upper(argument) Returns a capitalized representation
of the argument
String.lower(argument) Returns a lower case representation
of the argument
String.gsub(mainString, finString, Returns a string by replacing
replaceString) occurances of findingString with
replaceString
String.strfind(mainStr, findStr, Returns the start index and end index
StartInd, EndInd) of the string in the main string and
nil if not found
String.reverse(arg) Returns a string by reversing the
characters of the passed string.
String.format(…) Returns a formatted string
String.char(arg)and stringbyte(arg) Returns internal numeric and
character representations of input
argument
String.rep(string,n) Returns a string by repeating the
same string n number of times
.. Thus operator concatenates two
strings.
   
 
Boolean             
              Boolean , a true of false variable. The keywords are lower case “true” and “false”4
nil
Nil means nothing, and as such you will get it back whenever you call something that doesn't
exist.

nil can be used to destroy a variable as well, in the following manner;

killMe = nil

Lua garbage collector will free the memory up on its next pass.
Operators/ conditionals
Arithmetic
Operator Description
+ Addition
- Subtraction
* Multiplication
/ division
% Modus operator
^ Exponent operator
 
Logical
Operator Description
And Logical AND operator ( A: &&)
Or Logical OR operator (A: ||)
Not Logical NOT operator (A:~)
 
Relational
Operator Description
== True if the value of the two operands
are the same
~= True if the value of two operands are
different
> True if the value of left operand is
greater than the value of right
operand
< True if the value of the left operand
is less than the value of the right
operand
>= True if the value of the left operand
is greater than or equal to the value
of right operand.
<= True if the value of left operand is
less than or equal to the value of
right operand.
 
If statements
If a = = 1 then
… logic…
Elseif op ==2 then
…logic….
Else
..logic..
End
Loops
While loop
While (true)
do
              print(‘Nodemcu’)
end
 
For loop
for i=10,1,-1
do
              print(i)
end
lua has a for iterator, which will simply iterate, it takes 3 parameters
1)      The starting or counter usually followed by a variable in the above example it is
i=10
2)    The end place inclusive, given as a number.
3)    The incremental operator, how much the initial counter should increase or decrease
Functions
Function sum(num1,num2)
return num1+num2
end
function has the ability to assign pass variable to and fro in the program, you don’t need to
write certain steps repetitive in the program.
 
 
Example:
Function multiply(num1, num2, fun)
a=0
for i=num2, i, -1
do
a = a + fun(num1, num1)
end
return a
end
function calling
func = sum ()
a = multiply(2,2,func)

Getting Started on OSX (solution by NodeMCU)


Getting started with NodeMCU devkit on OSX, if you are using NodeMCU it uses a serial
driver from SiLabs you need to download it , if you have used any Arduino clones before you
would have known about this serial driver chip software , it can be downloaded from the link
here.
ESPlorer works well with OSX, apart from that there are many other software you can use it.
To flash the firmware you need special flags:
Download the nodemcu firmware,
Install esptool:
Follow the command in your terminal window.
git clone https://github.com/themadinventor/esptool.git
cd esptool
sudo python ./setup.py install
 
Hold down the “FlASH” button on the device and hit the”RST” button while doing so.
Substituing in the correct path to the firmware file you downloaded, run
python ./esptool.py --port=/dev/cu.SLAB_USBtoUART  write_flash  -fm=dio -fs=32m 0x00000 ../nodemcu-master-8-
modules-2015-09-01-02-42-13-float.bin
 
Unplug the device and replug it.

Port Forwarding Example


We have seen how to control and upload data to webserver, when you are accessing data from
webserver it can be done only when your device are connected to same access point, what if
you want to control and access data from any part of the world, you need to do port
forwarding your IP address so that you can control and access your ESP8266 or Nodemcu
from any part of the world.
              For this example I am using TP-Link router, I use this modem for my Wi-Fi, if you
are using different router you can check it out to know how to port forward with your router, if
you are using the same router then you can follow this tutorial.
Step 1: Log into the router's web management page: This can be done by typing 192.168.0.1
in your browser and type admin and admin for user name and password.
Step 2: Click forwarding > Virtual servers on the left side, and then click add new button

Step 3: after clicking the Add new button, Add or Modify a virtual Server Entry page will be
opened , in this you have to enter the details of Service port, Internal Port, Ip address
Service port is the Server port number you have entered in the Lua program, usually this will
be 80 by default,

leave the internal port blank and type the IP address as the ESP8266 connected with your
router this is the IP address each time when a ESP8266 connected to your router leave a local
IP which can be find from the serial monitor.
 
 
 
 
 
Click the Save button to save the setting you have done previously
Step 5:  Go to Status Page and check the WAN IP Address of the router. Copy the WAN IP
and port number to access the service from outside the network. Now you can access your
ESP8266 from any part of the world, you can control your Home lights from anywhere by
calling the IP address in your web browser or mobile browser.

For the above example I used port number 80 which is the default number for my router
management, which should be changed to use the port number 80 by the ESP8266 this can be
done by clicking the Security tab on the left side of the router management page.

If the WAN IP Address of the router is not a public IP Address, but a Private IP Address, that
means there is another NAT device connected to the WAN Port of the TP-LINK router, you
need open the service ports on that device as well.
 
 
Building Custom Firmware for NodeMCU
              Nodemcu firmware which consist of all the functions in some cases we never require
all the functional capabilities of the NodMCU in such cases, external community members
have built a website where anyone can build a custom firmware by choosing their required
API for their project.
Go to website http://nodemcu-build.com/
Select the modules that you want to include in the custom firmware for your project.

Click on the start build button on the bottom of the page, NodeMCU dev kits may come with
4MB memory flash, if you are using other generic devices it will run out of the memory if we
use all of the modules.
Components Need for this book
Esp8266 development kit or Nodemcu or any other development kit using Esp8266
LED
RELAY
BMP180 (I2C) sensor
DHT22 Temperature and humidity sensor
DHT11 Temperature and humidity sensor
 
Contact
For suggestions and queries you can always mail me at jayakumarmagesh@gmail.com
all the code and necessary documents for this book can be find here.

 
 

You might also like