Skip to content
Marcel Stör edited this page Jan 10, 2016 · 154 revisions

NodeMCU API Instruction

###version 1.4.0 2015-12-12

##INDEX

###node module

###file module

###wifi module

###wifi.sta sub-module

###wifi.ap sub-module

###wifi.ap.dhcp sub-module

###timer module

###gpio module

###pwm module

###net module

###net.server sub-module

###net.socket sub-module

###net.dns sub-module

###i2c module

###adc module

###uart module

###1-wire module

###bit module

###spi module

###mqtt module

###mqtt.client sub-module

###WS2801 module

###WS2812 module

###cjson module

###crypto module

###u8g module ####I2C Display Drivers

####SPI Display Drivers

###u8g.disp sub-module

###dht module

###enduser_setup

###Misc

-Back to Index

Summary

  • Easy to access wireless router
  • Based on Lua 5.1.4, Developers are supposed to have experience with Lua Program language.
  • Event-Drive programming modal.
  • Build-in file, timer, pwm, i2c, net, gpio, wifi, uart, adc module.
  • Serial Port BaudRate:9600
  • Re-mapped GPIO pin, use the index to program gpio, i2c, pwm.
  • GPIO Map Table:

##GPIO NEW TABLE ( Build 20141219 and later)

##new_gpio_map

IO index ESP8266 pin IO index ESP8266 pin
0 [*] GPIO16 7 GPIO13
1 GPIO5 8 GPIO15
2 GPIO4 9 GPIO3
3 GPIO0 10 GPIO1
4 GPIO2 11 GPIO9
5 GPIO14 12 GPIO10
6 GPIO12

** [*] D0(GPIO16) can only be used as gpio read/write. no interrupt supported. no pwm/i2c/ow supported. **

####Example

      gpiolookup = {[0]=3,[1]=10,[2]=4,[3]=9,[4]=2,[5]=1,[10]=12,[12]=6,[13]=7,[14]=5,[15]=8,[16]=0}

      pin = gpiolookup[2] -- map ESP8266 GPIO2 to NodeMCU pin 4

-Back to Index

##GPIO OLD TABLE (Before build 20141212)

##old_gpio_map

IO index ESP8266 pin IO index ESP8266 pin
0 GPIO12 6 GPIO9
1 GPIO13 7 GPIO10
2 GPIO14 8 GPIO0
3 GPIO15 9 GPIO2
4 GPIO3 10 GPIO4
5 GPIO1 11 GPIO5

-Back to Index

#Burn/Flash Firmware ###Address

nodemcu_512k.bin: 0x00000
See NodeMCU flash tool:
nodemcu-flasher

#node module

node.restart()

####Description restart the chip.

####Syntax node.restart()

####Parameters

  • nil

####Returns

  • nil

####Example

    node.restart();

####See also

node.dsleep()

####Description Enter deep sleep mode, wake up when timed out.

####Syntax node.dsleep(us, option)

Note: This function can only be used in the condition that esp8266 PIN32(RST) and PIN8(XPD_DCDC aka GPIO16) are connected together. Using sleep(0) will set no wake up timer, connect a GPIO to pin RST, the chip will wake up by a falling-edge on pin RST.
option=0, init data byte 108 is valuable;
option>0, init data byte 108 is valueless.
More details as follows:
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 belarge 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.

####Parameters

  • us: number(Integer) or nil, sleep time in micro second. If us = 0, it will sleep forever. If us = nil, will not set sleep time.

  • option: number(Integer) or nil. If option = nil, it will use last alive setting as default option.

####Returns

  • nil

####Example

    --do nothing
    node.dsleep()
    --sleep μs
    node.dsleep(1000000)
    --set sleep option, then sleep μs
    node.dsleep(1000000, 4)
    --set sleep option only
    node.dsleep(nil,4)

####See also - Back to Index

node.info()

####Description return NodeMCU version, chipid, flashid, flash size, flash mode, flash speed.

####Syntax node.info()

####Parameters

  • nil

####Returns

  • majorVer (number)
  • minorVer (number)
  • devVer (number)
  • chipid (number)
  • flashid (number)
  • flashsize (number)
  • flashmode (number)
  • flashspeed (number)

####Example

    majorVer, minorVer, devVer, chipid, flashid, flashsize, flashmode, flashspeed = node.info();
    print("NodeMCU "..majorVer.."."..minorVer.."."..devVer)

####See also - Back to Index

node.chipid()

####Description return chip ID

####Syntax node.chipid()

####Parameters nil

####Returns number:chip ID

####Example

    id = node.chipid();

####See also - Back to Index

node.flashid()

####Description return flashid ID

####Syntax node.flashid()

####Parameters nil

####Returns number:flash ID

####Example

    flashid = node.flashid();

####See also - Back to Index

node.heap()

####Description return the remain HEAP size in bytes

####Syntax node.heap()

####Parameters nil

####Returns number: system heap size left in bytes

####Example

    heap_size = node.heap();

####See also - Back to Index

node.key()

####Description define button function, button is connected to GPIO16.

####Syntax node.key(type, function())

####Parameters type: type is either string "long" or "short". long: press the key for 3 seconds, short: press shortly(less than 3 seconds)
function(): user defined function which is called when key is pressed. If nil, cancling the user defined function.
Default function: long: change LED blinking rate, short: reset chip

####Returns nil

####Example

    node.key("long", function() print('hello world') end)

####See also - node.led

- Back to Index

node.led()

####Description setup the on/off time for led, which connected to GPIO16, multiplexing with node.key()

####Syntax node.led(low, high)

####Parameters Low: LED off time, LED keeps on when low=0. Unit: milliseconds, time resolution: 80100ms
High: LED on time. Unit: milliseconds, time resolution: 80
100ms

####Returns nil

####Example

    -- turn led on forever.
    node.led(0);

####See also - node.key

- Back to Index

node.input()

####Description accept a string and put the string into Lua interpretor.
same as pcall(loadstring(str)) but support multi seperated line.

####Syntax node.input(str)

####Parameters str: Lua chunk

####Returns nil

####Example

    -- never use node.input() in console. no effect.
    sk:on("receive", function(conn, payload) node.input(payload) end)

####See also -

- Back to Index

node.output()

####Description direct output from lua interpretor to a call back function.

####Syntax node.output(function(str), serial_debug)

####Parameters function(str): a function accept every output as str, and can send the output to a socket.
serial_debug: 1 output also show in serial. 0: no serial output.

####Returns nil

####Example

    function tonet(str)
      sk:send(str)
      -- print(str) WRONG!!! never ever print something in this function
      -- because this will cause a recursive function call!!!
    end
    node.ouput(tonet, 1)  -- serial also get the lua output.
    -- a simple telnet server
    s=net.createServer(net.TCP) 
    s:listen(2323,function(c) 
       con_std = c 
       function s_output(str) 
          if(con_std~=nil) 
             then con_std:send(str) 
          end 
       end 
       node.output(s_output, 0)   -- re-direct output to function s_ouput.
       c:on("receive",function(c,l) 
          node.input(l)           -- works like pcall(loadstring(l)) but support multiple separate line
       end) 
       c:on("disconnection",function(c) 
          con_std = nil 
          node.output(nil)        -- un-regist the redirect output function, output goes to serial
       end) 
    end)

####See also -

- Back to Index

node.readvdd33()

####Description Reading vdd33 pin voltage

####Syntax node.readvdd33()

####Parameters no parameters ####Returns mV

####Example

    print(node.readvdd33())

output

3345

    v = node.readvdd33() / 1000
    print(v)
    v=nil

output

3.315

####See also -

- Back to Index

node.compile()

####Description compile lua text file into lua bytecode file, and save it as .lc file.

####Syntax node.compile("file.lua")

####Parameters lua text file end with ".lua" ####Returns nil

####Example

  file.open("hello.lua","w+")
  file.writeline([[print("hello nodemcu")]])
  file.writeline([[print(node.heap())]])
  file.close()

  node.compile("hello.lua")
  dofile("hello.lua")
  dofile("hello.lc")

####See also -

- Back to Index

node.setcpufreq()

####Description Change the working CPU Frequency

####Syntax node.setcpufreq(speed)

####Parameters speed: node.CPU80MHZ or node.CPU160MHZ

####Returns return targe CPU Frequency

####Example

    node.setcpufreq(node.CPU80MHZ)

####See also

-

- Back to Index

node.restore()

####Description Restore all configuration of Wi-Fi system.

####Syntax node.restore()

####Parameters none

####Returns none

####Example

    node.restore()

####See also

-

- Back to Index

#file module

file.remove()

####Description remove file from file system.

####Syntax file.remove(filename)

####Parameters filename: file to remove

####Returns nil

####Example

    -- remove "foo.lua" from file system.
    file.remove("foo.lua")

####See also - file.open()
- file.close()

- Back to Index

file.open()

####Description open file.

####Syntax file.open(filename, mode)

####Parameters filename: file to be opened, directories are not supported
mode:

  • "r": read mode (the default)
  • "w": write mode
  • "a": append mode
  • "r+": update mode, all previous data is 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

####Returns nil: file not opened, or not exists. true: file opened ok.

####Example

    -- open 'init.lua', print the first line.
    file.open("init.lua", "r")
    print(file.readline())
    file.close()

####See also - file.close()
- file.readline()

- Back to Index

file.close()

####Description close the file.

####Syntax file.close()

####Parameters nil

####Returns nil

####Example

    -- open 'init.lua', print the first line.
    file.open("init.lua", "r")
    print(file.readline())
    file.close()

####See also - file.open()
- file.readline()

- Back to Index

file.readline()

####Description read one line of file which is opened before.

####Syntax file.readline()

####Parameters nil

####Returns file content in string, line by line, include EOL('\n')
return nil when EOF.

####Example

    -- print the first line of 'init.lua'
    file.open("init.lua", "r")
    print(file.readline())
    file.close()

####See also - file.open()
- file.close()

- Back to Index

file.writeline()

####Description write string to file and add a '\n' at the end.

####Syntax file.writeline(string)

####Parameters string: content to be write to file

####Returns true: write ok. nil: there is error

####Example

    -- open 'init.lua' in 'a+' mode
    file.open("init.lua", "a+")
    -- write 'foo bar' to the end of the file
    file.writeline('foo bar')
    file.close()

####See also - file.open()
- file.write()

- Back to Index

file.read()

####Description read content of file which is opened before.

####Syntax file.read()

####Parameters if nothing passed in, read all byte in file. if pass a number n, then read n byte from file, or EOF is reached. if pass a string "q", then read until 'q' or EOF is reached.

####Returns file content in string
return nil when EOF.

####Example

    -- print the first line of 'init.lua'
    file.open("init.lua", "r")
    print(file.read('\r'))
    file.close()

    -- print the first 5 byte of 'init.lua'
    file.open("init.lua", "r")
    print(file.read(5))
    file.close()

####See also - file.open()
- file.close()

- Back to Index

file.write()

####Description write string to file.

####Syntax file.write(string)

####Parameters string: content to be write to file.

####Returns true: write ok. nil: there is error

####Example

    -- open 'init.lua' in 'a+' mode
    file.open("init.lua", "a+")
    -- write 'foo bar' to the end of the file
    file.write('foo bar')
    file.close()

####See also - file.open()
- file.writeline()

- Back to Index

file.flush()

####Description flush to file.

####Syntax file.flush()

####Parameters nil

####Returns nil

####Example

    -- open 'init.lua' in 'a+' mode
    file.open("init.lua", "a+")
    -- write 'foo bar' to the end of the file
    file.write('foo bar')
    file.flush()
    file.close()

####See also - file.open()
- file.writeline()

- Back to Index

file.seek()

####Description Sets and gets the file position, measured from the beginning of the file, to the position given by offset plus a base specified by the string whence.

####Syntax file.seek(whence, offset)

####Parameters whence:
"set": base is position 0 (beginning of the file);
"cur": base is current position;(default value)
"end": base is end of file;
offset: default 0

####Returns success: returns the final file position
fail: returns nil

####Example

    -- open 'init.lua' in 'a+' mode
    file.open("init.lua", "a+")
    -- write 'foo bar' to the end of the file
    file.write('foo bar')
    file.flush()
    file.seek("set")
    print(file.readline())
    file.close()

####See also - file.open()
- file.writeline()

- Back to Index

file.list()

####Description list all files.

####Syntax file.list()

####Parameters nil

####Returns a lua table which contains the {file name: file size} pairs

####Example

    l = file.list();
    for k,v in pairs(l) do
      print("name:"..k..", size:"..v)
    end

####See also - file.remove()

- Back to Index

file.format()

####Description format file system.

####Syntax file.format()

####Parameters nil

####Returns nil

####Example

    file.format()

####See also - file.remove()

- Back to Index

file.rename()

####Description rename a file. NOTE: the current opened file will be closed.

####Syntax file.rename(oldname, newname)

####Parameters oldname: old file name, directories are not supported
newname: new file name, directories are not supported

####Returns false: rename failed. true: rename ok.

####Example

    -- rename file 'temp.lua' to 'init.lua'.
    file.rename("temp.lua","init.lua")

####See also - file.close()

- Back to Index

file.fsinfo()

####Description Get file system info

####Syntax

  • file.fsinfo()

####Parameters

  • nil

####Returns

  • remaining (number)
  • used (number)
  • total (number)

####Example

    -- get file system info
    remaining, used, total=file.fsinfo()
    print("\nFile system info:\nTotal : "..total.." Bytes\nUsed : "..used.." Bytes\nRemain: "..remaining.." Bytes\n")

####See also

- Back to Index

#wifi module ##CONSTANT wifi.STATION, wifi.SOFTAP, wifi.STATIONAP

wifi.setmode()

####Description setup wifi operation mode.

  • wifi.STATION is when the device is connected to another wifi router. This is often done to give the device access to the internet.
  • wifi.SOFTAP is when the device is acting as ONLY an access point. This mode will allow you to see the device in the list of wifi networks. In this mode your computer can connect to the device creating a local area network. Unless you change the value, the ESP8266 device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP, such as: 192.168.4.2.
  • wifi.STATIONAP is a combination of wifi.STATION and wifi.SOFTAP. It allows you to create a local wifi connection AND connect to another wifi router.

####Syntax wifi.setmode(mode)

####Parameters mode: value should be:

  • wifi.STATION
  • wifi.SOFTAP
  • wifi.STATIONAP

####Returns current mode after setup

####Example

    wifi.setmode(wifi.STATION)

####See also - wifi.getmode()

- Back to Index

wifi.getmode()

####Description get wifi operation mode.

####Syntax wifi.getmode()

####Parameters nil

####Returns wifi operation mode

1 = STATION
2 = SOFTAP
3 = STATIONAP

####Example

    print(wifi.getmode())

####See also - wifi.setmode()

- Back to Index

wifi.getchannel()

####Description get current wifi channel.

####Syntax wifi.getchannel()

####Parameters nil

####Returns current wifi channel

####Example

    print(wifi.getchannel())

####See also

- Back to Index

wifi.setphymode()

####Description Setup wifi physical mode.

  • wifi.PHYMODE_B 802.11b, More range, Low Transfer rate, More current draw
  • wifi.PHYMODE_G 802.11g, Medium range, Medium transfer rate, Medium current draw
  • 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
Tx 802.11b, CCK 11Mbps, P OUT=+17dBm 170 mA
Tx 802.11g, OFDM 54Mbps, P OUT =+15dBm 140 mA
Tx 802.11n, MCS7 65Mbps, P OUT =+13dBm 120 mA
Rx 802.11b, 1024 bytes packet length, -80dBm 50 mA
Rx 802.11g, 1024 bytes packet length, -70dBm 56 mA
Rx 802.11n, 1024 bytes packet length, -65dBm 56 mA

####Syntax wifi.setphymode(mode)

####Parameters mode: value should be:

  • wifi.PHYMODE_B
  • wifi.PHYMODE_G
  • wifi.PHYMODE_N

####Returns Current physical mode after setup

####Example

   --STATION 
   wifi.setphymode()

####See also - wifi.getphymode()

- Back to Index

wifi.getphymode()

####Description get wifi physical mode.

####Syntax wifi.getmode()

####Parameters nil

####Returns wifi physical mode

  • 1: wifi.PHYMODE_B
  • 2: wifi.PHYMODE_G
  • 3: wifi.PHYMODE_N

####Example

    print(wifi.getphymode())

####See also - wifi.setphymode()

- Back to Index

wifi.startsmart()

####Description starts to auto configuration, if success set up ssid and pwd automatically.
in new method, must using under wifi.STATION mode.

####Syntax [old] wifi.startsmart(channel, function succeed_callback())
[new] wifi.startsmart(type, function succeed_callback(ssid, password))

####Parameters

[old]
channel: 113, startup channel for searching, if nil, default to 6. 20 seconds for each channel.
succeed_callback: callback function called after configuration, which is called when got password and connected to AP.
[new]
type: 0
1. 0 means use ESP_TOUCH, 1 means use AIR_KISS. The APP (Android and iOS) can download with full source code from https://github.com/espressifapp. Note: dev096 branch only suppurt ESP Touch V021, please check out old version.
succeed_callback: with 2 arguments, ssid and password, called after configuration.

####Returns nil

####Example

    -- old
    wifi.startsmart(6, function() end)
    -- new
    wifi.setmode(wifi.STATION)
    wifi.startsmart(0, 
        function(ssid, password) 
            print(string.format("Success. SSID:%s ; PASSWORD:%s", ssid, password))
        end
    )
    -- above sdk v120, can get phone ip, must use esptouch v034.
    wifi.startsmart(0,function(ssid, password,phoneip) print(ssid) print(password) print(phoneip) end)

####See also - wifi.stopsmart()

- Back to Index

wifi.stopsmart()

####Description stop the configuring process.

####Syntax wifi.stopsmart()

####Parameters nil

####Returns nil

####Example

    wifi.stopsmart()

####See also - wifi.startsmart()

- Back to Index

wifi.sleeptype()

####Description config the sleep type for wifi modem.

####Syntax type_actual = wifi.sleeptype(type_need)

####Parameters type_need:
wifi.NONE_SLEEP, wifi.LIGHT_SLEEP, wifi.MODEM_SLEEP

####Returns type_actual:
wifi.NONE_SLEEP, wifi.LIGHT_SLEEP, wifi.MODEM_SLEEP

####Example

    realtype = wifi.sleeptype(wifi.MODEM_SLEEP)

####See also - node.dsleep()

- Back to Index

wifi.sta.getconfig()

####Description Get wifi station configuration.
Note: If bssid_set is equal to 0 then bssid is irrelevant

####Syntax ssid, password, bssid_set, bssid=wifi.sta.getconfig()

####Parameters nil

####Returns ssid, password, bssid_set, bssid

####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

####See also - wifi.sta.connect()
- wifi.sta.disconnect()

- Back to Index

wifi.sta.config()

####Description Set wifi station configuration

####Syntax wifi.sta.config(ssid, password)
wifi.sta.config(ssid, password, auto)
wifi.sta.config(ssid, password, bssid)
wifi.sta.config(ssid, password, auto, bssid)

####Parameters

  • ssid: string which is less than 32 bytes.
  • password: string which is 8-64 or 0 bytes. Empty string indicates an open Wifi Access Point.
  • auto: value of 0 or 1 (Default is 1)
    • 0: Disable auto connect and remain disconnected from Access Point
    • 1: Enable auto connect and connect to Access Point.
  • bssid: String that contains the MAC address of the Access Point, (optional).
    • 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"

####Returns nil

####Example

   --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()

####See also - wifi.sta.connect()
- wifi.sta.disconnect()

- Back to Index

wifi.sta.connect()

####Description connect to AP in station mode.

####Syntax wifi.sta.connect()

####Parameters nil

####Returns nil

####Example

    wifi.sta.connect()

####See also - wifi.sta.disconnect()
- wifi.sta.config()

- Back to Index

wifi.sta.disconnect()

####Description disconnect from AP in station mode.

####Syntax wifi.sta.disconnect()

####Parameters nil

####Returns nil

####Example

    wifi.sta.disconnect()

####See also - wifi.sta.config()
- wifi.sta.connect()

- Back to Index

wifi.sta.autoconnect()

####Description auto connect to AP in station mode.

####Syntax wifi.sta.autoconnect(auto)

####Parameters auto: 0 to disable auto connecting. 1 to enable auto connecting

####Returns nil

####Example

    wifi.sta.autoconnect()

####See also - wifi.sta.config()
- wifi.sta.connect()
- wifi.sta.disconnect()

- Back to Index

wifi.sta.getip()

####Description get ip, netmask, gateway address in station mode.

####Syntax wifi.sta.getip()

####Parameters nil

####Returns ip, netmask, gateway address in string, for example:"192.168.0.111"
return nil if ip = "0.0.0.0".

####Example

    -- print current ip, 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

####See also - wifi.sta.getmac()

- Back to Index

wifi.sta.setip()

####Description set ip, netmask, gateway address in station mode.

####Syntax wifi.sta.setip(cfg)

####Parameters cfg: table contain ip, netmask, and gateway

{
  ip="192.168.0.111",
  netmask="255.255.255.0",
  gateway="192.168.0.1"
}

####Returns true if success, false if fail.

####Example

  cfg =
  {
    ip="192.168.0.111",
    netmask="255.255.255.0",
    gateway="192.168.0.1"
  }
  wifi.sta.setip(cfg)

####See also - wifi.sta.setmac()

- Back to Index

wifi.sta.getmac()

####Description get mac address in station mode.

####Syntax wifi.sta.getmac()

####Parameters nil

####Returns mac address in string, for example:"18-33-44-FE-55-BB"

####Example

    -- print current mac address
    print(wifi.sta.getmac())

####See also - wifi.sta.getip()

- Back to Index

wifi.sta.setmac()

####Description set mac address in station mode.

####Syntax wifi.sta.setmac(mac)

####Parameters mac address in string, for example:"DE:AD:BE:EF:7A:C0"

####Returns true if success, false if fail.

####Example

    print(wifi.sta.setmac("DE:AD:BE:EF:7A:C0"))

####See also - wifi.sta.setip()

- Back to Index

wifi.sta.getap()

####Description scan and get ap list as a lua table into callback function.

####Syntax wifi.sta.getap(function(table))
wifi.sta.getap(cfg, function(table))
wifi.sta.getap(format, function(table))
wifi.sta.getap(cfg, format, function(table))

####Parameters

  • cfg: table that contains scan configuration
    • ssid: ssid == nil, don't filter ssid.
    • bssid: bssid == nil, don't filter bssid.
    • channel: channel == 0, scan all channels, otherwise scan set channel.(Default is 0)
    • show_hidden: show_hidden == 1, get info for router with hidden ssid.(Default is 0)
  • format: Select output table format, 0 or 1 is valid.(0 is Default)
    • 0: Old format (SSID : Authmode, RSSI, BSSID, Channel)
      • NOTE: When using old format for table output, any duplicate SSIDs will be discarded.
    • 1: New format (BSSID : SSID, RSSI, Authmode, Channel)
  • function(table): a callback function to receive ap table when scan is done
    • This function receives a table, the key is the ssid, value is other info in format: authmode,rssi,bssid,channel
    • If you are using the new output format, the key is the bssid, value is other info in format: ssid,rssi,authmode,channel

####Returns nil

####Example

  -- print ap list
    function listap(t)
      for k,v in pairs(t) do
        print(k.." : "..v)
      end
    end
    wifi.sta.getap(listap)

  -- Print AP list that is easier to read
	function listap(t) -- (SSID : Authmode, RSSI, BSSID, Channel)
	 print("\n"..string.format("%32s","SSID").."\tBSSID\t\t\t\t  RSSI\t\tAUTHMODE\tCHANNEL")
	 for ssid,v in pairs(t) do
	  local authmode, rssi, bssid, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]+)")
	  print(string.format("%32s",ssid).."\t"..bssid.."\t  "..rssi.."\t\t"..authmode.."\t\t\t"..channel)
	 end
	end
	wifi.sta.getap(listap)

--NOTE: The rest of the examples use the new style output format

  -- print ap list
    function listap(t)
      for k,v in pairs(t) do
        print(k.." : "..v)
      end
    end
    wifi.sta.getap(1, listap)

  -- Print AP list that is easier to read
    function listap(t) -- (SSID : Authmode, RSSI, BSSID, Channel)
     print("\n\t\t\tSSID\t\t\t\t\tBSSID\t\t\t  RSSI\t\tAUTHMODE\t\tCHANNEL")
      for bssid,v in pairs(t) do
       local ssid, rssi, authmode, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]*)")
        print(string.format("%32.s",ssid).."\t"..bssid.."\t  "..rssi.."\t\t"..authmode.."\t\t\t"..channel)
      end
    end
    wifi.sta.getap(1, listap)

  --check for specific AP
    function listap(t)
     print("\n\t\t\tSSID\t\t\t\t\tBSSID\t\t\t  RSSI\t\tAUTHMODE\t\tCHANNEL")
      for bssid,v in pairs(t) do
       local ssid, rssi, authmode, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]*)")
        print(string.format("%32.s",ssid).."\t"..bssid.."\t  "..rssi.."\t\t"..authmode.."\t\t\t"..channel)
      end
    end
   scan_cfg={}
   scan_cfg.ssid="myssid" 
   scan_cfg.bssid="AA:AA:AA:AA:AA:AA" 
   scan_cfg.channel=0
   scan_cfg.show_hidden=1
   wifi.sta.getap(scan_cfg, 1, listap)

   --get RSSI for currently configured AP
   function listap(t)
     for bssid,v in pairs(t) do
      local ssid, rssi, authmode, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]*)")
       print("CURRENT RSSI IS: "..rssi)
     end
   end
  ssid, tmp, bssid_set, bssid=wifi.sta.getconfig() 
  scan_cfg={}
  scan_cfg.ssid=ssid 
  if bssid_set==1 then scan_cfg.bssid=bssid else scan_cfg.bssid=nil end
  scan_cfg.channel=wifi.getchannel()
  scan_cfg.show_hidden=0
  ssid, tmp, bssid_set, bssid=nil, nil, nil, nil
  wifi.sta.getap(scan_cfg, 1, listap)

####See also - wifi.sta.getip()

- Back to Index

wifi.sta.status()

####Description get current status in station mode.

####Syntax wifi.sta.status()

####Parameters nil

####Returns 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.

####See also - Back to Index

wifi.sta.getbroadcast()

####Description get getbroadcast address in station mode.

####Syntax wifi.sta.getbroadcast()

####Parameters nil

####Returns getbroadcast address in string, for example:"192.168.0.255"
return nil if ip = "0.0.0.0".

####Example

    bc = wifi.sta.getbroadcast()
    print(bc)
    -- 192.168.0.255

####See also - wifi.sta.getip()

- Back to Index

wifi.sta.eventMonReg()

Description

Register callback for wifi station status event

Syntax

wifi.sta.eventMonReg(wifi_status, function)
wifi.sta.eventMonReg(wifi_status, function(Previous_state))
wifi.sta.eventMonReg(wifi.status, "unreg")

Parameters

  • wifi_status: wifi status you would like to set callback for
    • Valid wifi states:
      • wifi.STA_IDLE
      • wifi.STA_CONNECTING
      • wifi.STA_WRONGPWD
      • wifi.STA_APNOTFOUND
      • wifi.STA_FAIL
      • wifi.STA_GOTIP
  • function: function to perform when event occurs
  • "unreg": unregister previously registered callback
  • Previous_state: previous wifi_state(0 - 5)

Returns

Nothing.

Example

  --register callback
  wifi.sta.eventMonReg(wifi.STA_IDLE, function() print("STATION_IDLE") end)
  wifi.sta.eventMonReg(wifi.STA_CONNECTING, function() print("STATION_CONNECTING") end)
  wifi.sta.eventMonReg(wifi.STA_WRONGPWD, function() print("STATION_WRONG_PASSWORD") end)
  wifi.sta.eventMonReg(wifi.STA_APNOTFOUND, function() print("STATION_NO_AP_FOUND") end)
  wifi.sta.eventMonReg(wifi.STA_FAIL, function() print("STATION_CONNECT_FAIL") end)
  wifi.sta.eventMonReg(wifi.STA_GOTIP, function() print("STATION_GOT_IP") end)
  
  --register callback: use previous state
  wifi.sta.eventMonReg(wifi.STA_CONNECTING, function(Previous_State)
    if(Previous_State==wifi.STA_GOTIP) then 
      print("Station lost connection with Access Point\n\tAttempting to reconnect...")
    else
      print("STATION_CONNECTING")
    end
  end)
  
  --unregister callback
  wifi.sta.eventMonReg(wifi.STA_IDLE, "unreg")

####See also - wifi.sta.eventMonStart()

- wifi.sta.eventMonStop()

- Back to Index

wifi.sta.eventMonStart()

Description

Start wifi station event monitor

Syntax

wifi.sta.eventMonStart()
wifi.sta.eventMonStart(ms)

Parameters

  • ms: interval between checks in milliseconds. defaults to 150 ms if not provided.

Returns

Nothing.

Example

  --start wifi event monitor with default interval
  wifi.sta.eventMonStart()

  --start wifi event monitor with 100 ms interval
  wifi.sta.eventMonStart(100)

####See also - wifi.sta.eventMonReg()

- wifi.sta.eventMonStop()

- Back to Index

wifi.sta.eventMonStop()

Description

Stop wifi station event monitor

Syntax

wifi.sta.eventMonStop()
wifi.sta.eventMonStop("unreg all")

Parameters

  • "unreg all": unregister all previously registered functions

Returns

Nothing.

Example

  --stop wifi event monitor
  wifi.sta.eventMonStop()

  --stop wifi event monitor and unregister all callbacks
  wifi.sta.eventMonStop("unreg all")

####See also - wifi.sta.eventMonReg()

- wifi.sta.eventMonStart()

- Back to Index

#wifi.ap module

wifi.ap.config()

####Description set ssid and pwd in ap mode. Be sure to make the pwd value at least 8 characters! If you don't make the pwd value 8 characters, it will default to no password and not set the value for ssid. It will still work as an access point, but you will see a name in your wifi list like: ESP_9997C3

####Syntax wifi.ap.config(cfg)

####Parameters

  • string: SSID chars 1-32
  • string: pwd chars 8-64
  • int: auth Authentication AUTH_OPEN | AUTH_WPA_PSK | AUTH_WPA2_PSK | AUTH_WPA_WPA2_PSK default=Open
  • int: channel no. 1-14 default=6
  • int: hidden 0=not hidden 1=hidden default=0
  • int: max maximal connections 1-4 default=4
  • int beacon interval time of beacons value 100-60000 default=100

####Example:

     cfg={}
     cfg.ssid="myssid"
     cfg.pwd="mypassword"
     wifi.ap.config(cfg)

####Returns nil

####See also -

- Back to Index

wifi.ap.getip()

####Description get ip, netmask, gateway in ap mode.

####Syntax wifi.ap.getip()

####Parameters nil

####Returns ip, netmask, gateway address in string, for example:"192.168.0.111"
return nil if ip = "0.0.0.0".

####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

####See also - wifi.ap.getmac()

- Back to Index

wifi.ap.setip()

####Description set ip, netmask, gateway address in ap mode.

####Syntax wifi.ap.setip(cfg)

####Parameters cfg: table contain ip, netmask, and gateway

{
  ip="192.168.1.1",
  netmask="255.255.255.0",
  gateway="192.168.1.1"
}

####Returns true if success, false if fail.

####Example

  cfg =
  {
    ip="192.168.1.1",
    netmask="255.255.255.0",
    gateway="192.168.1.1"
  }
  wifi.ap.setip(cfg)

####See also - wifi.ap.setmac()

- Back to Index

wifi.ap.getmac()

####Description get mac address in ap mode.

####Syntax wifi.ap.getmac()

####Parameters nil

####Returns mac address in string, for example:"1A-33-44-FE-55-BB"

####Example

    wifi.ap.getmac()

####See also - wifi.ap.getip()

- Back to Index

wifi.ap.setmac()

####Description set mac address in ap mode.

####Syntax wifi.ap.setmac(mac)

####Parameters mac address in byte string, for example:"AC-1D-1C-B1-0B-22"

####Returns true if success, false if fail.

####Example

    print(wifi.ap.setmac("AC-1D-1C-B1-0B-22"))

####See also - wifi.ap.setip()

- Back to Index

wifi.ap.getclient()

####Description get table of clients connected to ESP in ap mode.

####Syntax table=wifi.ap.getclient()

####Parameters nil

####Returns table of connected clients

####Example

    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

- Back to Index

wifi.ap.getbroadcast()

####Description get getbroadcast address in ap mode.

####Syntax wifi.ap.getbroadcast()

####Parameters nil

####Returns getbroadcast address in string, for example:"192.168.0.255"
return nil if ip = "0.0.0.0".

####Example

    bc = wifi.ap.getbroadcast()
    print(bc)
    -- 192.168.0.255

####See also - wifi.ap.getip()

- Back to Index

wifi.ap.dhcp submodule

wifi.ap.dhcp.config()

####Description Configure the dhcp service. Currently only supports setting the start address of the dhcp address pool. ####Syntax wifi.ap.dhcp.config(dhcp_config) ####Parameters dhcp_config: Table containing the start-IP of the dhcp address pool, eg. "192.168.1.100" ####Returns pool_startip, pool_endip ####Example

dhcp_config ={}
dhcp_config.start = "192.168.1.100"
wifi.ap.dhcp.config(dhcp_config)

wifi.ap.dhcp.start()

####Description Start the dhcp service ####Syntax wifi.ap.dhcp.start() ####Returns boolean indicating success

wifi.ap.dhcp.stop()

####Description Stop the dhcp service ####Syntax wifi.ap.dhcp.stop() ####Returns boolean indicating success

- Back to Index

#timer module

tmr.delay()

####Description delay us micro seconds.

####Syntax tmr.delay(us)

####Parameters us: delay time in micro second

####Returns nil

####Example

    -- delay 100us
    tmr.delay(100)

####See also - tmr.now()

- Back to Index

tmr.now()

####Description return the current value of system counter: uint31, us.

####Syntax tmr.now()

####Parameters nil

####Returns uint31: value of counter

####Example

    -- print current value of counter
    print(tmr.now())

####See also - tmr.delay()

- Back to Index

tmr.alarm()

####Description alarm time.

####Syntax tmr.alarm(id, interval, repeat, function do())

####Parameters id: 0~6, alarmer id.
interval: alarm time, unit: millisecond.
repeat: 0 - one time alarm, 1 - repeat.
function do(): callback function for alarm timed out

####Returns nil

####Example

    -- print "hello world" every 1000ms
    tmr.alarm(0, 1000, 1, function() print("hello world") end )

####See also - tmr.now()

- Back to Index

tmr.stop()

####Description

stop alarm.

####Syntax tmr.stop(id)

####Parameters id: 0~6, alarmer id.

####Returns nil

####Example

    -- print "hello world" every 1000ms
    tmr.alarm(1, 1000, 1, function() print("hello world") end )

    -- something else

    -- stop alarm
    tmr.stop(1)

####See also - tmr.now()

- Back to Index

tmr.wdclr()

####Description clear system watchdog counter.

####Syntax tmr.wdclr()

####Parameters nil.

####Returns nil

####Example

    for i=1,10000 do 
      print(i)
      tmr.wdclr()   -- should call tmr.wdclr() in a long loop to avoid hardware reset caused by watchdog.
    end 

####See also - tmr.delay()

- Back to Index

tmr.time()

####Description return rtc time since start up in second, uint31 form.

####Syntax tmr.time()

####Parameters nil.

####Returns number

####Example

####See also - tmr.now()

- Back to Index

#GPIO module ##CONSTANT gpio.OUTPUT, gpio.INPUT, gpio.INT, gpio.HIGH, gpio.LOW

gpio.mode()

####Description initialize pin to GPIO mode, set the pin in/out mode, internal pullup.

####Syntax gpio.mode(pin, mode, pullup)

####Parameters pin: 0~12, IO index
mode: gpio.OUTPUT or gpio.INPUT, or gpio.INT(interrupt mode) pullup: gpio.PULLUP or gpio.FLOAT, default: gpio.FLOAT.

####Returns nil

####Example

    -- set gpio 0 as output.
    gpio.mode(0, gpio.OUTPUT)

####See also - gpio.read()

- Back to Index

gpio.read()

####Description read pin value.

####Syntax gpio.read(pin)

####Parameters pin: 0~12, IO index

####Returns number:0 - low, 1 - high

####Example

    -- read value of gpio 0.
    gpio.read(0)

####See also - gpio.mode()

- Back to Index

gpio.write()

####Description set pin value.

####Syntax gpio.write(pin)

####Parameters pin: 0~12, IO index
level: gpio.HIGH or gpio.LOW

####Returns nil

####Example

    -- set pin index 1 to GPIO mode, and set the pin to high.
    pin=1
    gpio.mode(pin, gpio.OUTPUT)
    gpio.write(pin, gpio.HIGH)

####See also - gpio.mode()
- gpio.read()

- Back to Index

gpio.trig()

####Description set the interrupt callback function for pin.

####Syntax gpio.trig(pin, type, function(level))

####Parameters pin: 1~12, IO index, pin D0 does not support Interrupt.
type: "up", "down", "both", "low", "high", which represent rising edge, falling edge, both edge, low level, high level trig mode separately.
function(level): callback function when triggered. The level parameter is the GPIO pin reading soon after the interrupt is triggered. Use previous callback function if undefined here.

####Returns nil

####Example

    -- use pin 0 as the input pulse width counter
    pulse1 = 0
    du = 0
    gpio.mode(1,gpio.INT)
    function pin1cb(level)
     du = tmr.now() – pulse1
     print(du)
     pulse1 = tmr.now()
     if level == 1 then gpio.trig(1, "down") else gpio.trig(1, "up") end
    end
    gpio.trig(1, "down",pin1cb)

####See also - gpio.mode()
- gpio.write()

- Back to Index

#PWM module

pwm.setup()

####Description Set pin to PWM mode. Only 6 pins can be set to PWM mode at the most.

####Syntax pwm.setup(pin, clock, duty)

####Parameters pin: 112, IO index
clock: 1
1000, pwm frequency
duty: 0~1023, pwm duty cycle, max 1023(10bit)

####Returns nil

####Example

    -- set pin index 1 as pwm output, frequency is 100Hz, duty cycle is half.
    pwm.setup(1, 100, 512)

####See also - pwm.start()

- Back to Index

pwm.close()

####Description quit PWM mode for specified pin.

####Syntax pwm.close(pin)

####Parameters pin: 1~12, IO index

####Returns nil

####Example

    pwm.close(1)

####See also - pwm.start()

- Back to Index

pwm.start()

####Description pwm starts, you can detect the waveform on the gpio.

####Syntax pwm.start(pin)

####Parameters pin: 1~12, IO index

####Returns nil

####Example

    pwm.start(1)

####See also - pwm.stop()

- Back to Index

pwm.stop()

####Description pause the output of PWM waveform.

####Syntax pwm.stop(pin)

####Parameters pin: 1~12, IO index

####Returns nil

####Example

    pwm.stop(1)

####See also - pwm.start()

- Back to Index

pwm.setclock()

####Description

set pwm frequency for pin.
-Note: setup pwm frequency will synchronously change others if there are any. Only one PWM frequency can be allowed for the system.

####Syntax pwm.setclock(pin, clock)

####Parameters pin: 112, IO index.
clock: 1
1000, pwm frequency.

####Returns nil

####Example

    pwm.setclock(1, 100)

####See also - pwm.getclock()

- Back to Index

pwm.getclock()

####Description get pwm frequency of pin.

####Syntax pwm.getclock(pin)

####Parameters pin: 1~12, IO index.

####Returns number:pwm frequency of pin

####Example

    print(pwm.getclock(1))

####See also - pwm.setclock()

- Back to Index

pwm.setduty()

####Description set duty clycle for pin.

####Syntax pwm.setduty(pin, duty)

####Parameters pin: 112, IO index
duty: 0
1023, pwm duty cycle, max 1023(10bit).

####Returns nil

####Example

    pwm.setduty(1, 512)

####See also - pwm.getduty()

- Back to Index

pwm.getduty()

####Description get duty clycle for pin.

####Syntax pwm.getduty(pin)

####Parameters pin: 1~12, IO index

####Returns number: duty cycle, max 1023.

####Example

    -- D1 is connected to green led
    -- D2 is connected to blue led
    -- D3 is connected to red led
    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.

####See also - pwm.setduty()

- Back to Index

#net module ##CONSTANT net.TCP, net.UDP

net.createServer()

####Description create a server.

####Syntax net.createServer(type, timeout)

####Parameters type: net.TCP or net.UDP
timeout: for a TCP server, timeout is 1~28800 seconds, for a inactive client to disconnected.

####Returns net.server sub module

####Example

    net.createServer(net.TCP, 30) -- 30s timeout

####See also - net.createConnection()

- Back to Index

net.createConnection()

####Description Create a client.

####Syntax net.createConnection(type, secure)

####Parameters type: net.TCP or net.UDP
secure: 1 or 0, 1 for ssl link, 0 for normal link

####Returns net.socket sub module

####Example

    net.createConnection(net.UDP, 0)

####See also - net.createServer()

- Back to Index

#net.server module

net.server:listen()

####Description listen on port from [ip] address.

####Syntax net.server.listen(port,[ip],function(net.socket))

####Parameters port: port number
ip:ip address string, can be omitted
function(net.socket): callback function, pass to Caller function as param if a connection is created successfully

####Returns nil

####Example

    -- create a server
    sv=net.createServer(net.TCP, 30)    -- 30s time out for a inactive client
    -- server listen on 80, if data received, print data to console, and send "hello world" to remote.
    sv:listen(80,function(c)
      c:on("receive", function(c, pl) print(pl) end)
      c:send("hello world")
      end)

####See also - net.createServer()

- Back to Index

net.server:close()

####Description close server.

####Syntax net.server.close()

####Parameters nil

####Returns nil

####Example

    -- create a server
    sv=net.createServer(net.TCP, 30)
    -- close server
    sv:close()

####See also - net.createServer()

- Back to Index

#net.socket module

net.socket:connect()

####Description connect to remote.

####Syntax connect(port, ip/domain)

####Parameters port: port number
ip: ip address or domain name in string

####Returns nil

####See also - net.socket:on() - Back to Index

net.socket:send()

####Description send data to remote via connection.

####Syntax send(string, function(sent))

####Parameters string: data in string which will be sent to remote
function(sent): callback function for sending string

####Returns nil

Note

Multiple consecutive send() calls aren't guaranteed to work (and often don't). Instead, subscribe to the "sent" event on the socket and send additional data (or close) in that callback. See #730 for an example and explanation.

####See also - net.socket:on()

- Back to Index

net.socket:on()

####Description register callback function for event.

####Syntax on(event, function cb())

####Parameters event: string, which can be: "connection", "reconnection", "disconnection", "receive", "sent"
function cb(net.socket, [string]): callback function. The first param is the socket.
If event is "receive", the second param is received data in string.

####Returns nil

####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)

####See also - net.createServer()

- Back to Index

net.socket:close()

####Description close socket.

####Syntax close()

####Parameters nil

####Returns nil

####See also - net.createServer()

- Back to Index

net.socket:dns()

####Description get domain ip

####Syntax dns(domain, function(net.socket, ip))

####Parameters domain: domain name.
function (net.socket, ip): callback function. The first param is the socket, the second param is the ip address in string.

####Returns nil

####Example

    sk=net.createConnection(net.TCP, 0)
    sk:dns("www.nodemcu.com",function(conn,ip) print(ip) end)
    sk = nil

####See also - net.createServer()

- Back to Index

net.dns module

net.dns.setdnsserver()

####Description 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) ####Parameters dns_ip_addr: The IP address to use as DNS server
dns_index: (range 0~1) Which DNS server to set. Supports max. 2 DNS servers. ####Returns nil ####Example See net.dns:getdnsserver() ####See also net.dns:getdnsserver()

net.dns.getdnsserver()

####Description Gets the IP address of the DNS server used to resolve domain names. ####Syntax net.dns.getdnsserver(dns_index) ####Parameters dns_index: (range 0~1) Which DNS server to set. Supports max. 2 DNS servers. ####Returns IP address of 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

####See also net.dns:setdnsserver()

net.dns.resolve()

####Description Resolve a hostname to an IP address. Doesn't require a socket like net.socket.dns(). ####Syntax net.dns.resolve( domain, function(ip) ) ####Parameters domain: Domain name to resolve
function(sk,ip): Callback called when the name was resolved. Don't use sk, it's a socket used internally to resolve the hostname. ####Returns nil ####Example

net.dns.resolve("www.google.com", function(sk, ip)
    if (ip == nil) then print("DNS fail!") else print(ip) end
end)

####See also net.socket:dns()

#i2c module ##CONSTANT i2c.SLOW, i2c.TRANSMITTER, i2c.RECEIVER. FAST(400k)is not supported for now.

i2c.setup()

####Description initialize i2c.

####Syntax i2c.setup(id, pinSDA, pinSCL, speed)

####Parameters id = 0
pinSDA: 112, IO index
pinSCL: 1
12, IO index
speed: i2c.SLOW

####Returns speed: the seted speed.

####See also - i2c.read()

- Back to Index

i2c.start()

####Description start i2c transporting.

####Syntax i2c.start(id)

####Parameters id = 0

####Returns nil

####See also - i2c.read()

- Back to Index

i2c.stop()

####Description stop i2c transporting.

####Syntax i2c.stop(id)

####Parameters id = 0

####Returns nil

####See also - i2c.read()

- Back to Index

i2c.address()

####Description setup i2c address and read/write mode.

####Syntax i2c.address(id, device_addr, direction)

####Parameters id=0
device_addr: device address.
direction: i2c.TRANSMITTER for writing mode , i2c. RECEIVER for reading mode

####Returns true: get ack false: no ack get

####See also - i2c.read()

- Back to Index

i2c.write()

####Description write data to i2c, data can be multi numbers, string or lua table.

####Syntax i2c.write(id, data1, data2,...)

####Parameters id=0
data: data can be numbers, string or lua table.

####Returns number: number of bytes wrote.

####Example

    i2c.write(0, "hello", "world")

####See also - i2c.read()

- Back to Index

i2c.read()

####Description read data for len bytes.

####Syntax i2c.read(id, len)

####Parameters id=0
len: data length

####Returns string:data received.

####Example

    id=0
    sda=1
    scl=2

    -- initialize i2c, set pin1 as sda, set pin2 as scl
    i2c.setup(id,sda,scl,i2c.SLOW)

    -- user defined function: read from reg_addr content of dev_addr
    function read_reg(dev_addr, reg_addr)
      i2c.start(id)
      i2c.address(id, dev_addr ,i2c.TRANSMITTER)
      i2c.write(id,reg_addr)
      i2c.stop(id)
      i2c.start(id)
      i2c.address(id, dev_addr,i2c.RECEIVER)
      c=i2c.read(id,1)
      i2c.stop(id)
      return c
    end

    -- get content of register 0xAA of device 0x77
    reg = read_reg(0x77, 0xAA)
    print(string.byte(reg))

####See also - i2c.write()

- Back to Index

#adc module ##CONSTANT none

adc.read()

####Description read adc value of id, esp8266 has only one 10bit adc, id=0, pin TOUT

####Syntax adc.read(id)

####Parameters id = 0

####Returns adc value

####See also -

- Back to Index

adc.readvdd33()

####Description Reading vdd33 pin voltage

####Syntax adc.readvdd33()

####Parameters no parameters ####Returns mV

####Example

    print(adc.readvdd33())

output

3345

    v = adc.readvdd33() / 1000
    print(v)
    v=nil

output

3.315

####See also -

- Back to Index

#uart module

##CONSTANT uart.STOPBITS_1, uart.STOPBITS_1_5, uart.STOPBITS_2, uart.PARITY_NONE, uart.PARITY_EVEN, uart.PARITY_ODD

uart.setup()

####Description setup uart's baud, databits, parity, stopbits, echo.

####Syntax uart.setup( id, baud, databits, parity, stopbits, echo )

####Parameters id = 0, only 1 uart supported.
baud = 300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 74880, 115200, 230400, 460800, 921600, 1843200, 2686400.
databits = 5, 6, 7, 8.
parity = 0(none), PARITY_ODD, PARITY_EVEN.
stopbits = 1(1 stopbit), STOPBITS_1, STOPBITS_1_5, STOPBITS_2.
echo = 0(close echo back).

####Returns baud.

####See also -

- Back to Index

uart.on()

####Description set the callback function to the uart event,
"data" event supported, means there is data input from uart.

####Syntax uart.on(method, [number/end_char], [function], [run_input])

####Parameters method = "data", there is data input from uart.
number/end_char: if pass in a number n<255, the callback will called when n chars are received.
if n=0, will receive every char in buffer.
if pass in a one char string "c", the callback will called when "c" is encounterd, or max n=255 received.
function: callback function, event "data" has a callback like this: function(data) end
run_input: 0 or 1, 0: input from uart will not go into lua interpreter, can accept binary data.
1: input from uart will go into lua interpreter, and run.

