Commit b2f9a563 authored by Johny Mattsson's avatar Johny Mattsson
Browse files

Merge branch 'dev-rtd' into newdocs

parents 547ebdf3 ee23e460
blockquote {
padding: 0 15px;
color: #777;
border-left: 4px solid #ddd;
}
.rst-content blockquote {
margin: 0;
}
/*shifts the nested subnav label to the left to align it with the regular nav item labels*/
ul.subnav ul.subnav span {
padding-left: 1.3em;
}
\ No newline at end of file
# NodeMCU Dokumentation
NodeMCU ist eine [eLua](http://www.eluaproject.net/)-basierende firmware für den [ESP8266 WiFi SOC von Espressif](http://espressif.com/en/products/esp8266/). Dies ist ein Partnerprojekt für die beliebten [NodeMCU dev kits](https://github.com/nodemcu/nodemcu-devkit-v1.0) - open source NodeMCU boards mit ESP8266-12E chips.
Diese firmware nutzt das Espressif SDK v1.4, das Dateisystem basiert auf [spiffs](https://github.com/pellepl/spiffs).
There are essentially three ways to build your NodeMCU firmware: cloud build service, Docker image, dedicated Linux environment (possibly VM).
## Cloud build service
NodeMCU "application developers" just need a ready-made firmware. There's a [cloud build service](http://nodemcu-build.com/) with a nice UI and configuration options for them.
## Docker image
Occasional NodeMCU firmware hackers don't need full control over the complete tool chain. They might not want to setup a Linux VM with the build environment. Docker to the rescue. Give [Docker NodeMCU build](https://hub.docker.com/r/marcelstoer/nodemcu-build/) a try.
## Linux build environment
NodeMCU firmware developers commit or contribute to the project on GitHub and might want to build their own full fledged build environment with the complete tool chain. There is a [post in the esp8266.com Wiki](http://www.esp8266.com/wiki/doku.php?id=toolchain#how_to_setup_a_vm_to_host_your_toolchain) that describes this.
\ No newline at end of file
This diff is collapsed.
Adafruit provides a really nice [firmware flashing tutorial](https://learn.adafruit.com/building-and-running-micropython-on-the-esp8266/flash-firmware). Below you'll find just the basics for the two popular tools esptool and NodeMCU Flasher.
!!! note "Note:"
Keep in mind that the ESP8266 needs to be put into flash mode before you can flash a new firmware!
## esptool
> A cute Python utility to communicate with the ROM bootloader in Espressif ESP8266. It is intended to be a simple, platform independent, open source replacement for XTCOM.
Source: [https://github.com/themadinventor/esptool](https://github.com/themadinventor/esptool)
Supported platforms: OS X, Linux, Windows, anything that runs Python
**Running esptool.py**
Run the following command to flash an *aggregated* binary as is produced for example by the [cloud build service](build.md#cloud-build-service) or the [Docker image](build.md#docker-image).
`esptool.py --port <USB-port-with-ESP8266> write_flash 0x00000 <nodemcu-firmware>.bin`
## NodeMCU Flasher
> A firmware Flash tool for NodeMCU...We are working on next version and will use QT framework. It will be cross platform and open-source.
Source: [https://github.com/nodemcu/nodemcu-flasher](https://github.com/nodemcu/nodemcu-flasher)
Supported platforms: Windows
\ No newline at end of file
# NodeMCU Documentation
NodeMCU is an [eLua](http://www.eluaproject.net/) based firmware for the [ESP8266 WiFi SOC from Espressif](http://espressif.com/en/products/esp8266/). This is a companion project to the popular [NodeMCU dev kits](https://github.com/nodemcu/nodemcu-devkit-v1.0), ready-made open source development boards with ESP8266-12E chips.
The firmware is based on the Espressif SDK v1.4 and uses a file system based on [spiffs](https://github.com/pellepl/spiffs).
## Getting started
- [Build the firmeware](build.md) with the modules you need.
- [Flash the firmware](flash.md) to the chip.
- Load your code into the firmware.
# ADC Module
The ADC module provides access to the in-built ADC.
On the ESP8266 there is only a single-channel, which is multiplexed with the
battery voltage. Depending on the setting in the "esp init data" (byte 107)
one can either use the ADC to read an external voltage, or to read the
system voltage, but not both.
The default setting in the NodeMCU firmware can be controlled via user_config.h at compile time, by defining one of ESP_INIT_DATA_ENABLE_READVDD33, ESP_INIT_DATA_ENABLE_READADC or ESP_INIT_DATA_FIXED_VDD33_VALUE. To change the setting
at a later date, use Espressif's flash download tool to create a new init data block.
## adc.read()
Samples the ADC.
####Syntax
`adc.read(channel)`
####Parameters
- `channel`: Always zero on the ESP8266
####Returns
number:the sampled value
####Example
```lua
val = adc.read(0)
```
___
## adc.readvdd33()
Reads the system voltage.
####Syntax
`adc.readvdd33()`
####Parameters
`nil`
####Returns
The system voltage, in millivolts.
If the ESP8266 has been configured to use the ADC for sampling the external pin, this function will always return 65535. This is a hardware and/or SDK limitation.
####Example
```lua
mv = adc.readvdd33()
```
___
# bit Module
Bit manipulation support, on 32bit integers.
## bit.bnot()
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.
___
## bit.band()
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.
___
## bit.bor()
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.
___
## bit.bxor()
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.
___
## bit.lshift()
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
___
## bit.rshift()
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).
___
## bit.arshift()
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).
___
## bit.bit()
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).
___
## bit.set()
Set bits in a number.
####Syntax
`bit.set(value, pos1 [, ... posn ])`
####Parameters
- `value`: the base number.
- `pos1`: position of the first 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).
___
## bit.clear()
Clear bits in a number.
####Syntax
`bit.clear(value, pos1 [, ... posn])`
####Parameters
- `value`: the base number.
- `pos1`: position of the first 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).
___
## bit.isset()
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.
___
## bit.isclear()
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.
___
# crypto Module
The crypto modules provides various functions for working with cryptographic algorithms.
## crypto.hash()
Compute a cryptographic hash of a Lua string.
####Syntax
`hash = crypto.hash(algo, str)`
####Parameters
- `algo`: The hash algorithm to use, case insensitive 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)
####Returns
A binary string containing the message digest. To obtain the textual version (ASCII hex characters), please use `crypto.toHex()`.
####Example
```lua
print(crypto.toHex(crypto.hash("sha1","abc")))
```
___
## crypto.hmac()
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)
####Returns
A binary string containing the HMAC signature. Use `crypto.toHex()` to obtain the textual version.
####Example
```lua
print(crypto.toHex(crypto.hmac("sha1","abc","mysecret")))
```
___
## crypto.mask()
Applies an XOR mask to a Lua string. Note that this is not a proper cryptographic mechanism, but some protocols may use it nevertheless.
####Syntax
masked = crypto.mask (message, mask)
####Parameters
- message: message to mask
- mask = the mask to apply, repeated if shorter than the message
####Returns
The masked message, as a binary string. Use `crypto.toHex()` to get a textual representation of it.
####Example
```lua
print(crypto.toHex(crypto.mask("some message to obscure","X0Y7")))
```
___
## crypto.toHex()
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
####Returns
An ASCII hex string.
####Example
```lua
print(crypto.toHex(crypto.hash("sha1","abc")))
```
___
## crypto.toBase64()
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
```lua
print(crypto.toBase64(crypto.hash("sha1","abc")))
```
___
# file Module
The file module provides access to the file system and its individual files.
The file system is a flat file system, with no notion of directories/folders.
Only one file can be open at any given time.
## file.fsinfo()
Return size information for the file system, in bytes.
####Syntax
`file.fsinfo()`
####Parameters
`nil`
####Returns
- `remaining` (number)
- `used` (number)
- `total` (number)
####Example
```lua
-- get file system info
remaining, used, total=file.fsinfo()
print("\nFile system info:\nTotal : "..total.." Bytes\nUsed : "..used.." Bytes\nRemain: "..remaining.." Bytes\n")
```
```
___
## file.format()
Format the file system. Completely erases any existing file system and writes a new one. Depending on the size of the flash chip in the ESP, this may take several seconds.
####Syntax
`file.format()`
####Parameters
`nil`
####Returns
`nil`
####Example
```lua
file.format()
```
####See also
- `file.remove()`
___
## file.list()
Lists all files in the file system.
####Syntax
`file.list()`
####Parameters
`nil`
####Returns
a lua table which contains the {file name: file size} pairs
####Example
```lua
l = file.list();
for k,v in pairs(l) do
print("name:"..k..", size:"..v)
end
```
___
## file.remove()
Remove a file from the file system. The file must not be currently open.
###Syntax
`file.remove(filename)`
####Parameters
- `filename`: file to remove
####Returns
`nil`
####Example
```lua
-- remove "foo.lua" from file system.
file.remove("foo.lua")
```
####See also
- `file.open()`
___
## file.rename()
Renames a file. If a file is currently open, it will be closed first.
####Syntax
`file.rename(oldname, newname)`
####Parameters
- `oldname`: old file name
- `newname`: new file name
####Returns
`true` on success, `false` on error.
####Example
```lua
-- rename file 'temp.lua' to 'init.lua'.
file.rename("temp.lua","init.lua")
```
___
## file.open()
Opens a file for access, potentially creating it (for write modes).
When done with the file, it must be closed using `file.close()`.
####Syntax
`file.open(filename, mode)`
####Parameters
- `filename`: file to be opened, directories are not supported
- `mode`:
- "r": read mode (the default)<br />
- "w": write mode<br />
- "a": append mode<br />
- "r+": update mode, all previous data is preserved<br />
- "w+": update mode, all previous data is erased<br />
- "a+": append update mode, previous data is preserved, writing is only allowed at the end of file
####Returns
- `nil` if file not opened, or not exists (read modes). true` if file opened ok.
####Example
```lua
-- open 'init.lua', print the first line.
file.open("init.lua", "r")
print(file.readline())
file.close()
```
####See also
- `file.close()`
- `file.readline()`
___
## file.close()
Closes the open file, if any.
####Syntax
`file.close()`
####Parameters
`nil`
####Returns
`nil`
####Example
```lua
-- open 'init.lua', print the first line.
file.open("init.lua", "r")
print(file.readline())
file.close()
```
####See also
- `file.open()`
___
## file.readline()
Read the next line from the open file.
####Syntax
`file.readline()`
####Parameters
`nil`
####Returns
File content in string, line by line, include EOL('\n'). Return `nil` when EOF.
####Example
```lua
-- print the first line of 'init.lua'
file.open("init.lua", "r")
print(file.readline())
file.close()
```
####See also
- `file.open()`
- `file.close()`
- `file.read()`
___
## file.writeline()
Write a string to the open file and append '\n' at the end.
####Syntax
`file.writeline(string)`
####Parameters
- `string`: content to be write to file
####Returns
`true` if write ok, `nil` on error.
####Example
```lua
-- 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.readline()`
___
## file.read()
Read content from the open file.
####Syntax
`file.read([n_or_str])`
####Parameters
- `n_or_str`:
- if nothing passed in, read all byte in file.
- if pass a number n, then read n bytes from file, or EOF is reached.
- if pass a string "str", then read until 'str' or EOF is reached.
####Returns
File content in string, or nil when EOF.
####Example
```lua
-- print the first line of 'init.lua'
file.open("init.lua", "r")
print(file.read('\n'))
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.readline()`
___
## file.write()
Write a string to the open file.
####Syntax
`file.write(string)`
####Parameters
`string`: content to be write to file.
####Returns
`true` if the write is ok, `nil` on error.
####Example
```lua
-- 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()`
___
## file.flush()
Flushes any pending writes to the file system, ensuring no data is lost on a restart. Closing the open file using `file.close()` performs an implicit flush as well.
####Syntax
`file.flush()`
####Parameters
`nil`
####Returns
`nil`
####Example
```lua
-- 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()
-- write 'baz' too
file.write('baz')
file.close()
```
####See also
- `file.close()`
___
## file.seek()
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
If no parameters are given, the function simply returns the current file offset.
####Returns
The resulting file position, or `nil` on error.
####Example
```lua
file.open("init.lua", "r")
-- skip the first 5 bytes of the file
file.seek("set", 5)
print(file.readline())
file.close()
```
####See also
- `file.open()`
___
# gpio Module
This module provides access to the GPIO (General Purpose I/O) subsystem.
All access is based on the I/O index number on the NodeMCU dev kits, not the internal gpio pin. For example, the D0 pin on the dev kit is mapped to the internal GPIO pin 16.
If not using a NodeMCU dev kit, please refer to the below GPIO pin maps for the index<->gpio mapping.
| 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 support. No pwm/i2c/ow support. **
## gpio.mode()
Initialize pin to GPIO mode, set the pin in/out direction, and optional internal pullup.
####Syntax
`gpio.mode(pin, mode [, pullup])`
####Parameters
- `pin`: pin to configure, IO index
- `mode`: one of gpio.OUTPUT or gpio.INPUT, or gpio.INT(interrupt mode)
- `pullup`: gpio.PULLUP or gpio.FLOAT; The default is gpio.FLOAT.
####Returns
`nil`
####Example
```lua
gpio.mode(0, gpio.OUTPUT)
```
####See also
- `gpio.read()`
- `gpio.write()`
___
## gpio.read()
Read digital GPIO pin value.
####Syntax
`gpio.read(pin)`
####Parameters
- `pin`: pin to read, IO index
####Returns
number:0 - low, 1 - high
####Example
```lua
-- read value of gpio 0.
gpio.read(0)
```
####See also
- `gpio.mode()`
___
## gpio.write ()
Set digital GPIO pin value.
####Syntax
`gpio.write(pin, level)`
####Parameters
- `pin`: pin to write, IO index
- `level`: `gpio.HIGH` or `gpio.LOW`
####Returns
`nil`
####Example
```lua
-- 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()`
___
## gpio.trig()
Establish a callback function to run on interrupt for a pin.
There is currently no support for unregistering the callback.
This function is not available if GPIO_INTERRUPT_ENABLE was undefined at compile time.
####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 correspondingly.
- `function(level)`: callback function when triggered. The gpio level is the param. Use previous callback function if undefined here.
####Returns
`nil`
####Example
```lua
-- use pin 1 as the input pulse width counter
pin = 1
pulse1 = 0
du = 0
gpio.mode(pin,gpio.INT)
function pin1cb(level)
du = tmr.now() - pulse1
print(du)
pulse1 = tmr.now()
if level == gpio.HIGH then gpio.trig(pin, "down") else gpio.trig(pin, "up") end
end
gpio.trig(pin, "down", pin1cb)
```
####See also
- `gpio.mode()`
___
## gpio.serout()
Serialize output based on a sequence of delay-times. After each delay, the pin is toggled.
####Syntax
`gpio.serout(pin, start_level, delay_times [, repeat_num])`
####Parameters
- `pin`: pin to use, IO index
- `start_level`: level to start on, either `gpio.HIGH` or `gpio.LOW`
- `delay_times`: an array of delay times between each toggle of the gpio pin.
- `repeat_num`: an optional number of times to run through the sequence.
Note that this function blocks, and as such any use of it must adhere to the SDK guidelines of time spent blocking the stack (10-100ms). Failure to do so may lead to WiFi issues or outright crashes/reboots.
####Returns
`nil`
####Example
```lua
gpio.mode(1,gpio.OUTPUT,gpio.PULLUP)
gpio.serout(1,1,{30,30,60,60,30,30}) -- serial one byte, b10110010
gpio.serout(1,1,{30,70},8) -- serial 30% pwm 10k, lasts 8 cycles
gpio.serout(1,1,{3,7},8) -- serial 30% pwm 100k, lasts 8 cycles
gpio.serout(1,1,{0,0},8) -- serial 50% pwm as fast as possible, lasts 8 cycles
gpio.serout(1,0,{20,10,10,20,10,10,10,100}) -- sim uart one byte 0x5A at about 100kbps
gpio.serout(1,1,{8,18},8) -- serial 30% pwm 38k, lasts 8 cycles
```
___
# node Module
The node module provides access to system-level features such as sleep, restart and various info and IDs.
## node.bootreason()
Returns the boot reason code.
This is the raw code, not the new "reset info" code which was introduced in recent SDKs. Values are:
- 1: power-on
- 2: reset (software?)
- 3: hardware reset via reset pin
- 4: WDT reset (watchdog timeout)
####Syntax
`node.bootreason()`
####Parameters
`nil`
####Returns
number:the boot reason code
####Example
```lua
rsn = node.bootreason()
```
___
## node.restart()
Restarts the chip.
####Syntax
`node.restart()`
####Parameters
`nil`
####Returns
`nil`
####Example
```lua
node.restart();
```
___
## node.dsleep()
Enter deep sleep mode, wake up when timed out.
The maximum sleep time is 4294967295us, ~71 minutes. This is an SDK limitation.
Firmware from before 05 Jan 2016 have a maximum sleeptime of ~35 minutes.
####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.<br />
option=0, init data byte 108 is valuable;<br />
option>0, init data byte 108 is valueless.<br />
More details as follows:<br />
0, RF_CAL or not after deep-sleep wake up, depends on init data byte 108.<br />
1, RF_CAL after deep-sleep wake up, there will belarge current.<br />
2, no RF_CAL after deep-sleep wake up, there will only be small current.<br />
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
```lua
--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)
```
___
## node.info()
Returns 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
```lua
majorVer, minorVer, devVer, chipid, flashid, flashsize, flashmode, flashspeed = node.info()
print("NodeMCU "..majorVer.."."..minorVer.."."..devVer)
```
___
## node.chipid()
Returns the ESP chip ID.
####Syntax
`node.chipid()`
####Parameters
`nil`
####Returns
number:chip ID
####Example
```lua
id = node.chipid();
```
___
## node.flashid()
Returns the flash chip ID.
####Syntax
`node.flashid()`
####Parameters
`nil`
####Returns
number:flash ID
####Example
```lua
flashid = node.flashid();
```
___
## node.heap()
Returns the current available heap size in bytes. Note that due to fragmentation, actual allocations of this size may not be possible.
####Syntax
`node.heap()`
####Parameters
`nil`
####Returns
number: system heap size left in bytes
####Example
```lua
heap_size = node.heap();
```
___
## node.key() --deprecated
Define action to take on button press (on the old devkit 0.9), button connected to GPIO 16.
This function is only available if the firmware was compiled with DEVKIT_VERSION_0_9 defined.
####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, remove the user defined function. Default function: long: change LED blinking rate, short: reset chip
####Returns
`nil`
####Example
```lua
node.key("long", function() print('hello world') end)
```
####See also
- `node.led()`
___
## node.led() --deprecated
Set the on/off time for the LED (on the old devkit 0.9), with the LED connected to GPIO16, multiplexed with `node.key()`.
This function is only available if the firmware was compiled with DEVKIT_VERSION_0_9 defined.
####Syntax
`node.led(low, high)`
####Parameters
- `low`: LED off time, LED keeps on when low=0. Unit: milliseconds, time resolution: 80~100ms<br />
- `high`: LED on time. Unit: milliseconds, time resolution: 80~100ms
####Returns
`nil`
####Example
```lua
-- turn led on forever.
node.led(0)
```
####See also
- `node.key()`
___
## node.input()
Submit a string to the Lua interpreter. Similar to `pcall(loadstring(str))`, but without the single-line limitation.
!!! note "Note:"
This function only has an effect when invoked from a callback. Using it directly on the console **does not work**.
####Syntax
`node.input(str)`
####Parameters
- `str`: Lua chunk
####Returns
`nil`
####Example
```lua
sk:on("receive", function(conn, payload) node.input(payload) end)
```
####See also
- `node.output()`
___
## node.output()
Redirects the Lua interpreter output to a callback function. Optionally also prints it to the serial console.
!!! note "Note:"
Do **not** attempt to `print()` or otherwise induce the Lua interpreter to produce output from within the callback function. Doing so results in infinite recursion, and leads to a watchdog-triggered restart.
####Syntax
`node.output(output_fn, serial_debug)`
####Parameters
- `output_fn(str)`: a function accept every output as str, and can send the output to a socket (or maybe a file).
- `serial_debug`: 1 output also show in serial. 0: no serial output.
####Returns
`nil`
####Example
```lua
function tonet(str)
sk:send(str)
end
node.output(tonet, 1) -- serial also get the lua output.
```
```lua
-- 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
- `node.input()`
___
## node.readvdd33() --deprecated, moved to adc.readvdd33()
####See also
- `adc.readvdd33()`
___
## node.compile()
Compile a Lua text file into Lua bytecode, and save it as .lc file.
####Syntax
`node.compile(filename)`
####Parameters
- `filename`: name of Lua text file
####Returns
`nil`
####Example
```lua
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")
```
___
## node.setcpufreq()
Change the working CPU Frequency.
####Syntax
`node.setcpufreq(speed)`
####Parameters
- `speed`: `node.CPU80MHZ` or `node.CPU160MHZ`
####Returns
number:target CPU Frequency
####Example
```lua
node.setcpufreq(node.CPU80MHZ)
```
___
## node.restore()
Restore system configuration to defaults. Erases all stored WiFi settings, and resets the "esp init data" to the defaults. This function is intended as a last-resort without having to reflash the ESP altogether.
This also uses the SDK function `system_restore()`, which doesn't document precisely what it erases/restores.
####Syntax
`node.restore()`
####Parameters
`nil`
####Returns
`nil`
####Example
```lua
node.restore()
node.restart() -- ensure the restored settings take effect
```
___
## node.stripdebug()
Controls the amount of debug information kept during `node.compile()`, and
allows removal of debug information from already compiled Lua code.
Only recommended for advanced users, the NodeMCU defaults are fine for almost all use cases.
####Syntax
`node.stripdebug([level[, function]])``
####Parameters
- `level`:
- 1: don't discard debug info
- 2: discard Local and Upvalue debug info
- 3: discard Local, Upvalue and line-number debug info
- function: a compiled function to be stripped per setfenv except 0 is not permitted.
If no arguments are given then the current default setting is returned. If function is omitted, this is the default setting for future compiles. The function argument uses the same rules as for `setfenv()`.
#### Returns
If invoked without arguments, returns the current level settings. Otherwise, `nil` is returned.
####Example
```lua
node.stripdebug(3)
node.compile('bigstuff.lua')
```
####See also
- `node.compile()`
___
# 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<sup>-n</sup> multiplier. This allows for high fidelity even when working with very small values. The effective range is thus 1E<sup>-7</sup> to 65535.
- Sensor names are limited to a maximum of 4 characters.
!!! note 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
- rtcmem module
- rtctime module
## rtcfifo.prepare()
Initializes the rtcfifo module for use.
Calling `rtcfifo.prepare()` unconditionally re-initializes the storage - any samples stored are discarded.
####Syntax
`rtcfifo.prepare([table])`
####Parameters
This function takes an optional configuration table as an argument. 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.
####Returns
`nil`
####Example
```lua
rtcfifo.prepare() -- Initialize with default values
```
```lua
rtcfifo.prepare({storage_begin=21, storage_end=128}) -- Use RTC slots 19 and up for variable storage
```
####See also
- `rtcfifo.ready()`
___
## rtcfifo.ready()
Returns non-zero if the rtcfifo has been prepared and is ready for use, zero if not.
####Syntax:
`rtcfifo.ready()`
####Parameters
`nil`
####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
```
####See also
- `rtcfifo.prepare()`
___
## rtcfifo.put()
Puts a sample into the rtcfifo.
If the rtcfifo has not been prepared, this function does nothing.
####Syntax
`rtcfifo.put(timestamp, value, neg_e, name)`
####Parameters
- `timestamp`: Timestamp in seconds. The timestamp would typically come from `rtctime.get()`.
- `value`: The value to store.
- `neg_e`: The effective value stored is `valueE<sup>neg_e</sup>`.
- `name`: Name of the sensor. 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.
####Returns
`nil`
####Example
```lua
local sample = ... -- Obtain a sample value from somewhere
rtcfifo.put(rtctime.get(), sample, 0, "foo") -- Store sample with no scaling, under the name "foo"
```
___
## rtcfifo.peek()
Reads a sample from the rtcfifo. An offset into the rtcfifo may be specified, but by default it reads the first sample (offset 0).
####Syntax:
`rtcfifo.peek([offset])`
####Parameters
- `offset`: Peek at sample at position `offset` in the fifo. This is a relative offset, from the current head. Zero-based. Default value is 0.
####Returns
The values returned match the input arguments used to `rtcfifo.put()`.
- `timestamp`: Timestamp in seconds.
- `value`: The value.
- `neg_e`: Scaling factor.
- `name`: The sensor name.
If no sample is available (at the specified offset), nothing is returned.
####Example
```lua
local timestamp, value, neg_e, name = rtcfifo.peek()
```
___
## rtcfifo.pop()
Reads the first sample from the rtcfifo, and removes it from there.
####Syntax:
`rtcfifo.pop()`
####Parameters
`nil`
####Returns
The values returned match the input arguments used to `rtcfifo.put()`.
- `timestamp`: Timestamp in seconds.
- `value`: The value.
- `neg_e`: Scaling factor.
- `name`: The sensor name.
####Example
```lua
while rtcfifo.count() > 0 do
local timestamp, value, neg_e, name = rtcfifo.pop()
-- do something with the sample, e.g. upload to somewhere
end
```
___
## rtcfifo.dsleep_until_sample()
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)`
####Parameter
- minsleep_us: minimum sleep time, in microseconds.
####Example
```lua
rtcfifo.dsleep_until_sample(0) -- deep sleep until it's time to take the next sample
```
####See also
- `rtctime.dsleep_aligned()`
___
# rtcmem Module
The rtcmem module provides basic access to the RTC (Real Time Clock) memory.
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
- rtctime module
- rtcfifo module
## rtcmem.read32()
Reads one or more 32bit values from RTC user memory.
####Syntax
`rtcmem.read32(idx [, num])`
####Parameters
- `idx`: The index to start reading from. Zero-based.
- `num`: Number of slots to read (default 1).
####Returns
The value(s) read from RTC user memory.
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
```lua
val = rtcmem.read32(0) -- Read the value in slot 0
val1, val2 = rtcmem.read32(42, 2) -- Read the values in slots 42 and 43
```
####See also
- `rtcmem.write32()`
___
## rtcmem.write32()
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`: Index to start writing to. Auto-increments if multiple values are given. Zero-based.
- `val`: The (32bit) value to store.
- `val2...`: Additional values to store. Optional.
####Returns
`nil`
####Example
```lua
rtcmem.write32(0, 53) -- Store the value 53 in slot 0
rtcmem.write32(42, 2, 5, 7) -- Store the values 2, 5 and 7 into slots 42, 43 and 44, respectively.
```
####See also
- `rtcmem.read32()`
___
# 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.
!!! note 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
- rtcmem module
- sntp module
## rtctime.set()
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.
####Syntax
`rtctime.set(seconds, microseconds)`
####Parameters
- `seconds`: the seconds part, counted from the Unix epoch.
- `microseconds`: the microseconds part
####Returns
`nil`
####Example
```lua
rtctime.set(1436430589, 0) -- Set time to 2015 July 9, 18:29:49
```
####See also
- `sntp.sync()`
___
## rtctime.get()
Returns the current time. If current time is not available, zero is returned.
####Syntax
`rtctime.get()`
####Parameters
`nil`
####Returns
A two-value timestamp containing:
- `sec`: seconds since the Unix epoch
- `usec`: the microseconds part
####Example
```lua
sec, usec = rtctime.get()
```
####See also
- `rtctime.set()`
___
## rtctime.dsleep()
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
- `microseconds`: The number of microseconds to sleep for. Maxmium value is 4294967295us, or ~71 minutes.
- `option`: The sleep option. See `node.dsleep()` for specifics.
####Returns
This function does not return.
####Example
```lua
rtctime.dsleep(60*1000000) -- sleep for a minute
```
```lua
rtctime.dsleep(5000000, 4) -- sleep for 5 seconds, do not start RF on wakeup
```
___
## rtctime.dsleep_aligned()
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_us, minsleep_us [, option])`
####Parameters
- `aligned_us`: specifies the boundary interval in microseconds.
- `minsleep_us`: 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.
- `option`: as with `dsleep()`, the `option` sets the sleep option, if specified.
####Example
```lua
rtctime.dsleep_aligned(5*1000000, 3*1000000) -- sleep at least 3 seconds, then wake up on the next 5-second boundary
```
___
# 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
- rtctime module
## sntp.sync()
Attempts to obtain time synchronization.
####Syntax
`sntp.sync([server_ip], [callback], [errcallback])`
####Parameters
- `server_ip`: 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.
- `callback`: 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.
- `errcallback`: 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
`nil`
####Example
```lua
-- Best effort, use the last known NTP server (or the NTP "anycast" address 224.0.1.1 initially)
sntp.sync()
```
```lua
-- 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
)
```
####See also
- `rtctime.set()`
___
# uart Module
The uart module allows configuration of and communication over the uart serial port.
## uart.setup()
(Re-)configures the communication parameters of the UART.
####Syntax
`uart.setup(id, baud, databits, parity, stopbits, echo)`
####Parameters
- `id`: Always zero, only one uart supported.
- `baud`: One of 300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 74880, 115200, 230400, 460800, 921600, 1843200, 2686400.
- `databits`: One of 5, 6, 7, 8.
- `parity`: uart.PARITY_NONE, uart.PARITY_ODD, or uart.PARITY_EVEN.
- `stopbits`: uart.STOPBITS_1, uart.STOPBITS_1_5, or uart.STOPBITS_2.
- `echo`: if zero, disable echo, otherwise enable echo.
####Returns
number:configured baud rate
####Example
```lua
-- configure for 9600, 8N1, with echo
uart.setup(0, 9600, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1)
```
___
## uart.write()
Write string or byte to the uart.
####Syntax
uart.write(id, data1 [, data2, ...])
####Parameters
- `id`: Always zero, only one uart supported.
- `data1`...: String or byte to send via uart.
####Returns
`nil`
####Example
```lua
uart.write(0, "Hello, world\n")
```
___
## uart.on()
Sets the callback function to handle uart events.
Currently only the "data" event is supported.
####Syntax
`uart.on(method, [number/end_char], [function], [run_input])`
####Parameters
- `method`: "data", data has been received on the 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; If 0, input from uart will not go into Lua interpreter, can accept binary data. If 1, input from uart will go into Lua interpreter, and run.
To unregister the callback, provide only the "data" parameter.
####Returns
`nil`
####Example
```lua
-- when 4 chars is received.
uart.on("data", 4,
function(data)
print("receive from uart:", data)
if data=="quit" then
uart.on("data") -- unregister callback function
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") -- unregister callback function
end
end, 0)
```
___
# Getting started
## Obtain the firmware
[Build the firmware](build.html) or download it from ?
## Flash the firmware
There are a number of tools for flashing the firmware.
The [issues list on GitHub](https://github.com/nodemcu/nodemcu-firmware/issues) is **not** the right place to ask for help. Use it to report bugs and to place feature requests. "how do I ..." or a "I can't get this to work ..." should be directed to StackOverflow or esp8266.com.
## StackOverflow
StackOverflow is the perfect place to ask coding questions. Use one or several of the following tags: [esp8266](http://stackoverflow.com/tags/esp8266), [nodemcu](http://stackoverflow.com/tags/nodemcu) or [Lua](http://stackoverflow.com/tags/lua).
## esp8266.com Forums
esp8266.com has a few [NodeMCU specific forums](http://www.esp8266.com/viewforum.php?f=17) where a number of our active community members tend to hang out.
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment