You are on page 1of 117

Copyright

NodeMCU Development Workshop
Agus Kurniawan
1st Edition, 2015
Copyright © 2015 Agus Kurniawan

Table of Contents
Copyright
Preface
1. Preparing Development Environment
1.1 NodeMCU
1.2 Electronics Components
1.2.1 Arduino Starter Kit
1.2.2 Fritzing
1.2.3 Cooking-Hacks: Arduino Starter Kit
1.2.4 Arduino Sidekick Basic kit v2
1.2.5 Grove - Starter Kit for Arduino
1.2.6 DFRobot - Arduino Kit for Beginner v3
1.3 Development Tools
1.4 Testing
2. Setting Up NodeMCU
2.1 Getting Started
2.2 Connecting NodeMCU board to Computer
2.3 Flashing The Latest NodeMCU Firmware
2.3.1 Windows Platform
2.3.2 Linux and OS X Platforms
2.4 Development Tools
2.4.1 Serial/UART Tool

3.3 Demo 3.11 Iteration - for 3.3 Uploading Lua Script File to NodeMCU Board 3.13 Iteration - repeat .7 Increment and Decrement 3. Lua Programming Language 3.3 NodeMCU Studio 2.3.2 Assigning Variables 3.2 Common Rule 3.2.2 Arduino IDE 2.5.5 Hello NodeMCU: Blinking LED 2.then 3.5 Arithmetic Operations 3.5.1 Preparing Development Environment 3.3 Variables 3.5.1 Wiring 2.2 Writing Program Using Serial/UART Tool 2.4 Comment 3.6 Mathematical Functions 3.8 Comparison Operators 3.3..4.1 Declaring Variable 3.9 Logical Operators 3.10 Decision - if.12 Iteration - while 3.4.

4 Testing 5.17 Lua Modules 4.1 Getting Started 6. GPIO Programming 4.3.1 Getting Started 5.3.3 Demo Analog Input: Working with Potentiometer 5.2 Writing Program 5.3 Testing 6.2 Writing Program 5.15 Array 3. PWM and Analog Input 5. Working with I2C 6.3.1 Wiring 5.3.16 Functions 3.3 Writing a Program 4.2.3 Testing 5.2.1 Wiring 5.3 Writing Program .2 Demo Analog Output (PWM) : RGB LED 5.1 Getting Started 4.14 break and do 3.2 Writing Program 6.2 Wiring 4.2.

4 Testing 9.1 Connecting to a WiFi Hotspot 10.6. SPI 8.2 Building a Simple Web Server Source Code Contact . Connecting to a Network 10.3 Writing a Program 8.2 Wiring 8.3 Writing a Program 9.4 Testing 7.2 Wiring 7.4 Testing 8.1 Getting Started 7.4 Testing 10.3 Writing a Program 7.1 Getting Started 9. Working with OLED Display 9.1 Getting Started 8.2 Wiring 9. UART 7.

Agus Kurniawan Depok. Preface This book was written to help anyone want to get started with NodeMCU v2 board development. July 2015 . It describes the basic elements of NodeMCU development starting with Lua programming.

Preparing Development Environment .1.

You can buy this product on your local electronic store.dx.1. NodeMCU was created shortly after the ESP8266 came out.html .1 NodeMCU NodeMCU is an open source IoT platform. http://www. http://www.com eBay.com/index_en.com/ Amazon. you can read it on http://nodemcu.ebay. The following is a form of NodeMCU v2.seeedstudio.amazon.com/ . http://www.com/ DX. http://www. http://www. It uses the Lua scripting language.banggood. Further information.com Banggood. The following is the list of Arduino store you can buy SeeedStudio.

2 Fritzing Store website: http://shop. Resistor. 1.2.2 Electronics Components We need electronic components to build our testing. We can use electronics kit from Arduino to be developed on NodeMCU.2. for instance. LED. .fritzing.1. You can buy Fritzing Starter Kit with Arduino UNO or Fritzing Starter Kit with Arduino Mega. sensor devices and etc.org/ . I recommend you can buy electronic component kit. The following is a list of electronics kit which can be used in our case.1 Arduino Starter Kit Store website: http://arduino.cc/en/Main/ArduinoStarterKit 1.

2.cooking-hacks.php/shop/arduino/starter- kits/arduino-starter-kit.1.com/index.html .3 Cooking-Hacks: Arduino Starter Kit Store website: http://www.

http://www.de/seeed-studio-sidekick-basic-kit-for-arduino-v2 .1.com/depot/Sidekick-Basic-Kit-for-Arduino-V2-p- 1858.exp-tech.seeedstudio.4 Arduino Sidekick Basic kit v2 Store website: http://www.html You also can find this kit on this online store.2.

2.com/depot/Grove-Starter-Kit-for-Arduino-p-1855. http://www. http://www.6 DFRobot - Arduino Kit for Beginner v3 DFRobot provides Arduino kit too.2.1.html .seeedstudio. you can buy this kit on Seeedstudio.com/index.php?route=product/product&path=35_49&product_id=345 .5 Grove - Starter Kit for Arduino Another option. You can buy it on the following website.dfrobot. 1.

.

.1. we can use any editor. In this book. I use Arduino IDE for text editor.3 Development Tools To develop app with NodeMCU target. You can learn how to install it on chapter 2.

4 Testing For testing. I used NodeMCU v2 on Windows 8.1. I also used Arduino Sidekick Basic kit for electronic components. .1.

Setting Up NodeMCU This chapter explains how to work on setting up NodeMCU board. . 2.

1 Getting Started In this chapter. We try to reflash the latest NodeMCU firmware and then test some basic scripts. . we learn how to get started with NodeMCU board.2.

After connected. you connect NodeMCU board to PC via microUSB cable. If you are working on Windows platform. . you may get lighting on blue LED.2.2 Connecting NodeMCU board to Computer Firstly. you should see NodeMCU board detected on Ports (COM & LPT). open Device Manager.

Please download it based on your platform. . you update that driver.However. Just follow instructions. you download the driver for mac.aspx . from https://www.silabs. For instance. if you get a problem about NodeMCU hardware driver.com/products/mcu/Pages/USBtoUARTBridgeVCPDrivers. You also can install a driver from Silicon Labs because NodeMCU v2 uses this chip.

. Type this command.After installed. ls /dev/cu* For Linux. you verify it. This board is recognized as /dev/cu. on my OS X it has detected. you can use ls /dev/tty* .SLAB_USBtoUART . Then. For instance. you see a list of driver.

on your computer. . For instance.Next up. use a serial console program such as CoolTerm (Mac) or Putty (Windows) or screen (linux) to connect to NodeMCU board. I used PuTTY on Windows.

I will explain it on the next section. we must flash the latest NodeMCU firmware. you should get NodeMCU shell in Lua script. shown in Figure below. . You may get a problem. In this case.If success.

you can use NodeMCU flasher. x86 and x64.2. Select COM Port where NodeMCU was attached. To flash firmware.bin file.com/nodemcu/nodemcu-firmware . I try to flash NodeMCU firmware on Windows. click Advanced tab.3 Flashing The Latest NodeMCU Firmware In this section.com/nodemcu/nodemcu-flasher . There are two binary platforms. 2. . I show you how to flash it on Windows platform.3. OSX and Linux. Please download NodeMCU Flasher on https://github. Open the program so you get the dialog as below. In this scenario. Download *. Select Baudrate 5700 and SPI Mode is DIO. You can get the latest NodeMCU firmware on https://github. Then. we try to flash the latest NodeMCU firmware.1 Windows Platform In this section.

. On Operation tab.Click Config tab and select firmware file. you start by clicking Flash button.

you can use serial/UART tool and connect to NodeMCU board. If success.If done. . Then. Set NodeMCU serial port and set baudrate 9600. you should see NodeMCU shell. you will get a notification. connect to the board. To test.

you need to install wine tool.Try to write a simple script print(“Hello NodeMCU”) so you will get a response. to emulate for running on Linux or OS X. you can use esptool. Just follow the instruction. . https://www. I show you how to flash NodeMCU using Flasher.com/viewtopic. 2.org . install wine tool. This tool actually runs Windows platform.2 Linux and OS X Platforms If you’re working on Linux or Mac.3.espressif.py tool from https://github. Flash Download tool. Firstly.php?f=5&t=433 . In this section.winehq. You can type this command on Linux platform.com/nodemcu/nodemcu-firmware/tree/master/tools . for instance. In this case. from http://bbs.

Then.SLAB_USBtoUART so I map it to com1 . Set CrystalFreq 26M. download the latest Flashing tool from Espressif on http://bbs. Navigate to dosdevices folder and create a symlink to your NodeMCU tty device. $ brew install unrar After extracted. $ wine flash_download_tool_v1. For instance. run it via wine. $ sudo add-apt-repository ppa:ubuntu-wine/ppa $ sudo apt-get update $ sudo apt-get install wine1.espressif. Select COM Port to com1 . navigate to flashing too.2_150512. SPI SPEED 40MHz and SPI MODE DIO. you can install it via brew $ brew install wine Then. FlASH SIZE 32Mbit. on OS X my NodeMCU has detected on /dev/tty.SLAB_USBtoUART com1 You can close and run this tool. wine directory has created. you can install it via brew on OS X platform. For instance.Ubuntu Linux. Now you can flash NodeMCU firmware for NodeMCU v2 with the following parameters.php?f=5&t=433 .7 If you’re working with OS X. see green highlight.wine/dosdevices $ ln -s /dev/tty. $ cd ~/.exe After running.com/viewtopic. you need unrar. To extract this file.

It will flash firmware to the board.If done. click START button. .

If done. you should see Lua shell. . try to connect. Select serial port of NodeMCU and set baudrate 9600. Then. If success. you can test it using Serial/UART tool.

You can write simple program using print(). . > print("Hello NodeMCU") Shell will response this script.

.

1 Serial/UART Tool By default. https://github.4 Development Tools In this case.2 Arduino IDE If you have experience in Arduino development. http://ttssh2.en . http://realterm.4.net/ and Tera Term. .osdn.2.html.sourceforge. you can use Serial/UART tools such as CoolTerm (Mac) or Putty (Windows) or screen (linux) . Open Arduino IDE. 2. You also can use Realterm.4.com/esp8266/Arduino .jp/index. I show you several development tools you can use it in NodeMCU development. You can use add-on on your Arduino using this library. you can use Arduino IDE to develop NodeMCU board too. 2.