####Returns nil

####Example

    -- when 4 chars is received.
    uart.on("data", 4, 
      function(data)
        print("receive from uart:", data)
        if data=="quit" then 
          uart.on("data") 
        end        
    end, 0)
    -- when '\r' is received.
    uart.on("data", "\r", 
      function(data)
        print("receive from uart:", data)
        if data=="quit\r" then 
          uart.on("data") 
        end        
    end, 0)

####See also -

- Back to Index

uart.write()

####Description write string or byte to uart.

####Syntax uart.write( id, data1, data2, ... )

####Parameters id = 0, only 1 uart supported.
data1..n: string or byte to send via uart.

####Returns nil

####See also -

- Back to Index

uartalt()

####Description Change uart pins

####Syntax uart.alt( on )

####Parameters on = 0, use standard pins on = 1, use alternate pins GPIO13 and GPIO15

####Returns nil

####See also -

- Back to Index

#onewire module

##CONSTANT none

ow.setup()

####Description set a pin in onewire mode.

####Syntax ow.setup(pin)

####Parameters pin: 1~12, IO index

####Returns nil

####See also -

- Back to Index

ow.reset()

####Description Perform a 1-Wire reset cycle.

####Syntax ow.reset(pin)

####Parameters pin: 1~12, IO index

####Returns number: Returns 1 if a device responds with a presence pulse. Returns 0 if there is no device or the bus is shorted or otherwise held low for more than 250uS

####See also -

- Back to Index

ow.skip()

####Description Issue a 1-Wire rom skip command, to address all on bus.

####Syntax ow.skip(pin)

####Parameters pin: 1~12, IO index

####Returns nil

####See also -

- Back to Index

ow.select()

####Description Issue a 1-Wire rom select command, make sure you do the ow.reset(pin) first.

####Syntax ow.select(pin, rom)

####Parameters pin: 1~12, IO index
rom: string value, len 8, rom code of the salve device

####Returns nil

####Example

-- 18b20 Example
pin = 9
ow.setup(pin)
count = 0
repeat
  count = count + 1
  addr = ow.reset_search(pin)
  addr = ow.search(pin)
  tmr.wdclr()
until((addr ~= nil) or (count > 100))
if (addr == nil) then
  print("No more addresses.")
else
  print(addr:byte(1,8))
  crc = ow.crc8(string.sub(addr,1,7))
  if (crc == addr:byte(8)) then
    if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then
      print("Device is a DS18S20 family device.")
        repeat
          ow.reset(pin)
          ow.select(pin, addr)
          ow.write(pin, 0x44, 1)
          tmr.delay(1000000)
          present = ow.reset(pin)
          ow.select(pin, addr)
          ow.write(pin,0xBE,1)
          print("P="..present)  
          data = nil
          data = string.char(ow.read(pin))
          for i = 1, 8 do
            data = data .. string.char(ow.read(pin))
          end
          print(data:byte(1,9))
          crc = ow.crc8(string.sub(data,1,8))
          print("CRC="..crc)
          if (crc == data:byte(9)) then
             t = (data:byte(1) + data:byte(2) * 256) * 625
             t1 = t / 10000
             t2 = t % 10000
             print("Temperature="..t1.."."..t2.."Centigrade")
          end                   
          tmr.wdclr()
        until false
    else
      print("Device family is not recognized.")
    end
  else
    print("CRC is not valid!")
  end
end

####See also -

- Back to Index

ow.write()

####Description Write a byte. If 'power' is 1 then the wire is held high at the end for parasitically powered devices. You are responsible for eventually depowering it by calling depower() or doing another read or write.

####Syntax ow.write(pin, v, power)

####Parameters pin: 1~12, IO index
v: byte to be written to salve device
power: 1 for wire being held high for parasitically powered devices.

####Returns nil

####Example

####See also -

- Back to Index

ow.write_bytes()

####Description Write multi bytes. If 'power' is 1 then the wire is held high at the end for parasitically powered devices. You are responsible for eventually depowering it by calling depower() or doing another read or write.

####Syntax ow.write_bytes(pin, buf, power)

####Parameters pin: 1~12, IO index
buf: string to be written to slave device
power: 1 for wire being held high for parasitically powered devices.

####Returns nil

####Example

####See also -

- Back to Index

ow.read()

####Description read a byte.

####Syntax ow.read(pin)

####Parameters pin: 1~12, IO index

####Returns byte read from slave device.

####Example

####See also -

- Back to Index

ow.read_bytes()

####Description read multi bytes.

####Syntax ow.read_bytes(pin, size)

####Parameters pin: 1~12, IO index
size: number of bytes to be read from slave device.

####Returns string: bytes read from slave device.

####Example

####See also -

- Back to Index

ow.depower()

####Description Stop forcing power onto the bus. You only need to do this if you used the 'power' flag to ow.write() or used a ow.write_bytes() and aren't about to do another read or write.

####Syntax ow.depower(pin)

####Parameters pin: 1~12, IO index

####Example

####Returns nil

####See also -

- Back to Index

ow.reset_search()

####Description Clear the search state so that it will start from the beginning again.

####Syntax ow.reset_search(pin)

####Parameters pin: 1~12, IO index

####Returns nil

####Example

####See also -

- Back to Index

ow.target_search()

####Description Setup the search to find the device type 'family_code' on the next call to ow.search() if it is present.

####Syntax ow.target_search(pin, family_code)

####Parameters pin: 1~12, IO index
family_code: byte for family code.

####Returns nil

####Example

####See also -

- Back to Index

ow.search()

####Description Look for the next device.

####Syntax ow.search(pin)

####Parameters pin: 1~12, IO index

####Returns if succeed return a string length of 8, which contain the rom code of slave device.
if failed in searching next device return nil.

####Example

####See also -

- Back to Index

ow.crc8()

####Description Compute a Dallas Semiconductor 8 bit CRC, these are used in the ROM and scratchpad registers.

####Syntax ow.crc8(buf)

####Parameters buf: string value, data to be calculated check sum in string.

####Returns crc result in byte.

####Example

####See also -

- Back to Index

ow.check_crc16()

####Description Compute the 1-Wire CRC16 and compare it against the received CRC.

####Syntax ow.check_crc16(buf, inverted_crc0, inverted_crc1, crc)

####Parameters buf: string value, data to be calculated check sum in string.
inverted_crc0: LSB of received CRC.
inverted_crc1: MSB of received CRC.
crc: crc starting value (optional)

####Returns bool: true, if the CRC matches; false for dismatches.

####Example

####See also -

- Back to Index

ow.crc16()

####Description Compute a Dallas Semiconductor 16 bit CRC. This is required to check the integrity of data received from many 1-Wire devices. Note that the CRC computed here is not what you'll get from the 1-Wire network, for two reasons:
1) The CRC is transmitted bitwise inverted.
2) Depending on the endian-ness of your processor, the binary representation of the two-byte return value may have a different byte order than the two bytes you get from 1-Wire.

####Syntax ow.crc16(buf, crc)

####Parameters buf: string value, data to be calculated check sum in string.
crc: crc starting value (optional)

####Returns return The CRC16, as defined by Dallas Semiconductor.

####Example

####See also -

- Back to Index

#bit module

##CONSTANT none

bit.bnot()

####Description Bitwise negation, equivalent to ~value in C.

####Syntax bit.bnot(value)

####Parameters value: the number to negate.

####Returns number: the bitwise negated value of the number.

####Example

####See also -

- Back to Index

bit.band()

####Description Bitwise AND, equivalent to val1 & val2 & ... & valn in C.

####Syntax bit.band(val1, val2, ... valn)

####Parameters val1: first AND argument.
val2: second AND argument.
valn: nth AND argument.

####Returns number: the bitwise AND of all the arguments.

####Example

####See also -

- Back to Index

bit.bor()

####Description Bitwise OR, equivalent to val1 | val2 | ... | valn in C.

####Syntax bit.bor(val1, val2, ... valn)

####Parameters val1: first OR argument.
val2: second OR argument.
valn: nth OR argument.

####Returns number: the bitwise OR of all the arguments.

####Example

####See also -

- Back to Index

bit.bxor()

####Description Bitwise XOR, equivalent to val1 ^ val2 ^ ... ^ valn in C.

####Syntax bit.bxor(val1, val2, ... valn)

####Parameters val1: first XOR argument.
val2: second XOR argument.
valn: nth XOR argument.

####Returns number: the bitwise XOR of all the arguments.

####Example

####See also -

- Back to Index

bit.lshift()

####Description Left-shift a number, equivalent to value << shift in C.

####Syntax bit.lshift(value, shift)

####Parameters value: the value to shift.
shift: positions to shift.

####Returns number: the number shifted left

####Example

####See also -

- Back to Index

bit.rshift()

####Description Logical right shift a number, equivalent to ( unsigned )value >> shift in C.

####Syntax bit.rshift(value, shift)

####Parameters value: the value to shift.
shift: positions to shift.

####Returns number: the number shifted right (logically).

####Example

####See also -

- Back to Index

bit.arshift()

####Description Arithmetic right shift a number equivalent to value >> shift in C.

####Syntax bit.arshift(value, shift)

####Parameters value: the value to shift.
shift: positions to shift.

####Returns number: the number shifted right (arithmetically).

####Example

####See also -

- Back to Index

bit.bit()

####Description Generate a number with a 1 bit (used for mask generation). Equivalent to 1 << position in C.

####Syntax bit.bit(position)

####Parameters position: position of the bit that will be set to 1.

####Returns number: a number with only one 1 bit at position (the rest are set to 0).

####Example

####See also -

- Back to Index

bit.set()

####Description Set bits in a number.

####Syntax bit.set(value, pos1, pos2, ..., posn)

####Parameters value: the base number.
pos1: position of the first bit to set.
pos2: position of the second bit to set.
posn: position of the nth bit to set.

####Returns number: the number with the bit(s) set in the given position(s).

####Example

####See also -

- Back to Index

bit.clear()

####Description Clear bits in a number.

####Syntax bit.clear(value, pos1, pos2, ..., posn)

####Parameters value: the base number.
pos1: position of the first bit to clear.
pos2: position of the second bit to clear.
posn: position of thet nth bit to clear.

####Returns number: the number with the bit(s) cleared in the given position(s).

####Example

####See also -

- Back to Index

bit.isset()

####Description Test if a given bit is set.

####Syntax bit.isset(value, position)

####Parameters value: the value to test.
position: bit position to test.

####Returns boolean: true if the bit at the given position is 1, false otherwise.

####Example

####See also -

- Back to Index

bit.isclear()

####Description Test if a given bit is cleared.

####Syntax bit.isclear(value, position)

####Parameters value: the value to test.
position: bit position to test.

####Returns boolean: true if the bit at the given position is 0, false othewise.

####Example

####See also -

- Back to Index

#spi module ##CONSTANT MASTER, SLAVE, CPHA_LOW, CPHA_HIGH, CPOL_LOW, CPOL_HIGH

DATABITS_8, DATABITS_16 -- Deprecated

All transactions for sending and receiving are most-significant-bit first and least-significant last.

spi.setup()

####Description setup spi configuration.

####Syntax spi.setup( id, mode, cpol, cpha, databits, clock_div, [duplex_mode] )

####Parameters id: spi id number.
mode: MASTER or SLAVE(not supported yet).
cpol: CPOL_LOW or CPOL_HIGH, clock polarity. CPOL_HIGH is not supported currently.
cpha: CPHA_HIGH or CPHA_LOW, clock phase.
databits: DATABITS_8, 1 - 32.
clock_div: spi clock divider, f(SPI) = f(CPU) / clock_div.
duplex_mode: spi.HALFDUPLEX (default), spi.FULLDUPLEX.

####Returns number: 1.

####Example

####See also -

- Back to Index

spi.send()

####Description send data via SPI in half-duplex mode. send & receive data in full-duplex mode.

####Syntax HALFDUPLEX:
wrote = spi.send( id, data1, [data2], ..., [datan] )

FULLDUPLEX:
wrote[, rdata1, ..., [rdatan]] = spi.send( id, data1, [data2], ..., [datan] )

####Parameters id: spi id number.
data: data can be either a string, a table or an integer number
Each data item is considered with databits number of bits.

####Returns wrote: bytes writen count.
rdata: received data when configured with spi.FULLDUPLEX. see spi.setup().
same data type as correspding data parameter

####Example

####See also -

- Back to Index

spi.recv()

####Description recv data from spi.

####Syntax read = spi.recv( id, size, [default_data] )

####Parameters id: spi id number.
size: data size want to read. default_data: default data being sent on MOSI (all-1 if omitted)

####Returns string: string bytes read from spi.

####Example

####See also -

- Back to Index

spi.set_mosi()

####Description Insert data items into MOSI buffer for spi.transaction().

####Syntax spi.set_mosi( id, offset, bitlen, data1, [data2], ..., [datan] )

####Parameters id: spi id number.
offset: bit offset into MOSI buffer for inserting data1 and subsequent items.
bitlen: bit length of data1, data2, ...
data: data items, bitlen number of bits considered for transaction.

####Returns nil

####Example

####See also -

- Back to Index

spi.get_miso()

####Description Extract data items from MISO buffer after spi.transaction().

####Syntax data1, [data2], ..., [datan] = spi.get_miso( id, offset, bitlen, num )

####Parameters id: spi id number.
offset: bit offset into MISO buffer for first data item.
bitlen: bit length of data items.
num: number of data items to retrieve.

####Returns num data items.

####Example

####See also -

- Back to Index

spi.transaction()

####Description Start an SPI transaction, consisting of up to 5 phases:

  1. Command
  2. Address
  3. MOSI
  4. Dummy
  5. MISO

####Syntax spi.transaction( id, cmd_bitlen, cmd_data, addr_bitlen, addr_data, mosi_bitlen, dummy_bitlen, miso_bitlen )

####Parameters cmd_bitlen: bit length of the command phase (0 - 16).
cmd_data: data for command phase.
addr_bitlen: bit length for address phase (0 - 32).
addr_data: data for command phase.
mosi_bitlen: bit length of the MOSI phase (0 - 512).
dummy_bitlen: bit length of the dummy phase (0 - 256).
miso_bitlen: bit length of the MISO phase (0 - 512), half-duplex.
full-duplex mode is activated with negative value.

####Returns nil

####Example

####See also -

- Back to Index

#mqtt module ##CONSTANT

mqtt.Client()

####Description Create a MQTT client. The client adheres to version 3.1.1 of the MQTT protocol, make sure that your broker supports and is correctly configured for version 3.1.1 of the MQTT protocol. The client is incompatible with brokers running version 3.1 of the MQTT protocol.

####Syntax mqtt.Client(clientid, keepalive, user, pass, cleansession)

####Parameters clientid: the client id.
keepalive: keepalive second, a number.
user: user name, a string.
pass: user password, a string.
cleansession: clean session ,a number, 0 for false and 1 for true.

####Returns mqtt client.

####Example

-- init mqtt client with keepalive timer 120sec
m = mqtt.Client("clientid", 120, "user", "password")

-- setup Last Will and Testament (optional)
-- Broker will publish a message with qos = 0, retain = 0, data = "offline" 
-- to topic "/lwt" if client don't send keepalive packet
m:lwt("/lwt", "offline", 0, 0)

m:on("connect", function(con) print ("connected") end)
m:on("offline", function(con) print ("offline") end)

-- on publish message receive event
m:on("message", function(conn, topic, data) 
  print(topic .. ":" ) 
  if data ~= nil then
    print(data)
  end
end)

-- for secure: m:connect("192.168.11.118", 1880, 1)
m:connect("192.168.11.118", 1880, 0, function(conn) print("connected") end)

-- subscribe topic with qos = 0
m:subscribe("/topic",0, function(conn) print("subscribe success") end)

-- publish a message with data = hello, QoS = 0, retain = 0
m:publish("/topic","hello",0,0, function(conn) print("sent") end)

m:close();
-- you can call m:connect again

####See also -

- Back to Index

#mqtt client module

mqtt.client:lwt()

####Description setup Last Will and Testament (optional)
Broker will publish a message with qos = 0, retain = 0, data = "offline"
to topic "/lwt" if client don't send keepalive packet.

####Syntax mqtt:lwt(topic, message, qos, retain)

####Parameters topic: the topic to publish to, String.
message: the message to publish, Buffer or String.
qos: qos level, default 0.
retain: retain flag, default 0.

####Returns nil.

####Example

####See also -

- Back to Index

mqtt.client:connect()

####Description Connects to the broker specified by the given host, port, and secure options

####Syntax mqtt:connect( host, port, secure, function(client) )

####Parameters host: host domain or ip, string.
port: number, broker port.
secure: 0 or 1, default 0. As per #539 secure connections use TLS 1.2.
function(client): when connected, call this function.

####Returns nil.

####Example

####See also -

- Back to Index

mqtt.client:close()

####Description close connection to the broker.

####Syntax mqtt:close()

####Parameters nil

####Returns nil.

####Example

####See also -

- Back to Index

mqtt.client:publish()

####Description Publish a message

####Syntax mqtt:publish( topic, payload, qos, retain, function(client) )

####Parameters topic: the topic to publish to, string
message: the message to publish, string
qos: qos level, default 0
retain: retain flag, default 0
function(client): callback fired when PUBACK received.

####Returns nil.

####Example

####See also -

- Back to Index

mqtt.client:subscribe()

####Description Subscribe to a topic or topics

####Syntax mqtt:subscribe(topic, qos, function(client, topic, message))

####Parameters topic: a string topic to subscribe to
qos: qos subscription level, default 0
function(client, topic, message): callback fired when message received.

####Returns nil.

####Example

####See also -

- Back to Index

mqtt.client:on()

####Description register callback function to event.

####Syntax mqtt:on(event, function(client, [topic], [message]))

####Parameters event: string, which can be: "connect", "message", "offline"
function cb(client, [topic], [message]): callback function. The first param is the client.
If event is "message", the 2nd and 3rd param are received topic and message in string.

####Returns nil.

####Example

####See also -

#WS2801 Module

ws2801.init()

####Description Initializes the module and sets the pin configuration.

####Syntax ws2801.init(pin_clk, pin_data)

####Parameters pin_clk = Pin for the clock. Supported are GPIO 0, 2, 4, 5
pin_data = Pin for the data. Supported are GPIO 0, 2, 4, 5

####Return nil

ws2801.write()

####Description Sends a string of RGB Data in 24bits to WS2801. Don't forget to call ws2801.init() before.

####Syntax ws2801.write(string.char(R1,G1,B1(,R2,G2,B2...)) )

####Parameters R1 = The first pixel's red channel's value(0-255)
G1 = The first pixel's green channel's value(0-255)
B1 = The first pixel's blue channel's value(0-255)
... You can connect a lot of WS2801...
R2,G2,B2 is the next WS2801's Red, Green and Blue channel's value

####Return nil

#WS2812 Module

ws2812.writergb()

####Description Send the RGB Data in 8bits to WS2812

####Syntax ws2812.writergb(pin, string.char(R1,G1,B1(,R2,G2,B2...)) )

####Parameters pin = Supported all the PINs(0,1,2...)
R1 = The first WS2812 though the line's Red Channel's Parameters(0-255)
G1 = The first WS2812 though the line's Green Channel's Parameters(0-255)
B1 = The first WS2812 though the line's Blue Channel's Parameters(0-255)
... You can connect a lot of WS2812...
R2,G2,B2 is the next WS2812's Red, Green and Blue Channel's Parameters

####Return nil

####Example

   r = 255
   g = 0
   b = 0
   rgb = string.char(r, g, b) 
   ws2812.writergb(2, rgb) -- turn first WS2812B, connected to pin 2, red 

cjson.encode()

####Description Encode table to json string

####Syntax cjson.encode(table)

####Parameters table = data to encode

####Return json string

####Example

print(cjson.encode({key="value"}))

cjson.decode()

####Description Decode json string to table

####Syntax cjson.decode(s)

####Parameters s = string to decode

####Return Lua table

####Example

t= cjson.decode("{\"key\":\"value\"}")
for k,v in pairs(t) do print(k,v) end

- Back to Index

#Crypto Module

crypto.hash()

####Description Compute a cryptographic hash of a Lua string.

####Syntax digest = crypto.hash(algo, str)

####Parameters algo = hash algorithm to use, case insensitive string
str = data to calculate the hash for

Supported hash algorithms are:

  • MD2 (not available by default, has to be explicitly enabled in user_config.h)
  • MD5
  • SHA1
  • SHA256, SHA384, SHA512 (unless disabled in user_config.h)

####Return A binary string containing the message digest. To obtain the textual version (ASCII hex characters), please use crypto.toHex().

####Example

print(crypto.toHex(crypto.hash("sha1","abc")))

crypto.hmac()

####Description Compute a HMAC (Hashed Message Authentication Code) signature for a Lua string.

####Syntax signature = crypto.hmac(algo, str, key)

####Parameters algo = hash algorithm to use, case insensitive string
str = data to calculate the hash for
key = key to use for signing, may be a binary string

Supported hash algorithms are:

  • MD2 (not available by default, has to be explicitly enabled in user_config.h)
  • MD5
  • SHA1
  • SHA256, SHA384, SHA512 (unless disabled in user_config.h)

####Return A binary string containing the HMAC signature. Use crypto.toHex() to obtain the textual version.

####Example

print(crypto.toHex(crypto.hmac("sha1","abc","mysecret")))

crypto.mask()

####Description Applies an XOR mask to a Lua string.

####Syntax masked = crypto.mask (message, mask)

####Parameters message = message to mask
mask = the mask to apply, repeated if shorter than the message

####Return The masked message, as a binary string. Use crypto.toHex() to get a textual representation of it.

####Example

print(crypto.toHex(crypto.mask("some message to obscure","X0Y7")))

crypto.toHex()

####Description Provides an ASCII hex representation of a (binary) Lua string. Each byte in the input string is represented as two hex characters in the output.

####Syntax hexstr = crypto.toHex(binary)

####Parameters binary = input string to get hex representation for

####Return An ASCII hex string.

####Example

print(crypto.toHex(crypto.hash("sha1","abc")))

crypto.toBase64()

####Description Provides a Base64 representation of a (binary) Lua string.

####Syntax b64 = crypto.toBase64(binary)

####Parameters binary = input string to Base64 encode

####Return A Base64 encoded string.

####Example

print(crypto.toBase64(crypto.hash("sha1","abc")))

- Back to Index

#u8g module ##CONSTANT u8g.DRAW_UPPER_RIGHT, u8g.DRAW_UPPER_LEFT, u8g.DRAW_LOWER_RIGHT, u8g.DRAW_LOWER_LEFT, u8g.DRAW_ALL, u8g.MODE_BW, u8g.MODE_GRAY2BIT

u8g.font_6x10, ...

u8g.*_i2c()

####Description Initialize a display via I2C.

####Syntax Example u8g.ssd1306_128x64_i2c(sla)

####Parameters sla: I2C slave address.

####Returns u8g display.

####Example

sda = 5
scl = 6
i2c.setup(0, sda, scl, i2c.SLOW)

sla = 0x3c
disp = u8g.ssd1306_128x64_i2c(sla)

####See also

- Back to Index

u8g.*_hw_spi()

####Description Initialize a display via Hardware SPI.

####Syntax Example u8g.ssd1306_128x64_spi(cs, dc, res)

####Parameters cs: GPIO pin for /CS.
dc: GPIO pin for DC.
res: GPIO pin for /RES (optional).

####Returns u8g display.

####Example

spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, spi.DATABITS_8, 0)

cs  = 8 -- GPIO15, pull-down 10k to GND
dc  = 4 -- GPIO2
res = 0 -- GPIO16, RES is optional YMMV
disp = u8g.ssd1306_128x64_spi(cs, dc, res)

####See also

- Back to Index

#u8g display sub-module The Lua bindings for this library closely follow u8glib's object oriented C++ API. Visit the u8glib wiki for technical details.

u8g.disp:drawBitmap()

####Description Draw a bitmap at the specified x/y position (upper left corner of the bitmap). Parts of the bitmap may be outside the display boundaries. The bitmap is specified by the array bitmap. A cleared bit means: Do not draw a pixel. A set bit inside the array means: Write pixel with the current color index. For a monochrome display, the color index 0 will usually clear a pixel and the color index 1 will set a pixel.

####Syntax disp.drawBitmap(x, y, cnt, h, bitmap)