If you have the list on there.json on Additional Boards Manager URLs . . for new list item. click menu File -> Prefernces (Windows/Linux) or Arduino -> Preferences (OS X) so you should see Preferences dialog.com/package_esp8266com_index. Add http://arduino.Then. just add .esp8266.

If done. Click menu Tools -> Board -> Boards Managers. . click OK button.

After installed. you can see a list of ESP8266 Modules target on Arduino IDE.Then. . you should see Boards Manager dialog. Find esp8266 board and install it.

We can wait the released version of this tool.Now you can write the program for NodeMCU.4. . 2. You may get problems while you are developing a program.3 NodeMCU Studio This tool is still development tool and written in C#. You can download this tool on https://github.com/nodemcu/nodemcu-studio-csharp .

.

We use serial tool to write a program.2. you must know NodeMCU GPIO.5. Other LED pin is be connected to NodeMCU GND. 2. Now you connect NodeMCU board to Computer via USB cable.1 Wiring Connect LED on NodeMCU D1. The following is NodeMCU v2 GPIO.5 Hello NodeMCU: Blinking LED In this section. we build a blinking LED program via Lua shell. . Firstly.

write(pin.2 Writing Program Using Serial/UART Tool The first demo is to blink a LED.write(pin.OUTPUT) gpio.lua pin = 1 gpio.mode(pin.HIGH) print(gpio.gpio. -- hello.gpio.5.LOW) This script will turn on a LED on D1 and then turn off it.gpio.2.read(pin)) gpio. . Type this script per lin on Serial/UART tool.