####Parameters x: X-position (left position of the bitmap).
y: Y-position (upper position of the bitmap).
cnt: Number of bytes of the bitmap in horizontal direction. The width of the bitmap is cnt*8.
h: Height of the bitmap.
bitmap: Bitmap data supplied as string.

####Returns nil

####Example lua_examples/u8glib/u8g_bitmaps.lua

####See also u8glib drawBitmap()

- Back to Index

u8g.disp:drawXBM()

####Description Draw a XBM Bitmap. Position (x,y) is the upper left corner of the bitmap. XBM contains monochrome, 1-bit bitmaps. This procedure only draws pixel values 1. The current color index is used for drawing (see setColorIndex). Pixel with value 0 are not drawn (transparent).

Bitmaps and XBMs are supplied as strings to drawBitmap() and drawXBM(). This off-loads all data handling from the u8g module to generic methods for binary files. In contrast to the source code based inclusion of XBMs into u8glib, it's required to provide precompiled binary files. This can be performed online with Online-Utility's Image Converter: Convert from XBM to MONO format and upload the binary result with nodemcu-uploader.py or ESPlorer.

####Syntax disp.drawXBM(x, y, w, h, bitmap)

####Parameters x: X-position (left position of the bitmap).
y: Y-position (upper position of the bitmap).
w: Width of the bitmap.
h: Height of the bitmap.
bitmap: XBM data supplied as string.

####Returns nil

####Example lua_examples/u8glib/u8g_bitmaps.lua

####See also u8glib drawXBM()

- Back to Index

u8g.disp:setFont()

####Description u8glib comes with a wide range of fonts for small displays. Since they need to be compiled into the firmware image, you'd need to include them in app/include/u8g_config.h and recompile. Simply add the desired fonts to the font table:

#define U8G_FONT_TABLE \
    U8G_FONT_TABLE_ENTRY(font_6x10)  \
    U8G_FONT_TABLE_ENTRY(font_chikita)

They'll be available as u8g.<font_name> in Lua.

####Syntax disp.setFont(font)

####Parameters font: Constant to indentify pre-compiled font.

####Returns nil

####Example

disp:setFont(u8g.font_6x10)

####See also u8glib setFont()

- Back to Index

#dht module ##CONSTANT dht.OK, dht.ERROR_CHECKSUM, dht.ERROR_TIMEOUT

  • dht.OK is 0, dht.ERROR_CHECKSUM is 1, dht.ERROR_TIMEOUT is 2

dht.read()

####Description Read all kinds of dht sensors, including dht11, 21, 22, 33, 44 humidity temperature combo sensor.

####Syntax dht.read(pin)

####Parameters pin: pin number of dht sensor (can't be 0), type is number

####Return integer of status, number of temperature, humidity, decimial of temperature, decimial of humidity.
status is integer, temperature, humidity, decimial of temperature, decimial of humidity is number. *Note: If using float firmware, the temperature, humidity already with decimial.

####Example

pin = 5
status,temp,humi,temp_decimial,humi_decimial = dht.read(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

dht.read11()

####Description Read dht11 humidity temperature combo sensor.

####Syntax dht.read11(pin)

####Parameters pin: pin number of dht sensor (can't be 0), type is number

####Return integer of status, number of temperature, humidity, decimial of temperature, decimial of humidity.
status is integer, temperature, humidity, decimial of temperature, decimial of humidity is number. *Note: If using float firmware, the temperature, humidity already with decimial.

####Example

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

dht.readxx()

####Description Read all kinds of dht sensors, except dht11.

####Syntax dht.readxx(pin)

####Parameters pin: pin number of dht sensor (can't be 0), type is number

####Return integer of status, number of temperature, humidity, decimial of temperature, decimial of humidity.
status is integer, temperature, humidity, decimial of temperature, decimial of humidity is number. *Note: If using float firmware, the temperature, humidity already with decimial.

####Example

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

##sntp module

The SNTP module implements a Simple Network Time Procotol client. This includes support for the "anycast" NTP mode where, if supported by the NTP server(s) in your network, it is not necessary to even know the IP address of the NTP server.

When compiled together with the rtctime module it also offers seamless integration with it, potentially reducing the process of obtaining NTP synchronization to a simple sntp.sync() call without any arguments.

####See also

sntp.sync()

####Description Attempts to obtain time synchronization.

####Syntax sntp.sync([server_ip], [callback], [errcallback])

####Parameters If the server_ip argument is non-nil, that server is used. If nil, then the last contacted server is used. This ties in with the NTP anycast mode, where the first responding server is remembered for future synchronization requests. The easiest way to use anycast is to always pass nil for the server argument.

If the callback argument is provided it will be invoked on a successful synchronization, with three parameters: seconds, microseconds, and server. Note that when the rtctime module is available, there is no need to explicitly call rtctime.set() - this module takes care of doing so internally automatically, for best accuracy.

On failure, the errcallback will be invoked, if provided. The sntp module automatically performs a number of retries before giving up and reporting the error. This callback receives no parameters.

####Returns

  • nothing

####Example

-- Best effort, use the last known NTP server (or the NTP "anycast" address 224.0.1.1 initially)
sntp.sync()

-- Sync time with 192.168.0.1 and print the result, or that it failed
sntp.sync('192.168.0.1',
  function(sec,usec,server)
    print('sync', sec, usec, server)
  end,
  function()
   print('failed!')
  end
)

-Back to Index

###rtctime module

The rtctime module provides advanced timekeeping support for NodeMCU, including keeping time across deep sleep cycles (provided rtctime.dsleep() is used instead of node.dsleep()). This can be used to significantly extend battery life on battery powered sensor nodes, as it is no longer necessary to fire up the RF module each wake-up in order to obtain an accurate timestamp.

This module is intended for use together with NTP (Network Time Protocol) for keeping highly accurate real time at all times. Timestamps are available with microsecond precision, based on the Unix Epoch (1970/01/01 00:00:00).

Time keeping on the ESP8266 is technically quite challenging. Despite being named RTC, the RTC is not really a Real Time Clock in the normal sense of the word. While it does keep a counter ticking while the module is sleeping, the accuracy with which it does so is highly dependent on the temperature of the chip. Said temperature changes significantly between when the chip is running and when it is sleeping, meaning that any calibration performed while the chip is active becomes useless mere moments after the chip has gone to sleep. As such, calibration values need to be deduced across sleep cycles in order to enable accurate time keeping. This is one of the things this module does.

Further complicating the matter of time keeping is that the ESP8266 operates on three different clock frequencies - 52MHz right at boot, 80MHz during regular operation, and 160MHz if boosted. This module goes to considerable length to take all of this into account to properly keep the time.

To enable this module, it needs to be given a reference time at least once (via rtctime.set()). For best accuracy it is recommended to provide a reference time twice, with the second time being after a deep sleep.

Note that while the rtctime module can keep time across deep sleeps, it will lose the time if the module is unexpectedly reset.

Important: This module uses RTC memory slots 0-9, inclusive. As soon as rtctime.set() (or sntp.sync()) has been called these RTC memory slots will be used.

####See also

-Back to Index

rtctime.set()

####Syntax rtctime.set(seconds, microseconds)

####Parameters

  • seconds and microseconds in Unix epoch

####Description Sets the rtctime to a given timestamp in the Unix epoch (i.e. seconds from midnight 1970/01/01). If the module is not already keeping time, it starts now. If the module was already keeping time, it uses this time to help adjust its internal calibration values. Care is taken that timestamps returned from rtctime.get() never go backwards. If necessary, time is slewed and gradually allowed to catch up.

It is highly recommended that the timestamp is obtained via NTP, GPS, or other highly accurate time source.

Values very close to the epoch are not supported. This is a side effect of keeping the memory requirements as low as possible. Considering that it's no longer 1970, this is not considered a problem.

####Returns

  • nothing

####Example

rtctime.set(1436430589, 0) -- Set time to 2015 July 9, 18:29:49

####See also

-Back to Index

rtctime.get()

####Description Returns the current time. If current time is not available, zero is returned.

####Parameters

  • none

####Returns

  • two values that represent seconds and microseconds since the start of Unix epoch

####Example

sec, usec = rtctime.get()

-Back to Index

rtctime.dsleep()

####Description Puts the ESP8266 into deep sleep mode, like node.dsleep(). It differs from node.dsleep() in the following ways:

  • Time is kept across the deep sleep. i.e. rtctime.get() will keep working (provided time was available before the sleep)
  • This call never returns. The module is put to sleep immediately. This is both to support accurate time keeping and to reduce power consumption.
  • The time slept will generally be considerably more accurate than with node.dsleep().
  • A sleep time of zero does not mean indefinite sleep, it is interpreted as a zero length sleep instead.

####Syntax rtctime.dsleep(microseconds [, option])

####Parameters

  • sleep time in microseconds
  • type of sleep, like for node.dsleep()

####Returns

  • nothing

####Example

rtctime.dsleep(60*1000000) -- sleep for a minute
rtctime.dsleep(5000000, 4) -- sleep for 5 seconds, do not start RF on wakeup

-Back to Index

rtctime.dsleep_aligned()

####Description For applications where it is necessary to take samples with high regularity, this function is useful. It provides an easy way to implement a "wake up on the next 5-minute boundary" scheme, without having to explicitly take into account how long the module has been active for etc before going back to sleep.

####Syntax rtctime.dsleep_aligned(aligned_us, minsleep_us [, option])

####Parameters

  • aligned_us parameter specifies the boundary interval in microseconds.
  • minsleep_us parameter is a minimum time that will be slept, if necessary skipping an interval. This is intended for sensors where a sample reading is started before putting the ESP8266 to sleep, and then fetched upon wake-up. Here minsleep_us should be the minimum time required for the sensor to take the sample.
  • as with node.dsleep(), the option sets the sleep option, if specified.

####Returns

  • nothing

####Example

rtctime.dsleep_aligned(5*1000000, 3*1000000) -- sleep at least 3 seconds, then wake up on the next 5-second boundary

-Back to Index

###rtcmem module

The RTC in the ESP8266 contains memory registers which survive a deep sleep, making them highly useful for keeping state across sleep cycles. Some of this memory is reserved for system use, but 128 slots (each 32bit wide) are available for application use. This module provides read and write access to these.

Due to the very limited amount of memory available, there is no mechanism for arbitrating use of particular slots. It is up to the end user to be aware of which memory is used for what, and avoid conflicts. Note that some Lua modules lay claim to certain slots.

####See also

rtcmem.read32()

####Description Reads num 32bit values from the RTC user memory, starting at index idx (zero-based). If num is not specified, a value of 1 is assumed.

####Syntax rtcmem.read32(idx [,num])

####Parameters

  • idx, index from which to start reading
  • num, number of 32bit elements to read

####Returns If idx is outside the valid range [0,127] this function returns nothing. If num results in overstepping the end of available memory, the function only returns the data from the valid slots.

####Example

val = rtcmem.read32(0) -- Read the value in slot 0
val1, val2 = rtcmem.read32(42, 2) -- Read the values in slots 42 and 43

-Back to Index

rtcmem.write32()

####Description Writes one or more values to RTC user memory, starting at index idx. Writing to indices outside the valid range [0,127] has no effect.

####Syntax rtcmem.write32(idx, val [, val2, ...] )

####Parameters

  • idx, starting user memory position
  • val[...], values to be written

####Example

rtcmem.read32(0, 53) -- Store the value 53 in slot 0
rtcmem.read32(42, 2, 5, 7) -- Store the values 2, 5 and 7 into slots 42, 43 and 44, respectively.

-Back to Index

###rtcfifo module

The rtcfifo module implements a first-in,first-out storage intended for sensor readings. As the name suggests, it is backed by the RTC user memory and as such survives deep sleep cycles. Conceptually it can be thought of as a cyclic array of { timestamp, name, value } tuples. Internally it uses a space-optimized storage format to allow the greatest number of samples to be kept. This comes with several trade-offs, and as such is not a one-solution-fits-all. Notably:

  • Timestamps are stored with second-precision.
  • Sample frequency must be at least once every 8.5 minutes. This is a side-effect of delta-compression being used for the time stamps.
  • Values are limited to 16 bits of precision, but have a separate field for storing an E-n multiplier. This allows for high fidelity even when working with very small values. The effective range is thus 1E-7 to 65535.
  • Sensor names are limited to a maximum of 4 characters.

Important: This module uses two sets of RTC memory slots, 10-20 for its control block, and a variable number of slots for samples and sensor names. By default these span 32-127, but this is configurable. Slots are claimed when rtcfifo.prepare() is called.

####See also

rtcfifo.prepare()

####Description Initializes the rtcfifo module for use. It takes an optional configuration table as an argument.

####Syntax rtcfifo.prepare([table])

####Parameters

  • table with key=value pairs

The following items may be configured:

  • interval_us: If wanting to make use of the rtcfifo.sleep_until_sample() function, this field sets the sample interval (in microseconds) to use. It is effectively the first argument of rtctime.dsleep_aligned().
  • sensor_count: Specifies the number of different sensors to allocate name space for. This directly corresponds to a number of slots reserved for names in the variable block. The default value is 5, minimum is 1, and maximum is 16.
  • storage_begin: Specifies the first RTC user memory slot to use for the variable block. Default is 32. Only takes effect if storage_end is also specified.
  • storage_end: Specified the end of the RTC user memory slots. This slot number will not be touched. Default is 128. Only takes effect if storage_begin is also specified.

Calling rtcfifo.prepare() unconditionally re-initializes the storage - any samples stored are discarded.

####Returns

  • nothing

####See also

####Example

rtcfifo.prepare() -- Initialize with default values
rtcfifo.prepare({storage_begin=21, storage_end=128}) -- Use RTC slots 19 and up for variable storage

-Back to Index

rtcfifo.ready()

####Description Checks if rtcfifo is prepared.

####Syntax rtcfifo.ready()

####Parameters

  • none

####Returns Returns non-zero if the rtcfifo has been prepared and is ready for use, zero if not.

####Example

if not rtcfifo.ready() then -- Prepare the rtcfifo if not already done
  rtcfifo.prepare()
end

-Back to Index

rtcfifo.put()

####Description Puts a sample into the rtcfifo.

####Syntax rtcfifo.put(timestamp, value, neg_e, name)

####Parameters

  • timestamp
  • sample value
  • sample name

The timestamp would typically come from rtctime.get(). The effective value stored is valueE<sup>neg_e</sup>. Only the first four (ASCII) characters of name are used.

Note that if the timestamp delta is too large compared to the previous sample stored, the rtcfifo evicts all earlier samples to store this one. Likewise, if name would mean there are more than the sensor_count (as specified to rtcfifo.prepare()) names in use, the rtcfifo evicts all earlier samples.

If the rtcfifo has not been prepared, this function does nothing.

####Returns

  • nothing

####Example

local sample = ... -- Obtain a sample value from somewhere
rtcfifo.put(rtctime.get(), sample, 0, "foo") -- Store sample with no scaling, under the name "foo"

-Back to Index

rtcfifo.peek()

####Description Reads a sample from the rtcfifo.

####Syntax rtcfifo.peek([offset])

####Parameters An offset into the rtcfifo may be specified, but by default it reads the first sample (offset 0).

####Returns

  • sample from rtcfifo

If no sample is available (at the specified offset), nothing is returned. The values returned match the input arguments used to rtcfifo.put().

####Example

local timestamp, value, neg_e, name = rtcfifo.peek()

-Back to Index

rtcfifo.pop()

####Description Reads the first sample from the rtcfifo, and removes it from there.

####Syntax rtcfifo.pop()

####Parameters

  • none

####Returns

  • first sample from the rtcfifo

If the rtcfifo is empty, nothing is returned. The values returned match the input arguments used to rtcfifo.put().

####Example

local timestamp, value, neg_e, name = rtcfifo.pop()

-Back to Index

rtcfifo.drop()

####Description Discards samples from the rtcfifo.

####Syntax rtcfifo.drop(num)

####Parameters

  • number of samples to discard

If num is greater or equal to the number of samples currently stored, the rtcfifo will be empty on return.

####Returns

  • nothing

####Example

rtcfifo.drop(2) -- Discard the first two samples in the rtcfifo, if present

-Back to Index

rtcfifo.count()

####Description Returns the number of samples currently stored in the rtcfifo.

####Syntax rtcfifo.count()

####Parameters

  • none

####Returns

  • nothing

####Example

while rtcfifo.count() > 0 do
  local timestamp, value, neg_e, name = rtcfifo.pop()
  -- do something with the sample, e.g. upload to somewhere
end

-Back to Index

rtcfifo.dsleep_until_sample()

####Description When the rtcfifo module is compiled in together with the rtctime module, this convenience function is available. It allows for some measure of separation of concerns, enabling writing of modularized Lua code where a sensor reading abstraction may not need to be aware of the sample frequency (which is largely a policy decision, rather than an intrinsic of the sensor). Use of this function is effectively equivalent to rtctime.dsleep_aligned(interval_us, minsleep_us) where interval_us is what was given to rtcfifo.prepare().

####Syntax rtcfifo.dsleep_until_sample(minsleep_us)

####Parameters

  • time to deep sleep in microseconds, or zero if you want to wait undetermined time, until the next sampling cycle is started

####Returns

  • nothing

####Example

rtcfifo.dsleep_until_sample(0) -- deep sleep until it's time to take the next sample

####See also

-Back to Index

tsl2561 module

tsl2561.init()

Description

Initializes the device on pins sdapin&sclpin. Optionally also configures the devices address and package. (Default: address pin floating (0x39) and FN package)

Syntax

tsl2561.init(sdapin, sclpin) tsl2561.init(sdapin, sclpin, address) tsl2561.init(sdapin, sclpin, address, package)

Parameters

  • sdapin: Pin number of the device's I2C sda connection
  • sclpin: Pin number of the device's I2C scl connection
  • (optional) address: Address of the device on the I2C bus
  • tsl2561.ADDRESS_GND
  • tsl2561.ADDRESS_FLOAT (default)
  • tsl2561.ADDRESS_VDD
  • (optional) package: Device's package type (slight difference in lux calculation)
  • tsl2561.PACKAGE_CS
  • tsl2561.PACKAGE_T_FN_CL (default)

Return

status: value indicating success or failure as explained below

  • 0: tsl2561.TSL2561_OK
  • 1: tsl2561.TSL2561_ERROR_I2CINIT: Can't initialize I2C bus
  • 2: tsl2561.TSL2561_ERROR_I2CBUSY: I2C bus busy
  • 3: tsl2561.TSL2561_ERROR_NOINIT: Initialize I2C bus before calling function
  • 4: tsl2561.TSL2561_ERROR_LAST

Example

status = tsl2561.init(5,6,tsl2561.ADDRESS_FLOAT, tsl2561.PACKAGE_T_FN_CL)
if (status == 0) then
  lux = tsl2561.getlux()
  print("Illuminance: "..lux.." lx") 
end

-Back to Index

tsl2561.settiming()

Description

Sets the integration time and gain settings of the device. When init() is called, these values default to 402ms and no gain.

Syntax

tsl2561.settiming(integration, gain)

Parameters

  • integration: Sets the device's integration period. Valid options:
  • tsl2561.INTEGRATIONTIME_13MS
  • tsl2561.INTEGRATIONTIME_101MS
  • tsl2561.INTEGRATIONTIME_402MS (default)
  • gain: Sets the device's gain. Valid options:
  • tsl2561.GAIN_1X (default)
  • tsl2561.GAIN_16X

Return

status: value indicating success or failure as explained below

  • 0: tsl2561.TSL2561_OK
  • 1: tsl2561.TSL2561_ERROR_I2CINIT: Can't initialize I2C bus
  • 2: tsl2561.TSL2561_ERROR_I2CBUSY: I2C bus busy
  • 3: tsl2561.TSL2561_ERROR_NOINIT: Initialize I2C bus before calling function
  • 4: tsl2561.TSL2561_ERROR_LAST

Example

status = tsl2561.init(5,6,tsl2561.ADDRESS_FLOAT, tsl2561.PACKAGE_T_FN_CL)
if (status == 0) then
  status = tsl2561.settiming(tsl2561.INTEGRATIONTIME_101MS, tsl2561.GAIN_16X)
end
if (status == 0) then
  lux = tsl2561.getlux()
  print("Illuminance: "..lux.." lx") 
end

-Back to Index

tsl2561.getlux()

Description

Reads sensor values from the device and returns calculated lux value.

Syntax

tsl2561.getlux()

Parameters

nil

Return

  • lux: The calculated illuminance in lux (lx).
  • status: value indicating success or failure as explained below
    • 0: tsl2561.TSL2561_OK
    • 1: tsl2561.TSL2561_ERROR_I2CINIT: Can't initialize I2C bus
    • 2: tsl2561.TSL2561_ERROR_I2CBUSY: I2C bus busy
    • 3: tsl2561.TSL2561_ERROR_NOINIT: Initialize I2C bus before calling function
    • 4: tsl2561.TSL2561_ERROR_LAST

Example

status = tsl2561.init(5,6,tsl2561.ADDRESS_FLOAT, tsl2561.PACKAGE_T_FN_CL)

if (status == 0) then
  lux = tsl2561.getlux()
  print("Illuminance: "..lux.." lx") 
end

-Back to Index

tsl2561.getrawchannels()

Description

Reads the device's 2 sensors and returns their values.

Syntax

tsl2561.getrawchannels()

Parameters

nil

Return

  • ch0: Value of the broad spectrum sensor
  • ch1: Value of the IR sensor
  • status: value indicating success or failure as explained below
    • 0: tsl2561.TSL2561_OK
    • 1: tsl2561.TSL2561_ERROR_I2CINIT: Can't initialize I2C bus
    • 2: tsl2561.TSL2561_ERROR_I2CBUSY: I2C bus busy
    • 3: tsl2561.TSL2561_ERROR_NOINIT: Initialize I2C bus before calling function
    • 4: tsl2561.TSL2561_ERROR_LAST

Example

status = tsl2561.init(5,6,tsl2561.ADDRESS_FLOAT, tsl2561.PACKAGE_T_FN_CL)

if (status == 0) then
  ch0, ch1 = tsl2561.getrawchannels()
  print("Raw values: "..ch0,ch1)
  lux = tsl2561.getlux()
  print("Illuminance: "..lux.." lx") 
end

-Back to Index

ucg module

Display Drivers

ucg.disp sub-module

ucg.*_hw_spi()

Constants

ucg.FONT_MODE_TRANSPARENT, ucg.FONT_MODE_SOLID, ucg.DRAW_UPPER_RIGHT, ucg.DRAW_UPPER_LEFT, ucg.DRAW_LOWER_RIGHT, ucg.DRAW_LOWER_LEFT, ucg.DRAW_ALL

ucg.font_7x13B_tr, ...

Description

Initializes a display via Hardware SPI.

Syntax

ucg.st7735_18x128x160_hw_spi(cs, dc, res)

Parameters

cs: GPIO pin for /CS.
dc: GPIO pin for DC.
res: GPIO pin for /RES (optional).

Returns

ucg display.

Example

spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, spi.DATABITS_8, 0)

cs  = 8 -- GPIO15, pull-down 10k to GND
dc  = 4 -- GPIO2
res = 0 -- GPIO16, RES is optional YMMV
disp = ucg.st7735_18x128x160_hw_spi(cs, dc, res)

#enduser_setup module This module provides simple way of configuring esp8266 chips without using a serial interface or pre-programming wifi credentials onto the esp.

After running enduser_setup.start() a portal like the above can be accessed through a wireless network called SetupGadget_XXXXXX. The portal is used to submit the credentials for the wifi of the enduser. After an IP address successfully has been obtained this module will stop as if enduser_setup.stop() had been called.

enduser_setup.start()

####Description Start the captive portal.

####Syntax enduser_setup([onConfigured()], [onError(err_num, string)], [onDebug(string)])

####Parameters

  • onConfigured(), this callback will be fired when an IP-address has been obtained, just before the enduser_setop module will terminate itself.
  • onError(), this callback will be fired if an error is encountered. err_num is a number describing the error, and string is a string containing a description of the error.
  • onDebug(), this callback is disabled in the default build of the enduser_setup module. It is intended to be used to find internal issues in the module. string is a string containing a description of what is going on.

####Returns

  • nil

####Example

enduser_setup.start(
  function()
    print("Connected to wifi as:" .. wifi.sta.getip())
  end,
  function(err, str)
    print("enduser_setup: Err #" .. err .. ": " .. str)
  end
);

enduser_setup.stop()

####Description Stop the captive portal.

####Syntax enduser_setup.stop()

####Parameters

  • nil

####Returns

  • nil

####Example

enduser_setup.stop();

- Back to Index

Clone this wiki locally