Type this script. gpio.HIGH). Now we try to build a blinking LED. -- blinking_led.lua .write(pin.If you should see lighting LED after executed gpio.

If you want to stop.OUTPUT) while 1 do gpio.gpio.HIGH) tmr.LOW) tmr.com/4refr0nt/luatool . This program uses Python to run the Lua file.3 Uploading Lua Script File to NodeMCU Board In this section.write(pin. you can press RST button on NodeMCU board. pin = 1 gpio. .delay(1000000) end You should see a blinking LED.delay(1000000) gpio. luatool needs pyserial library to access UART on NodeMCU.gpio.5. Please install Python on your platform. I show you how to upload our Lua file to NodeMCU board and then execute it. Just run Command Prompt with Administrator level. 2. You can install it via pip or easy_install sudo easy_install -U pyserial Remove “sudo” if you’re working on Windows platform. We can use luatool from https://github.mode(pin.write(pin.gpio.

lua. $ wget https://raw.py --port /dev/cu. $ .githubusercontent. If your installed Python is python. then change code on the top of script. /dev/ttyAM0. . I use blinking led from section 2./luatool. Save that script into a file. COM5. $ wget https://raw.2.SLAB_USBtoUART --src blinking_led. called blinking_led.py For testing.githubusercontent. $ sudo chmod a+x luatool. for instance.Now you can download this tool using wget or download it directly on Github website.com/4refr0nt/luatool/master/luatool/main. #!/usr/bin/env python2 to be the following script.com/4refr0nt/luatool/master/luatool/init.com/4refr0nt/luatool/master/luatool/luato $ wget https://raw.githubusercontent. Type this command to upload to NodeMCU board. Now you can set access right on this file so you can execute it.5. from this script.lua --dest bli Change —port parameter based on your attached NodeMCU board. #!/usr/bin/env python Save this code.

If done.lua") . connect to NodeMCU via serial tool and type this command. > dofile("blinking_led. this file will be available on NodeMCU. To execute this file.

Warning!! if your main. This file will be executed by NodeMCU. If you modified codes and upload the file again.lua --dest bli This command will upload Lua file and then execute it. you can write Lua file with named main. you must press RST to make sure NodeMCU doesn’t keep your file.lua is error.lua. $ . you can add —dofile parameter on your command. . Sometimes you want your program run after NodeMCU restarts. Type this command.py --port /dev/cu.If you want to upload and execute Lua script file.SLAB_USBtoUART --src blinking_led. you will get problem on NodeMCU./luatool.

. Lua Programming Language This chapter explains the basic of Lua programming language. you can skip this chapter. 3. If you already know about Lua programming.

you can execute Lua and run some Lua syntax. .org based your platform. you can press CTRL+D keys.3.lua. $ lua > print("Hello Lua") > a = 5 + 8 > print(a) If you want to quit from Lua shell. $ brew install lua After installed. you can install it via brew. You can download it on http://www. we must install Lua compiler and its runtime.1 Preparing Development Environment To work with Lua development. For OS X user.

3.” at the end of syntax. Here is the syntax rule: syntax_code1 syntax_code2 syntax_code3 .2 Common Rule You can write Lua script without ending “.

3. 3.3. create a file. called basic.2 Assigning Variables Variable that you already declare can be assigned by a value. n Once declared.lua.3.lua. you would write this: city = "Berlin" m = 2 n = 5 We also can declare a variable and assign its value. these variables can be used to store any type data. For example. n -- assignment city = "Berlin" m = 2 n = 5 -- declare and assign variables . and n you can write the following script: local city local m.1 Declaring Variable To declare a variable called city.3 Demo For illustration for declaring variables using Lua. -- this a simple script for Lua -- declare variables local city local m. 3. variable city will assign a string value “Berlin”. Write the following script for basic.3 Variables In this section. we explore how to define a variable and assign its value. It can done using the equals sign (=).3. 3. m.

Then. .q = 10. 12 print(city) print(m) print(n) print(a) print(str) print(p) print(q) Save this file. a = 6 str = "Hello world" local p. try to build and run it. $ lua basic.lua A sample output can be seen in Figure below.

Here is sample code: -- this a simple script for Lua -- declare variables local city local m. you can use — syntax.3. To do it.4 Comment You may explain how to work on your code with writing comments. n .

multiplication. create a folder arithdemo.lua. .4 c = a + b d = a - b e = a / b f = a * b print(c) print(d) print(e) print(f) Then.5 Arithmetic Operations Lua supports the same four basic arithmetic operations such as addition.3. subtraction. The following is the code illustration for basic arithmetic in arithdemo. Then.lua: -- basic arithmetic a = 3 b = 2. called arithdemo. For testing. create a file. The following is a sample output. try to build and run it. and division.

Create a file.sqrt(a * b) g = math. called mathdemo.5 b = 1.sin(a) e = math. .3.cos(b) f = math.pow(a.6 Mathematical Functions We try to work with math library.2) d = math. -- math demo a = 2.lua.pi print(c) print(d) print(e) print(f) print(g) Then. The following is a sample output. and write this script.6 c = math. try to build and run it.

increment a = a + 1 decrement. try to build and run it. .3. -- increment and decrement a = 4 print(a) -- increment a = a + 1 print(a) -- decrement a = a - 3 print(a) Then.lua and write this script. called incdec. a = a - 1 Create a file.7 Increment and Decrement We can write a script for increment and decrement using Lua.

8 Comparison Operators You may determine equality or difference among variables or values. Here is the list of comparison operators: == is equal to ~= is not equal > is greater than < is less than >= is greater than or equal to <= is less than or equal to This is sample code for comparison usage. -- comparison a = 3 b = 10 print(a < b) print(a > b) print(a <= b) print(a >= b) print(a == b) print(a ~= b) Build and run it.3. . A sample output of the program can be seen in Figure below.

3. called logical. and and or or not not Sample code: -- logical operators a = 3 b = 4 print(a<b and a>1) print(a>b or a>4) print(a<b and not (a>4)) Save this script into a file.9 Logical Operators These operators can be used to determine the logic between variables or values. A sample output of the program can be seen in Figure below.lua. Build and run it. .

-- ifthen demo a = 3 if a>1 then print("a>1") b = 3 print(b) else print("a<1") b = 10 print(b) end Now you can run it...3. . A sample output of the program can be seen in Figure below.then Syntax model for if.10 Decision - if.then can be formulated as below: if conditional then -- do something else -- do something end conditional can be obtained by logical or/and comparison operations.

A sample output of the program can be seen in Figure below.step do end For testing. write this script into a file.11 Iteration - for Iteration operation is useful when we do repetitive activities.1 do print(i) end Save this file and run it. for initialization.3.lua.10.end number. . for i=1. The following is for syntax. fordemo.

.lua. A sample output of the program can be seen in Figure below.12 Iteration - while Lua provides while syntax to do a looping. Write this script for testing. i = 1 while i < 10 do print(i) i = i + 1 end Save this code into a file. Build and run it. called whiledemo.3.

3. For a sample demo. . type these scripts. Then. run this demo. n = 5 repeat print(n) n = n + 1 until n > 12 Save these scripts into a file. called repeatdemo.13 Iteration - repeat Lua also provides repeat syntax to do looping.lua.

lua and run it. Write these scripts for testing. A sample output of the program can be seen in Figure below.3. print("--break demo---") n = 1 while n < 10 do print(n) n = n + 1 if n == 7 then do break end end end Save them into a file.14 break and do break can be used to stop on the code point. We can use “do break end” to stop our looping. . called breakdo.

Lua provides array called Tables. Then. type these scripts. For testing.#cities) print(cities[3]) print("length numbers:". . 4. #cities do print(cities[i]) end Save them into a file. cities = {"tokyo".15 Array Like other programming language. run it. we can use #variable_name. 10. To get a length of array. called array. We can define an array using {}.#numbers) print(numbers[5]) -- display all content of array print("--display array") for i=1. 8.3. 6. "london". "new york".lua.12} print(cities) print("length:". "berlin"} numbers = {2.

16 Functions A function can be used to save your redundant activities. . run it.b) return a + b end print("---function demo---") foo() c = add(10. 5) print(c) Save into a file. Let’s write these scripts for testing. function foo() print("calling from foo()") end function add(a. called functiondemo. Then.3.lua. We can define a function using (). It can attach parameters and return a value.

b. require("simplemodule") print("--load module--") res = add(10.lua and write these scripts. b) return a + b end function compute(a.3. create a file.lua on our code.lua.17 Lua Modules A module may consists of functions. function add(a. we call simplemodule. 8) print(c) Save all files. It can save your development time due to reusable API. 4) print(res) c = compute(5. Run our program on loadmodule. . called loadmodule. we just create a Lua file and called it. For illustration.lua and write these scripts. Create a file. called simplemodule. 6. c) return a + b - c end Then. To build a module in Lua.

4. GPIO Programming In this chapter I’m going to explain how to work with GPIO on NodeMCU and write a program. .

https://github. we build a program to illustrate how NodeMCU GPIO work.4. We can use gpio. In this chapter.read() to read GPIO value and gpio. we define our GPIO mode using gpio. It can be either GPIO output or GPIO input.write() to write HIGH/LOW to GPIO pins.mode(). Let’s start!. GPIO can be used to control digital I/O on NodeMCU.1 Getting Started In general. . Firstly. A list of NodeMCU API can be read on this site.com/nodemcu/nodemcu- firmware/wiki/nodemcu_api_en . We need a LED and a pushbutton.

The following is a sample of wiring.2 Wiring Connect LED to D1 on Arduino and pushbutton to D2. .4.

OUTPUT) gpio. .LOW) else gpio.lua.4.INPUT) while 1 do state = gpio.read(pushbutton) if state==0 then gpio. Then.delay(1000000) end Save these scripts.write(led.gpio. write these scripts.HIGH) end print(state) tmr.gpio.write(led.gpio. we just create a new Lua file.mode(led.mode(pushbutton. led = 1 pushbutton = 2 gpio.gpio.3 Writing a Program To create a program. called gpiodemo.

You should see a lighting LED. try to press pushbutton. For testing.4. You also see the program output if you connect to NodeMCU board via Serial app. .4 Testing Now you can upload and run this program to NodeMCU board.

.

. PWM and Analog Input This chapter explains how to work with NodeMCU Analog I/O. 5.

In this chapter. See the following of NodeMCU GPIO. . we try to access NodeMCU Analog I/O using Lua program.1 Getting Started NodeMCU board provides Analog I/O which can be connected to sensor or actuator devices. There are two scenarios for our cases: Controlling RGB LED Reading Analog input using Potentiometer Let’s start.5.

5. To understand these pins. Note: Pin 1: Red Pin 2: Common pin . RGB LED has 4 pins that you can see it on Figure below. you can see the following Figure.2 Demo Analog Output (PWM) : RGB LED In this scenario we build a Lua program to control RGB LED color using NodeMCU Analog output (PWM).

Pin 3: Green Pin 4: Blue Now we can start to build a Lua application and hardware implementation. RGB LED pin 1 (red) is connected to NodeMCU D1 RGB LED pin 2 is connected to NodeMCU 3V3 (VCC +3. NodeMCU provides API for PWM which can set a value from 0 to 1023 using pwm. write these scripts. called rgbdemo. 5. we only work with PWM maximum 3 PWM simultaneously. Let”s start to build a program.1 Wiring For our testing. Based on NodeMCU Lua API.setup().lua. blue. we must combine colors from red. create a file. we configure the following PWM pins.2. Firstly. green.3V) RGB LED pin 3 (green) is connected to NodeMCU D2 RGB LED pin 4 (blue) is connected to NodeMCU D3 Here is a sample implementation with NodeMCU and RGB Led 5. Then.2 Writing Program To display a certain color. red = 1 .2.

delay(1000000) print("yellow") set_rgb(0. 100. purple. b) pwm. 1023) tmr. 1023) tmr.start(red) pwm.start(green) pwm. blue. 0. 1023.3 Testing . g. b) print(r.stop(red) pwm. 0.stop(green) pwm.setup(green. 0.setup(red. yellow. green.delay(1000000) stop_all_pwm() print("green") set_rgb(1023.setup(blue.b) pwm. g) pwm. 5.start(blue) end function stop_all_pwm() pwm. 1023. 1023.delay(1000000) print("aqua") set_rgb(1023.delay(1000000) print("blue") set_rgb(1023. r) pwm.g.delay(1000000) end This program will generate six colors: red. 100.2.stop(blue) end while 1 do print("red") set_rgb(0. 0) tmr. green = 2 blue = 3 function set_rgb(r. 100. Save this file.delay(1000000) print("purple") set_rgb(700. 700) tmr. and aqua. 1023) tmr. 0) tmr.

shown in Figure below.Upload and run the program. You should see several color on RGB LED. The following is a sample demo on RGB LED. you should get program output. If you connect to NodeMCU board via Serial app. .

.

5.1 Wiring To understand Potentiometer. I use Potentiometer as analog input source. Vout to NodeMCU board Analog input A0.3 Demo Analog Input: Working with Potentiometer In this section. Our scenario is to read analog value from Potentiometer.3V). The following is hardware implementation. NodeMCU v2 only has one ADC on A0. In this section. we learn how to read analog input on NodeMCU board. . You can connect VCC to NodeMCU board on 3V3 pin (VCC +3. display it on Lua shell. GND to NodeMCU board GND. you see its scheme in Figure below. you must expand it using ICs based ADC. Then. In addition.5. For illustration. I use slide potentiometer. Let’s start!.3. If you want to work with many analog input. we are working on NodeMCU ADC on A0.

lua. 5.2 Writing Program Firstly.3 Testing Upload and run this program. print("ADC demo") while 1 do print("reading…") val = adc.read() function. we can use adc.val) tmr.delay(1000000) end Save this code. create a file.3.3. called adcdemo. Let’s write these scripts.5. If success. Ok. you can see analog value on Serial app. . To read analog input.read(0) print("Analog: ".

.

. Working with I2C In this chapter we learn how to work with I2C on NodeMCU board using Lua script. 6.

NodeMCU v2 has I2C/TWI on SD0 (SDA). I used PCF8591 AD/DA Converter module with sensor and actuator devices.aliexpress. SD2 (SDA).com Dealextreme. http://www.dx. SD3 (SDA) and CLK (SCL).1 Getting Started The I2C (Inter-Integrated Circuit) bus was designed by Philips in the early ’80s to allow easy communication between components which reside on the same circuit board. http://www. TWI stands for Two Wire Interface and for most marts this bus is identical to I²C.com/PCF8591-Converter-Module-Digital- Conversion/dp/B00BXX4UWC/ eBay. http://www.ebay. SD1 (SDA). For testing. You can find it on the following online store: Amazon. I2C bus consists of two wires.com/p/pcf8591-ad-da-analog-to-digital-digital-to- analog-converter-module-w-dupont-cable-deep-blue-336384 Aliexpress. SDA (Serial Data Line) and SCL (Serial Clock Line).amazon.6. The name TWI was introduced by Atmel and other companies to avoid conflicts with trademark issues related to I²C. http://www.com/ .

for instance.amazon.com/documents/data_sheet/PCF8591.electrodragon.com/WaveShare-PCF8591T-Converter-Evaluation- Development/dp/B00KM6X2OI/ . http://www. This module use PCF8591 IC and you can read the datasheet on the following URLs. http://www.pdf http://www.nxp.com/w/images/e/ed/PCF8591. This module has mini form model too.In addition. you can find it on Amazon.pdf . you can find this device on your local electronics store/online store.

I usually use this module to test I2C but NodeMCU v2 firmware doesn’t support with I2C
address 0x90. Basically you can modify firmware code and then built it.
In this chapter, we build a program to access sensor via I2C using Lua script and use
Arduino as I2C slave. We can use any pin on NodeMCU GPIO for I2C using I2c library
from NodeMCU firmware.

6.2 Writing Program
We use Arduino Uno as I2C source. You can connect Arduino Uno to NodeMCU board
directly.
The following is our wiring lab:

Arduino Uno SDA (A4) —> NodeMCU SDA (D1)
Arduino Uno SCL (A5) —> NodeMCU CLK (D2)
Arduino Uno GND —> NodeMCU GND

Hardware implementation can be shown in Figure below.

6.3 Writing Program
The first step is to write Arduino program. We can use Wire library to interact with I2C. In
this case, our Arduino acts as I2C slave and sends random byte.
Open Arduino IDE and write this code.
#include <Wire.h>

const byte SLAVE_ADDRESS = 0x15;
int led = 13;
byte x;

// source:
// http://forum.arduino.cc/index.php?topic=197633.0
byte randomDigit() {
unsigned long t = micros();
byte r = (t % 10) + 1;
for (byte i = 1; i <= 4; i++) {
t /= 10;
r *= ((t % 10) + 1);
r %= 11;
}
return (r - 1);
}

void sendData(){
byte data = randomDigit();
data = data + 30;
Wire.write(data);
Serial.println(data);
}

void setup() {
pinMode(led, OUTPUT);
Serial.begin(9600);
Wire.begin(SLAVE_ADDRESS);
TWBR = 152; // 50 kHz speed
Wire.onRequest(sendData);
}

void loop() {
delay(500);
}

Compile and upload this program to Arduino board.i2c.lua and write these scripts.sda. id=0 sda=1 scl=2 ARDUINO_I2C = 0x15 i2c. called i2cdemo. Create a file. Now you can start to write a Lua program for NodeMCU.dev_addr) .SLOW) function read_data(id.setup(id.Save this code.scl.

string.start(id) i2c. .delay(1000000) end Save this code.stop(id) return c end print("I2C demo") while 1 do val = read_data(id.RECEIVER) c = i2c.read(id. dev_addr.1) i2c.i2c. ARDUINO_I2C) print("RCV: ".byte(val)) tmr.1) c = i2c. i2c.read(id.address(id.

The following is a sample output. If success.4 Testing Now you can upload and run the Lua program to NodeMCU board.6. open Serial app and connect to NodeMCU to see the program output from Lua shell. You also can see the Arduino output using Serial Monitor. .

.

7. . UART In this chapter I’m going to explain how to access UART on NodeMCU board.

To listen incoming messages from UART uart.7.on(). The following is Lua API for UART: uart. I use Arduino board as UART source. uart. We read incoming message from UART.1 Getting Started NodeMCU v2 provides two UART but we only able to use one UART. . Let’s start!. You can read Lua API to access NodeMCU UART on https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en . databits. echo. To write data into UART In this chapter. parity.setup() . To setup UART such as baud.write(). stopbits.

The following is our wiring.7.2 Wiring In this scenario. I use Arduino Uno which is connected to NodeMCU board. . NodeMCU D10 (TXD0) is connected to Arduino Digital 10 NodeMCU D9 (RCD0) is connected to Arduino Digital 11 NodeMCU GND is connected to Arduino GND My wiring implementation can be seen in Figure below.

This program will wait incoming UART data and then send to Arduino UART on 0 and 1 pins. We use SoftwareSerial to access Serial on Digital 10 and 11. we write a program for Arduino using Arduino IDE.read()).begin(9600). } void loop() { if (mySerial.3 Writing a Program Firstly. } } .7. // RX.available() > 0) { Serial. Write this program.write(mySerial. mySerial.h> SoftwareSerial mySerial(10. #include <SoftwareSerial. 11). TX void setup() { Serial.begin(9600).

1."\r\n") val = val + 1 . 0. called uartdemo. 1. 9600.string.Save this program. 8. Write these scripts. and 11 pins) doesn’t connect to any board. Create a file. Then. please make sure Arduino UART (digital 0. 0) val = 65 -- looping while 1 do uart. uart.write(0.setup(0.char(val). Before uploading.lua. 10. upload it to Arduino board. The next step is to write a program for NodeMCU board.

if val>90 then val = 65 end tmr.delay(1000000) end Save this file. .

connect NodeMCU UART to Arduino UART (Digital pins: 10 and 11). Set baud 9600 and No line ending. You should see the UART output. . Don’t connect NodeMCU UART to Arduino while uploading a program. If done.7. To see the UART output. open Serial Monitor tool from Arduino IDE.4 Testing Now you can upload and run Lua program.

8. SPI In this chapter I’m going to explain how to work with SPI on NodeMCU board. .

If we’re working on SPI. we can’t access UART on the board. In this chapter. Let’s start!. shown in Figure below. I use Arduino board as SPI slave. We can only use one SPI on NodeMCU board with SPI master mode. SPI in NodeMCU board can be defined on the following pins: MOSI MISO SCK You can see these pins on S NodeMCU board.1 Getting Started The Serial Peripheral Interface (SPI) is a communication bus that is used to interface one or more slave peripheral integrated circuits (ICs) to a single master SPI device.8. usually a microcontroller or microprocessor of some sort. .

Do wiring as follows. For testing. I use Arduino board. . we don’t connect MISO pin.2 Wiring To work both SPI and UART/USB.8. NodeMCU MOSI (SD1) pin is connected to Arduino MOSI (Digital 11) pin NodeMCU SCLK (CLK) pin is connected to Arduino SCK (Digital 13) pin NodeMCU GND pin is connected to Arduino GND pin NodeMCU CS (CMD) pin is connected to Arduino SS (Digital 10) pin The following is a sample of wiring.

attachInterrupt().println (buf).h> char buf.3 Writing a Program Firstly. Write these codes on Arduino IDE. if(c>64 && c<91){ buf = c. SPCR |= _BV(SPIE). } } void loop() { if(isAvailable){ Serial. . pinMode(MISO. OUTPUT). isAvailable = false. } ISR (SPI_STC_vect) { byte c = SPDR.begin (9600).8. volatile boolean isAvailable. we write a program for Arduino. isAvailable = true. void setup() { Serial. // for debugging // SPI slave mode SPCR |= bit (SPE). pos = 0. #include <SPI. SPI. volatile byte pos. isAvailable = false. } } This program does wait incoming data from SPI master and then display the received data to Arduino Serial so we can see it on Serial Monitor.

DATABITS_8.Save this program as Arduino_spi. spi. spi.lua.send(1. The next step is to write a program for NodeMCU.char(val)) val = val + 1 if val>90 then val = 65 end . 0) val = 65 while 1 do spi. called spidemo. spi. spi.CPHA_LOW.string.MASTER. spi.char(val)) print(string. Build and upload the program to Arduino board. Create a file. and write these scripts.CPOL_LOW.setup(1.

delay(1000000) end This program will send data ASCII from 65 to 90. Save this code. . tmr.

8. If you connect to NodeMCU board via Serial tool. You should see received data from SPI. .4 Testing Now you can upload Lua program to NodeMCU board. you should see the program output too. open Serial Monitor tool from Arduino. If done.

9. Working with OLED Display In this chapter I’m going to explain how to work with OLED display .

9. Let’s start!.org/wiki/OLED]. An organic light-emitting diode (OLED) is a light-emitting diode (LED) in which the emissive electroluminescent layer is a film of organic compound which emits light in response to an electric current [source: http://en. In this chapter.1 Getting Started We can display characters. we work with OLED display 128x64 with I2C interface which display characters. numbers or symbols using an OLED graphic display module. .wikipedia.

2 Wiring The following is our wiring: NodeMCU SDA (D1) to OLED SDA NodeMCU SCL (D2) to OLED SCL NodeMCU VCC +3.3V to OLED VCC NodeMCU GND to OLED GND The following is a sample of wiring. .9.

10. 40. " 90") . function init_i2c_display() -- SDA and SCL can be assigned freely to available GPIOs local sda = 1 -- GPIO05 (D1) local scl = 2 -- GPIO04 (D2) local sla = 0x3c i2c. 10. 7) end function r_frame(a) disp:drawStr(0. 30. 16+30. 31. and write this code.lua.SLOW) disp = u8g. 40. 20. 18.lua . a+1) end function stringtest(a) disp:drawStr(30+a. 0. 0. 30. "drawDisc") disp:drawDisc(10. "drawBox") disp:drawBox(5. 0.setup(0. 15+30. 7) end function disc_circle(a) disp:drawStr(0. "drawFrame") disp:drawFrame(5. 30. 30. 25. 7) disp:drawStr(0. 10+30. "drawRFrame/Box") disp:drawRFrame(5.3 Writing a Program For testing. 10) disp:drawBox(10+a. With activating OLED with I2C interface. 18+30. a+1) disp:drawRBox(50. 15. 7) disp:drawStr(0. 9) disp:drawCircle(24+a. 20. 16. we use a sample program from https://github.com/nodemcu/nodemcu- firmware/blob/master/lua_examples/u8glib/u8g_graphics_test. 10) disp:drawFrame(10+a.9. 9) disp:drawDisc(24+a. " 0") disp:drawStr90(30. called oleddemo.font_6x10) disp:setFontRefHeightExtendedText() disp:setDefaultForegroundColor() disp:setFontPosTop() end function box_frame(a) disp:drawStr(0. "drawCircle") disp:drawCircle(10. 30. 10. 31+a.ssd1306_128x64_i2c(sla) end -- graphic test components function prepare() disp:setFont(u8g. sda. i2c. Create a file. scl.

6+a. 55) end function triangle(a) local offset = a disp:drawStr(0.band(draw_state. 45+offset*2. 60. string. 7)) elseif (component == 3) then . 1 do for x = 0. "ASCII page 1") for y = 0. 0. 40. "setScale2x2") disp:setScale2x2() disp:drawStr(0.band(draw_state. 10. 3) prepare() if (component == 0) then box_frame(bit. 0. 1 do s = y*16 + x + 32 disp:drawStr(x*7. 57+offset. s disp:drawStr(0. 10.30+offset. "setScale2x2") disp:undoScale() end -- the draw() routine function draw(draw_state) local component = bit. 0. 12. 55) disp:drawLine(7+a*2. "drawLine") disp:drawLine(7+a. 45+offset.40) disp:drawTriangle(14+offset. end function ascii_1() local x.rshift(draw_state. 86+offset*2. 55) disp:drawLine(7+a*3. 80. y*10+10. 55) disp:drawLine(7+a*4. 100. 7)) elseif (component == 2) then r_frame(bit. "drawTriangle") disp:drawTriangle(14.30-offset. 10.band(draw_state.40+offset. " 270") end function line(a) disp:drawStr(0. disp:drawStr180(30-a. 45. " 180") disp:drawStr270(30. 7)) elseif (component == 1) then disc_circle(bit. 31-a.10. disp:drawTriangle(57+offset*2. y. 10. 15.30. 5.53) disp:drawTriangle(10+offset. 31. 10. 86+offset. 45+offset.30.7-offset.7.char(s)) end end end function extra_page(a) disp:drawStr(0.

7)) elseif (component == 6) then ascii_1() elseif (component == 7) then extra_page(bit. 7)) elseif (component == 4) then line(bit. .wdclr() end print("--- Graphics Test done ---") end init_i2c_display() graphics_test(50000) Save this code.heap()) tmr. stringtest(bit.band(draw_state. 7)) end end function graphics_test(delay) print("--- Starting Graphics Test ---") -- cycle through all components local draw_state for draw_state = 0.band(draw_state. 1 do disp:firstPage() repeat draw(draw_state) until disp:nextPage() == false --print(node.delay(delay) -- re-trigger Watchdog! tmr.band(draw_state.band(draw_state. 7 + 8*8. 7)) elseif (component == 5) then triangle(bit.

symbols and graphics. You should see OLED displays some characters. .4 Testing Now you can compile and run this program into NodeMCU board.9.

. 10. Connecting to a Network In this chapter I’m going to explain how to connect a network from NodeMCU.

"password") print("connecting…") wifi.ip) Change SSID and password values.sta.sta.1 Connecting to a WiFi Hotspot We can wifi object to work with WiFi module on NodeMCU. run it via Serial program so you can see NodeMCU’s IP Address. we connect a SSID with a pin password.STATION) wifi.10.setmode(wifi.getip() print("IP: ". Then. -- connect a WIFI network wifi. For instance.config("SSID". . Upload this program. Save this code into a file called network. Write this code.sta.lua.connect() ip = wifi.

10.2 Building a Simple Web Server
The second demo is to build a simple web server. Write this code.
wifi.setmode(wifi.STATION)
wifi.sta.config("SSID","password")
print("connecting…")
wifi.sta.connect()
ip = wifi.sta.getip()
print("IP: ",ip)

srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
conn:on("receive",function(conn,payload)
print(payload)
conn:send("HTTP/1.1 200/OK\r\nServer: NodeMCU\r\nContent-Type: text/html
conn:send("<html><head><title>NodeMCU</title></head><body><p>Hello, NodeMc
end)
conn:on("sent",function(conn) conn:close() end)
end)

Change SSID and password values. Save this code into a file called webserver.lua.
Upload this program. Then, run it via Serial program so you can see NodeMCU’s IP
Address.
Open a browser and navigate to IP address of NodeMCU.

The following is the program output on Serial app.

Source Code

You can download source code on
http://www.aguskurniawan.net/book/nodemcu_11301082015.zip .

net . My blog: http://blog. Contact If you have question related to this book.com . please contact me at aguskur@hotmail.aguskurniawan.