Merge branch 'dev-rtd' into newdocs
This commit is contained in:
commit
b2f9a5637a
|
@ -0,0 +1,14 @@
|
||||||
|
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;
|
||||||
|
}
|
|
@ -0,0 +1,6 @@
|
||||||
|
# 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).
|
||||||
|
|
|
@ -0,0 +1,10 @@
|
||||||
|
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.
|
|
@ -0,0 +1,357 @@
|
||||||
|
# FAQ
|
||||||
|
|
||||||
|
**# # # Work in Progress # # #**
|
||||||
|
|
||||||
|
*I have started a thread on the ESP8266 forum, [Discussions on my NodeMCU Lua unofficial FAQ](http://www.esp8266.com/viewtopic.php?f=24&t=3311&p=18770). Please use this to discuss any issues that you have with this FAQ; any areas where you feel that the explanation is unclear or needs further expansion; or any or Qs that you feel need answering and would help others if they were included here. Thank-you. Terry Ellison*
|
||||||
|
|
||||||
|
## What is this FAQ for?
|
||||||
|
|
||||||
|
This FAQ does not aim to help you to learn to program or even how to program in Lua. There are plenty of resources on the Internet for this, some of which are listed in [[#Where to start|Where to start]]. What this FAQ does is to answer some of the common questions that a competent Lua developer would ask in learning how to develop Lua applications for the ESP8266 based boards running the [[http://NodeMCU.com/index_en.html|NodeMCU]] firmware.
|
||||||
|
|
||||||
|
## Lua Language
|
||||||
|
|
||||||
|
### Where to start
|
||||||
|
|
||||||
|
The NodeMCU firmware implements Lua 5.1 over the Espressif SDK for its ESP8266 SoC and the IoT modules based on this.
|
||||||
|
|
||||||
|
* The official lua.org **[[http://www.lua.org/manual/5.1/manual.html|Lua Language specification]]** gives a terse but complete language specification.
|
||||||
|
* Its [[http://www.lua.org/faq.html|FAQ]] provides information on Lua availability and licensing issues.
|
||||||
|
* The **[[http://www.luafaq.org/|unofficial Lua FAQ]]** provides a lot of useful Q and A content, and is extremely useful for those learning Lua as a second language.
|
||||||
|
* The [[http://lua-users.org/wiki/|Lua User's Wiki]] gives useful example source and relevant discussion. In particular, its [[http://lua-users.org/wiki/Learning|Lua Learning Lua]] section is a good place to start learning Lua.
|
||||||
|
* The best book to learn Lua is *Programming in Lua* by Roberto Ierusalimschy, one of the creators of Lua. It's first edition is available free [[http://www.lua.org/pil/contents.html|online]] . The second edition was aimed at Lua 5.1, but is out of print. The third edition is still in print and available in paperback. It contains a lot more material and clearly identifies Lua 5.1 vs Lua 5.2 differences. **This third edition is widely available for purchase and probably the best value for money**. References of the format [PiL **n.m**] refer to section **n.m** in this edition.
|
||||||
|
* The Espressif ESP8266 architecture is closed source, but the Espressif SDK itself is continually being updated so the best way to get the documentation for this is to [[https://www.google.co.uk/search?q=Espressif+IoT+SDK+Programming+Guide|google Espressif IoT SDK Programming Guide]] or to look at the Espressif [[http://bbs.espressif.com/viewforum.php?f=5|downloads forum]] .
|
||||||
|
* The **[[http://www.NodeMCU.com/docs/|NodeMCU documentation]]** is available online. However, please remember that the development team are based in China, and English is a second language, so the documentation needs expanding and be could improved with technical proofing.
|
||||||
|
* As with all Open Source projects the source for the NodeMCU firmware is openly available on the [[https://github.com/NodeMCU/NodeMCU-firmware|GitHub NodeMCU-firmware]] repository.
|
||||||
|
|
||||||
|
### How is NodeMCU Lua different to standard Lua?
|
||||||
|
|
||||||
|
Whilst the Lua standard distribution includes a host stand-alone Lua interpreter, Lua itself is primarily an *extension language* that makes no assumptions about a "main" program: Lua works embedded in a host application to provide a powerful, light-weight scripting language for use within the application. This host application can then invoke functions to execute a piece of Lua code, can write and read Lua variables, and can register C functions to be called by Lua code. Through the use of C functions, Lua can be augmented to cope with a wide range of different domains, thus creating customized programming languages sharing a syntactical framework.
|
||||||
|
|
||||||
|
The ESP8266 was designed and is fabricated in China by [[http://espressif.com/new-sdk-release/|Espressif Systems]]. Espressif have also developed and released a companion software development kit (SDK) to enable developers to build practical [[wp>Internet of Things|IoT]] applications for the ESP8266. The SDK is made freely available to developers in the form of binary libraries and SDK documentation. However this is in a *closed format*, with no developer access to the source files, so ESP8266 applications *must* rely solely on the SDK API (and the somewhat Spartan SDK API documentation).
|
||||||
|
|
||||||
|
The NodeMCU Lua firmware is an ESP8266 application and must therefore be layered over the ESP8266 SDK. However, the hooks and features of Lua enable it to be seamlessly integrated without loosing any of the standard Lua language features. The firmware has replaced some standard Lua modules that don't align well with the SDK structure with ESP8266-specific versions. For example, the standard `io` and `os` libraries don't work, but have been largely replaced by the NodeMCU `node` and `file` libraries. The `debug` and `math` libraries have also been omitted to reduce the runtime footprint.
|
||||||
|
|
||||||
|
NodeMCU Lua is based on [[http://www.eluaproject.net/overview|eLua]], a fully featured implementation of Lua 5.1 that has been optimized for embedded system development and execution to provide a scripting framework that can be used to deliver useful applications within the limited RAM and Flash memory resources of embedded processors such as the ESP8266. One of the main changes introduced in the eLua fork is to use read-only tables and constants wherever practical for library modules. On a typical build this approach reduces the RAM footprint by some 20-25KB and this makes a Lua implementation for the ESP8266 feasible. This technique is called LTR and this is documented in detail in an eLua technical paper: [[http://www.eluaproject.net/doc/master/en_arch_ltr.html|Lua Tiny RAM]].
|
||||||
|
|
||||||
|
The mains impacts of the ESP8266 SDK and together with its hardware resource limitations are not in the Lua language implementation itself, but in how *application programmers must approach developing and structuring their applications*. As discussed in detail below, the SDK is non-preemptive and event driven. Tasks can be associated with given events by using the SDK API to registering callback functions to the corresponding events. Events are queued internally within the SDK, and it then calls the associated tasks one at a time, with each task returning control to the SDK on completion. *The SDK states that if any tasks run for more than 10 mSec, then services such as Wifi can fail.*
|
||||||
|
|
||||||
|
The NodeMCU libraries act as C wrappers around registered Lua callback functions to enable these to be used as SDK tasks. ***You must therefore use an [[wp>Event-driven programming|Event-driven programming]] style in writing your ESP8266 Lua programs***. Most programmers are used to writing in a procedural style where there is a clear single flow of execution, and the program interfaces to operating system services by a set of synchronous API calls to do network I/O, etc. Whilst the logic of each individual task is procedural, this is not how you code up ESP8266 applications.
|
||||||
|
|
||||||
|
## ESP8266 Specifics
|
||||||
|
|
||||||
|
### How is coding for the ESP8266 the same as standard Lua?
|
||||||
|
|
||||||
|
* This is a fully featured Lua 5.1 implementation so all standard Lua language constructs and data types work.
|
||||||
|
* The main standard Lua libraries -- `core`, `coroutine`, `string` and `table` are implemented.
|
||||||
|
|
||||||
|
### How is coding for the ESP8266 different to standard Lua?
|
||||||
|
|
||||||
|
* The ESP8266 use onchip RAM and offchip Flash memory connected using a dedicated SPI interface. Both of these are *very* limited (when compared to systems than most application programmer use). The SDK and the Lua firmware already use the majority of this resource: the later build versions keep adding useful functionality, and unfortunately at an increased RAM and Flash cost, so depending on the build version and the number of modules installed the runtime can have as little as 17KB RAM and 40KB Flash available at an application level. This Flash memory is formatted an made available as a **SPI Flash File System (SPIFFS)** through the `file` library.
|
||||||
|
* However, if you choose to use a custom build, for example one which uses integer arithmetic instead of floating point, and which omits libraries that aren't needed for your application, then this can help a lot doubling these available resources. (See Marcel Stör's excellent [[http://frightanic.com/NodeMCU-custom-build/|custom build tool]] that he discusses in [[http://www.esp8266.com/viewtopic.php?f=23&t=3001|this forum topic]]). Even so, those developers who are used to dealing in MB or GB of RAM and file systems can easily run out of these resources. Some of the techniques discussed below can go a long way to mitigate this issue.
|
||||||
|
* Current versions of the ESP8266 run the SDK over the native hardware so there is no underlying operating system to capture errors and to provide graceful failure modes, so system or application errors can easily "PANIC" the system causing it to reboot. Error handling has been kept simple to save on the limited code space, and this exacerbates this tendency. Running out of a system resource such as RAM will invariably cause a messy failure and system reboot.
|
||||||
|
* There is currently no `debug` library support. So you have to use 1980s-style "binary-chop" to locate errors and use print statement diagnostics though the systems UART interface. (This omission was largely because of the Flash memory footprint of this library, but there is no reason in principle why we couldn't make this library available in the near future as an custom build option).
|
||||||
|
* The LTR implementation means that you can't easily extend standard libraries as you can in normal Lua, so for example an attempt to define `function table.pack()` will cause a runtime error because you can't write to the global `table`. (Yes, there are standard sand-boxing techniques to achieve the same effect by using metatable based inheritance, but if you try to use this type of approach within a real application, then you will find that you run out of RAM before you implement anything useful.)
|
||||||
|
* There are standard libraries to provide access to the various hardware options supported by the hardware: WiFi, GPIO, One-wire, I²C, SPI, ADC, PWM, UART, etc.
|
||||||
|
* The runtime system runs in interactive-mode. In this mode it first executes any `init.lua` script. It then "listens" to the serial port for input Lua chunks, and executes them once syntactically complete. There is no `luac` or batch support, although automated embedded processing is normally achieved by setting up the necessary event triggers in the `init.lua` script.
|
||||||
|
* The various libraries (`net`, `tmr`, `wifi`, etc.) use the SDK callback mechanism to bind Lua processing to individual events (for example a timer alarm firing). Developers should make full use of these events to keep Lua execution sequences short. *If any individual task takes too long to execute then other queued tasks can time-out and bad things start to happen.*
|
||||||
|
* Non-Lua processing (e.g. network functions) will usually only take place once the current Lua chunk has completed execution. So any network calls should be viewed at an asynchronous request. A common coding mistake is to assume that they are synchronous, that is if two `socket:send()` are on consecutive lines in a Lua programme, then the first has completed by the time the second is executed. This is wrong. Each `socket:send()` request simply queues the send operation for dispatch. Neither will start to process until the Lua code has return to is calling C function. Stacking up such requests in a single Lua task function burns scarce RAM and can trigger a PANIC. This true for timer, network, and other callbacks. It is even the case for actions such as requesting a system restart, as can be seen by the following example:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
node.restart(); for i = 1, 20 do print("not quite yet -- ",i); end
|
||||||
|
```
|
||||||
|
* You therefore *have* to implement ESP8266 Lua applications using an event driven approach. You have to understand which SDK API requests schedule asynchronous processing, and which define event actions through Lua callbacks. Yes, such an event-driven approach makes it difficult to develop procedurally structured applications, but it is well suited to developing the sorts of application that you will typically want to implement on an [[wp>Internet of Things|IoT]] device.
|
||||||
|
|
||||||
|
### So how does the SDK event / tasking system work in Lua?
|
||||||
|
|
||||||
|
* The SDK employs an event-driven and task-oriented architecture for programming at an applications level.
|
||||||
|
* The SDK uses a startup hook `void user_init(void)`, defined by convention in the C module `user_main.c`, which it invokes on boot. The `user_init()` function can be used to do any initialisation required and to call the necessary timer alarms or other SDK API calls to bind and callback routines to implement the tasks needed in response to any system events.
|
||||||
|
* The API provides a set of functions for declaring application functions (written in C) as callbacks to associate application tasks with specific hardware and timer events. These are non-preemptive at an applications level.
|
||||||
|
* Whilst the SDK provides a number of interrupt driven device drivers, the hardware architecture severely limits the memory available for these drivers, so writing new device drivers is not a viable options for most developers
|
||||||
|
* The SDK interfaces internally with hardware and device drivers to queue pending events.
|
||||||
|
* The registered callback routines are invoked sequentially with the associated C task running to completion uninterrupted.
|
||||||
|
* In the case of Lua, these C tasks are typically functions within the Lua runtime library code and these typically act as C wrappers around the corresponding developer-provided Lua callback functions. An example here is the Lua `tmr.alarm(id, interval, repeat, callback)` function. The calls a function in the `tmr` library which registers a C function for this alarm using the SDK, and when this C function is called it then invokes the Lua callback.
|
||||||
|
|
||||||
|
The NodeMCU firmware simply mirrors this structure at a Lua scripting level:
|
||||||
|
* A startup module `init.lua` is invoked on boot. This function module can be used to do any initialisation required and to call the necessary timer alarms or libary calls to bind and callback routines to implement the tasks needed in response to any system events.
|
||||||
|
* The Lua libraries provide a set of functions for declaring application functions (written in Lua) as callbacks (which are stored in the [[#So how is the Lua Registry used and why is this important?|Lua registry]]) to associate application tasks with specific hardware and timer events. These are non-preemptive at an applications level.
|
||||||
|
* The Lua libraries work in consort with the SDK to queue pending events and invoke any registered Lua callback routines, which then run to completion uninterrupted.
|
||||||
|
* Excessively long-running Lua functions can therefore cause other system functions and services to timeout, or allocate memory to buffer queued data, which can then trigger either the watchdog timer or memory exhaustion, both of which will ultimately cause the system to reboot.
|
||||||
|
* By default, the Lua runtime also 'listens' to UART 0, the serial port, in interactive mode and will execute any Lua commands input through this serial port.
|
||||||
|
|
||||||
|
This event-driven approach is very different to a conventional procedural implementation of Lua.
|
||||||
|
|
||||||
|
Consider a simple telnet example given in `examples/fragment.lua`:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
s=net.createServer(net.TCP)
|
||||||
|
s:listen(23,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)
|
||||||
|
c:on("receive",function(c,l) node.input(l) end)
|
||||||
|
c:on("disconnection",function(c)
|
||||||
|
con_std = nil
|
||||||
|
node.output(nil)
|
||||||
|
end)
|
||||||
|
end)
|
||||||
|
```
|
||||||
|
|
||||||
|
This example defines five Lua functions:
|
||||||
|
|
||||||
|
| Function | Defined in | Parameters | Callback? |
|
||||||
|
|-----------|------------|------------|-----------|
|
||||||
|
| Main | Outer module | ... (Not used) | |
|
||||||
|
| Connection listener | Main | c (connection socket) | |
|
||||||
|
| s_output | Connection listener | str | Yes |
|
||||||
|
| On Receive| Connection listener | c, l (socket, input) | Yes |
|
||||||
|
| On Disconnect | Connection listener | c (socket) | Yes |
|
||||||
|
|
||||||
|
`s`, `con_std` and `s_output` are global, and no [[#Why is it importance to understand how upvalues are implemented when programming for the ESP8266?|upvalues]] are used. There is no "correct" order to define these in, but we could reorder this code for clarity (though doing this adds a few extra globals) and define these functions separately one another. However, let us consider how this is executed:
|
||||||
|
|
||||||
|
* The outer module is compiled including the four internal functions.
|
||||||
|
* `Main` is then assigning the created `net.createServer()` to the global `s`. The `connection listener` closure is created and bound to a temporary variable which is then passed to the `socket.listen()` as an argument. The routine then exits returning control to the firmware.
|
||||||
|
* When another computer connects to port 23, the listener handler retrieves the reference to then connection listener and calls it with the socket parameter. This function then binds the s_output closure to the global `s_output`, and registers this function with the `node.output` hook. Likewise the `on receive` and `on disconnection` are bound to temporary variables which are passed to the respective on handlers. We now have four Lua function registered in the Lua runtime libraries associated with four events. This routine then exits returning control to the firmware.
|
||||||
|
* When a record is received, the on receive handler within the net library retrieves the reference to the `on receive` Lua function and calls it passing it the record. This routine then passes this to the `node.input()` and exits returning control to the firmware.
|
||||||
|
* The `node.input` handler polls on an 80 mSec timer alarm. If a compete Lua chunk is available (either via the serial port or node input function), then it executes it and any output is then passed to the `note.output` handler. which calls `s_output` function. Any pending sends are then processed.
|
||||||
|
* This cycle repeats until the other computer disconnects, and `net` library disconnection handler then calls the Lua `on disconnect` handler. This Lua routine dereferences the connected socket and closes the `node.output` hook and exits returning control to the disconnect handler which garbage collects any associated sockets and registered on handlers.
|
||||||
|
|
||||||
|
Whilst this is all going on, The SDK can (and often will) schedule other event tasks in between these Lua executions (e.g. to do the actual TCP stack processing). The longest individual Lua execution in this example is only 18 bytecode instructions (in the main routine).
|
||||||
|
|
||||||
|
Understanding how the system executes your code can help you structure it better and improve memory usage. Each event task is established by a callback in an API call in an earlier task.
|
||||||
|
|
||||||
|
### So what Lua library functions enable the registration of Lua callbacks?
|
||||||
|
|
||||||
|
SDK Callbacks include:
|
||||||
|
|
||||||
|
| Lua Module | Functions which define or remove callbacks |
|
||||||
|
|------------|--------------------------------------------|
|
||||||
|
| tmr | `alarm(id, interval, repeat, function())` |
|
||||||
|
| node | `key(type, function())`, `output(function(str), serial_debug)` |
|
||||||
|
| wifi | `startsmart(chan, function())`, `sta.getap(function(table))` |
|
||||||
|
| net.server | `sk:listen(port,[ip],function(socket))` |
|
||||||
|
| net | `sk:on(event, function(socket, [, data]))`, `sk:send(string, function(sent))`, `sk:dns(domain, function(socket,ip))` |
|
||||||
|
| gpio | `trig(pin, type, function(level))` |
|
||||||
|
| mqqt | `client:m:on(event, function(conn[, topic, data])` |
|
||||||
|
| uart | `uart.on(event, cnt, [function(data)], [run_input])` |
|
||||||
|
|
||||||
|
|
||||||
|
### So how is context passed between Lua event tasks?
|
||||||
|
|
||||||
|
* It is important to understand that any event callback task is associated with a single Lua function. This function is executed from the relevant NodeMCU library C code using a `lua_call()`. Even system initialisation which executes the `dofile("init.lua")` can be treated as a special case of this. Each function can invoke other functions and so on, but it must ultimate return control to the C library code.
|
||||||
|
* By their very nature Lua `local` variables only exist within the context of an executing Lua function, and so all locals are destroyed between these `lua_call()` actions. *No locals are retained across events*.
|
||||||
|
* So context can only be passed between event routines by one of three mechanisms:
|
||||||
|
* **Globals** are by nature globally accessible. Any global will persist until explicitly dereference by reassigning `nil` to it. Globals can be readily enumerated by a `for k,v in pairs(_G) do` so their use is transparent.
|
||||||
|
* The **File system** is a special case of persistent global, so there is no reason in principle why it can't be used to pass context. However the ESP8266 file system uses flash memory and this has a limited write cycle lifetime, so it is best to avoid using the file system to store frequently changing content except as a mechanism of last resort.
|
||||||
|
* **Upvalues**. When a function is declared within an outer function, all of the local variables in the outer scope are available to the inner function. Since all functions are stored by reference the scope of the inner function might outlast the scope of the outer function, and the Lua runtime system ensures that any such references persist for the life of any functions that reference it. This standard feature of Lua is known as *closure* and is described in [Pil 6]. Such values are often called *upvalues*. Functions which are global or [[#So how is the Lua Registry used and why is this important?|registered]] callbacks will persist between event routines, and hence any upvalues referenced by them can be used for passing context.
|
||||||
|
|
||||||
|
### So how is the Lua Registry used and why is this important?
|
||||||
|
|
||||||
|
So all Lua callbacks are called by C wrapper functions that are themselves callback activated by the SDK as a result of a given event. Such C wrapper functions themselves frequently need to store state for passing between calls or to other wrapper C functions. The Lua registry is simply another Lua table which is used for this purpose, except that it is hidden from direct Lua access. Any content that needs to be saved is created with a unique key. Using a standard Lua table enables standard garbage collection algorithms to operate on its content.
|
||||||
|
|
||||||
|
Note that we have identified a number of cases where library code does not correctly clean up Registry content when closing out an action, leading to memory leaks.
|
||||||
|
|
||||||
|
### Why is it importance to understand how upvalues are implemented when programming for the ESP8266?
|
||||||
|
|
||||||
|
Routines directly or indirectly referenced in the globals table, **_G**, or in the Lua Registry may use upvalues. The number of upvalues associated with a given routine is determined by the compiler and a vector is allocated when the closure is bound to hold these references. Each upvalues is classed as open or closed. All upvalues are initially open which means that the upvalue references back to the outer functions's register set. However, upvalues must be able to outlive the scope of the outer routine where they are declared as a local variable. The runtime VM does this by adding extra checks when executing a function return to scan any defined closures within its scope for back references and allocate memory to hold the upvalue and points the upvalue's reference to this. This is known as a closed upvalue.
|
||||||
|
|
||||||
|
This processing is a mature part of the Lua 5.x runtime system, and for normal Lua applications development this "behind-the-scenes" magic ensures that upvalues just work as any programmer might expect. Sufficient garbage collector metadata is also stored so that these hidden values will be garbage collected correctly *when properly dereferenced*. However allocating these internal structures is quite expensive in terms of memory, and this hidden overhead is hard to track or to understand. If you are developing a Lua application for a PC where the working RAM for an application is measured in MB, then this isn't really an issue. However, if you are developing an application for the ESP8266 where you might have 20 KB for your program and data, this could prove a killer.
|
||||||
|
|
||||||
|
One further complication is that some library functions don't correctly dereference expired callback references and as a result their upvalues may not be correctly garbage collected (though we are tracking this down and hopefully removing this issue). This will all be manifested as a memory leak. So using upvalues can cause more frequent and difficult to diagnose PANICs during testing. So my general recommendation is still to stick to globals for this specific usecase of passing context between event callbacks, and `nil` them when you have done with them.
|
||||||
|
|
||||||
|
### Can I encapsulate actions such as sending an email in a Lua function?
|
||||||
|
|
||||||
|
Think about the implications of these last few answers.
|
||||||
|
* An action such as composing and sending an email involves a message dialogue with a mail server over TCP. This in turn requires calling multiple API calls to the SDK and your Lua code must return control to the C calling library for this to be scheduled, otherwise these requests will just queue up, you'll run out of RAM and your application will PANIC.
|
||||||
|
* Hence it is simply ***impossible*** to write a Lua module so that you can do something like:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
-- prepare message
|
||||||
|
status = mail.send(to, subject, body)
|
||||||
|
-- move on to next phase of processing.
|
||||||
|
```
|
||||||
|
* But you could code up a event-driven task to do this and pass it a callback to be executed on completion of the mail send, something along the lines of the following. Note that since this involves a lot of asynchronous processing and which therefore won't take place until you've returned control to the calling library C code, you will typically execute this as the last step in a function and therefore this is best done as a tailcall [PiL 6.3].
|
||||||
|
|
||||||
|
```lua
|
||||||
|
-- prepare message
|
||||||
|
local ms = require("mail_sender")
|
||||||
|
return ms.send(to, subject, body, function(status) loadfile("process_next.lua")(status) end)
|
||||||
|
```
|
||||||
|
* Building an application on the ESP8266 is a bit like threading pearls onto a necklace. Each pearl is an event task which must be small enough to run within its RAM resources and the string is the variable context that links the pearls together.
|
||||||
|
|
||||||
|
### When and why should I avoid using tmr.delay()?
|
||||||
|
|
||||||
|
If you are used coding in a procedural paradigm then it is understandable that you consider using `tmr.delay()` to time sequence your application. However as discussed in the previous section, with NodeMCU Lua you are coding in an event-driven paradigm.
|
||||||
|
|
||||||
|
If you look at the `app/modules/tmr.c` code for this function, then you will see that it executes a low level `ets_delay_us(delay)`. This function isn't part of the NodeMCU code or the SDK; it's actually part of the xtensa-lx106 boot ROM, and is a simple timing loop which polls against the internal CPU clock. It does this with interrupts disabled, because if they are enabled then there is no guarantee that the delay will be as requested.
|
||||||
|
|
||||||
|
`tmr.delay()` is really intended to be used where you need to have more precise timing control on an external hardware I/O (e.g. lifting a GPIO pin high for 20 μSec). It will achieve no functional purpose in pretty much every other usecase, as any other system code-based activity will be blocked from execution; at worst it will break your application and create hard-to-diagnose timeout errors.
|
||||||
|
|
||||||
|
The latest SDK includes a caution that if any (callback) task runs for more than 10 mSec, then the Wifi and TCP stacks might fail, so if you want a delay of more than 8 mSec or so, then *using `tmr.delay()` is the wrong approach*. You should be using a timer alarm or another library callback, to allow the other processing to take place. As the NodeMCU documentation correctly advises (translating Chinese English into English): *`tmr.delay()` will make the CPU work in non-interrupt mode, so other instructions and interrupts will be blocked. Take care in using this function.*
|
||||||
|
|
||||||
|
|
||||||
|
### How do I avoid a PANIC loop in init.lua?
|
||||||
|
|
||||||
|
Most of us have fallen into the trap of creating an `init.lua` that has a bug in it, which then causes the system to reboot and hence gets stuck in a reboot loop. If you haven't then you probably will do so at least once.
|
||||||
|
* When this happens, the only robust solution is to reflash the firmware.
|
||||||
|
* The simplest way to avoid having to do this is to keep the `init.lua` as simple as possible -- say configure the wifi and then start your app using a one-time `tmr.alarm()` after a 2-3 sec delay. This delay is long enough to issue a `file.remove("init.lua")` through the serial port and recover control that way.
|
||||||
|
* Also it is always best to test any new `init.lua` by creating it as `init_test.lua`, say, and manually issuing a `dofile("init_test.lua")` through the serial port, and then only rename it when you are certain it is working as you require.
|
||||||
|
|
||||||
|
## Techniques for Reducing RAM and SPIFFS footprint
|
||||||
|
|
||||||
|
### How do I minimise the footprint of an application?
|
||||||
|
|
||||||
|
* Perhaps the simplest aspect of reducing the footprint of an application is to get its scope correct. The ESP8266 is an IoT device and not a general purpose system. It is typically used to attach real-world monitors, controls, etc. to an intranet and is therefore designed to implement functions that have limited scope. We commonly come across developers who are trying to treat the ESP8266 as a general purpose device and can't understand why their application can't run.
|
||||||
|
* The simplest and safest way to use IoT devices is to control them through a dedicated general purpose system on the same network. This could be a low cost system such as a [[https://www.raspberrypi.org/|RaspberryPi (RPi)]] server, running your custom code or an open source [[wp>home automation|home automation (HA)]] application. Such systems have orders of magnitude more capacity than the ESP8266, for example the RPi has 2GB RAM and its SD card can be up to 32GB in capacity, and it can support the full range of USB-attached disk drives and other devices. It also runs a fully featured Linux OS, and has a rich selection of applications pre configured for it. There are plenty of alternative systems available in this under $50 price range, as well as proprietary HA systems which can cost 10-50 times more.
|
||||||
|
* Using a tiered approach where all user access to the ESP8266 is passed through a controlling server means that the end-user interface (or smartphone connector), together with all of the associated validation and security can be implemented on a system designed to have the capacity to do this. This means that you can limit the scope of your ESP8266 application to a limited set of functions being sent to or responding to requests from this system.
|
||||||
|
* *If you are trying to implement a user-interface or HTTP webserver in your ESP8266 then you are really abusing its intended purpose. When it comes to scoping your ESP8266 applications, the adage **K**eep **I**t **S**imple **S**tupid truly applies.*
|
||||||
|
|
||||||
|
### How do I minimise the footprint of an application on the file system
|
||||||
|
|
||||||
|
* It is possible to write Lua code in a very compact format which is very dense in terms of functionality per KB of source code.
|
||||||
|
* However if you do this then you will also find it extremely difficult to debug or maintain your application.
|
||||||
|
* A good compromise is to use a tool such as [[http://luaforge.net/projects/luasrcdiet/|LuaSrcDiet]], which you can use to compact production code for downloading to the ESP8266:
|
||||||
|
* Keep a master repository of your code on your PC or a cloud-based versioning repository such as [[https://github.com/|GitHub]]
|
||||||
|
* Lay it out and comment it for ease of maintenance and debugging
|
||||||
|
* Use a package such as [[https://github.com/4refr0nt/ESPlorer|Esplorer]] to download modules that you are debugging and to test them.
|
||||||
|
* Once the code is tested and stable, then compress it using LuaSrcDiet before downloading to the ESP8266. Doing this will reduce the code footprint on the SPIFFS by 2-3x.
|
||||||
|
* Consider using `node.compile()` to pre-compile any production code. This removes the debug information from the compiled code reducing its size by roughly 40%. (However this is still perhaps 1.5-2x larger than a LuaSrcDiet-compressed source format, so if SPIFFS is tight then you might consider leaving less frequently run modules in Lua format. If you do a compilation, then you should consider removing the Lua source copy from file system as there's little point in keeping both on the ESP8266.
|
||||||
|
|
||||||
|
### How do I minimise the footprint of running application?
|
||||||
|
|
||||||
|
* The Lua Garbage collector is very aggressive at scanning and recovering dead resources. It uses an incremental mark-and-sweep strategy which means that any data which is not ultimately referenced back to the Globals table, the Lua registry or in-scope local variables in the current Lua code will be collected.
|
||||||
|
* Setting any variable to `nil` dereferences the previous context of that variable. (Note that reference-based variables such as tables, strings and functions can have multiple variables referencing the same object, but once the last reference has been set to `nil`, the collector will recover the storage.
|
||||||
|
* Unlike other compile-on-load languages such as PHP, Lua compiled code is treated the same way as any other variable type when it comes to garbage collection and can be collected when fully dereferenced, so that the code-space can be reused.
|
||||||
|
* Lua execution is intrinsically divided into separate event tasks with each bound to a Lua callback. This, when coupled with the strong dispose on dereference feature, means that it is very easy to structure your application using an classic technique which dates back to the 1950s known as [[wp>Overlay (programming)|Overlays]].
|
||||||
|
* Various approaches can be use to implement this. One is described by DP Whittaker in his [[http://www.esp8266.com/viewtopic.php?f=19&t=1940|Massive memory optimization: flash functions]] topic. Another is to use *volatile modules*. There are standard Lua templates for creating modules, but the `require()` library function creates a reference for the loaded module in the `package.loaded` table, and this reference prevents the module from being garbage collected. To make a module volatile, you should remove this reference to the loaded module by setting its corresponding entry in `package.loaded` to `nil`. You can't do this in the outermost level of the module (since the reference is only created once execution has returned from the module code), but you can do it in any module function, and typically an initialisation function for the module, as in the following example:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
local s=net.createServer(net.TCP)
|
||||||
|
s:listen(80,function(c) require("connector").init(c) end)
|
||||||
|
```
|
||||||
|
* **`connector.lua`** would be a standard module pattern except that the `M.init()` routine must include the lines
|
||||||
|
|
||||||
|
```lua
|
||||||
|
local M, module = {}, ...
|
||||||
|
...
|
||||||
|
function M.init(csocket)
|
||||||
|
package.loaded[module]=nil
|
||||||
|
...
|
||||||
|
end
|
||||||
|
--
|
||||||
|
return M
|
||||||
|
```
|
||||||
|
* This approach ensures that the module can be fully dereferenced on completion. OK, in this case, this also means that the module has to be reloaded on each TCP connection to port 80; however, loading a compiled module from SPIFFS only takes a few mSec, so surely this is an acceptable overhead if it enables you to break down your application into RAM-sized chunks. Note that `require()` will automatically search for `connector.lc` followed by `connector.lua`, so the code will work for both source and compiled variants.
|
||||||
|
* Whilst the general practice is for a module to return a table, [PiL 15.1] suggests that it is sometimes appropriate to return a single function instead as this avoids the memory overhead of an additional table. This pattern would look as follows:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
--
|
||||||
|
local s=net.createServer(net.TCP)
|
||||||
|
s:listen(80,function(c) require("connector")(c) end)
|
||||||
|
```
|
||||||
|
|
||||||
|
```lua
|
||||||
|
local module = _ -- this is a situation where using an upvalue is essential!
|
||||||
|
return function (csocket)
|
||||||
|
package.loaded[module]=nil
|
||||||
|
module = nil
|
||||||
|
...
|
||||||
|
end
|
||||||
|
```
|
||||||
|
* Also note that you should ***not*** normally code this up listener call as the following because the RAM now has to accommodate both the module which creates the server *and* the connector logic.
|
||||||
|
|
||||||
|
```lua
|
||||||
|
...
|
||||||
|
local s=net.createServer(net.TCP)
|
||||||
|
local connector = require("connector") -- don't do this unless you've got the RAM available!
|
||||||
|
s:listen(80,connector)
|
||||||
|
```
|
||||||
|
|
||||||
|
### How do I reduce the size of my compiled code?
|
||||||
|
|
||||||
|
Note that there are two methods of saving compiled Lua to SPIFFS:
|
||||||
|
- The first is to use `node.compile()` on the `.lua` source file, which generates the equivalent bytecode `.lc` file. This approach strips out all the debug line and variable information.
|
||||||
|
- The second is to use `loadfile()` to load the source file into memory, followed by `string.dump()` to convert it in-memory to a serialised load format which can then be written back to a `.lc` file. This approach creates a bytecode file which retains the debug information.
|
||||||
|
|
||||||
|
The memory footprint of the bytecode created by method (2) is the same as when executing source files directly, but the footprint of bytecode created by method (1) is typically **60% of this size**, because the debug information is almost as large as the code itself. So using `.lc` files generated by `node.compile()` considerably reduces code size in memory -- albeit with the downside that any runtime errors are extremely limited.
|
||||||
|
|
||||||
|
In general consider method (1) if you have stable production code that you want to run in as low a RAM footprint as possible. Yes, method (2) can be used if you are still debugging, but you will probably be changing this code quite frequently, so it is easier to stick with `.lua` files for code that you are still developing.
|
||||||
|
|
||||||
|
Note that if you use `require("XXX")` to load your code then this will automatically search for `XXX.lc` then `XXX.lua` so you don't need to include the conditional logic to load the bytecode version if it exists, falling back to the source version otherwise.
|
||||||
|
|
||||||
|
### How do I get a feel for how much memory my functions use?
|
||||||
|
|
||||||
|
* You should get an overall understanding of the VM model if you want to make good use of the limited resources available to Lua applications. An essential reference here is [[http://luaforge.net/docman/83/98/ANoFrillsIntroToLua51VMInstructions.pdf|A No Frills Introduction to Lua 5.1 VM Instructions]] . This explain how the code generator works, how much memory overhead is involved with each table, function, string etc..
|
||||||
|
* You can't easily get a bytecode listing of your ESP8266 code; however there are two broad options for doing this:
|
||||||
|
* **Generate a bytecode listing on your development PC**. The Lua 5.1 code generator is basically the same on the PC and on the ESP8266, so whilst it isn't identical, using the standard Lua batch compiler `luac` against your source on your PC with the `-l -s` option will give you a good idea of what your code will generate. The main difference between these two variants is the size_t for ESP8266 is 4 bytes rather than the 8 bytes size_t found on modern 64bit development PCs; and the eLua variants generate different access references for ROM data types. If you want to see what the `string.dump()` version generates then drop the `-s` option to retain the debug information.
|
||||||
|
* **Upload your `.lc` files to the PC and disassemble then there**. There are a number of Lua code disassemblers which can list off the compiled code that you application modules will generate, `if` you have a script to upload files from your ESP8266 to your development PC. I use [[http://luaforge.net/projects/chunkspy/|ChunkSpy]] which can be downloaded [[http://files.luaforge.net/releases/chunkspy/chunkspy/ChunkSpy-0.9.8/ChunkSpy-0.9.8.zip|here]] , but you will need to apply the following patch so that ChunkSpy understands eLua data types:
|
||||||
|
|
||||||
|
```diff
|
||||||
|
--- a/ChunkSpy-0.9.8/5.1/ChunkSpy.lua 2015-05-04 12:39:01.267975498 +0100
|
||||||
|
+++ b/ChunkSpy-0.9.8/5.1/ChunkSpy.lua 2015-05-04 12:35:59.623983095 +0100
|
||||||
|
@@ -2193,6 +2193,9 @@
|
||||||
|
config.AUTO_DETECT = true
|
||||||
|
elseif a == "--brief" then
|
||||||
|
config.DISPLAY_BRIEF = true
|
||||||
|
+ elseif a == "--elua" then
|
||||||
|
+ config.LUA_TNUMBER = 5
|
||||||
|
+ config.LUA_TSTRING = 6
|
||||||
|
elseif a == "--interact" then
|
||||||
|
perform = ChunkSpy_Interact
|
||||||
|
```
|
||||||
|
* Your other great friend is to use `node.heap()` regularly through your code.
|
||||||
|
* Use these tools and play with coding approaches to see how many instructions each typical line of code takes in your coding style. The Lua Wiki gives some general [[wp>Program optimization|optimisation]] tips, but in general just remember that these focus on optimising for execution speed and you will be interested mainly in optimising for code and variable space as these are what consumes precious RAM.
|
||||||
|
|
||||||
|
### What is the cost of using functions? ###
|
||||||
|
|
||||||
|
Consider the output of `dofile("test1a.lua")` on the following code compared to the equivalent where the function `pnh()` is removed and the extra `print(heap())` statement is placed inline:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
-- test1b.lua
|
||||||
|
collectgarbage()
|
||||||
|
local heap = node.heap
|
||||||
|
print(heap())
|
||||||
|
local function pnh() print(heap()) end
|
||||||
|
pnh()
|
||||||
|
print(heap())
|
||||||
|
```
|
||||||
|
|
||||||
|
|Heap Value | Function Call | Inline |
|
||||||
|
|-----------|---------------|--------|
|
||||||
|
| 1 | 20712 | 21064 |
|
||||||
|
| 2 | 20624 | 21024 |
|
||||||
|
| 3 | 20576 | 21024 |
|
||||||
|
|
||||||
|
Here bigger means less RAM used.
|
||||||
|
|
||||||
|
Of course you should still use functions to structure your code and encapsulate common repeated processing, but just bear in mind that each function definition has a relatively high overhead for its header record and stack frame (compared to the 20 odd KB RAM available). *So try to avoid overusing functions. If there are less than a dozen or so lines in the function then you should consider putting this code inline if it makes sense to do so.*
|
||||||
|
|
||||||
|
### What other resources are available?
|
||||||
|
|
||||||
|
* Install lua and luac on your development PC. This is freely available for Windows, Mac and Linux distributions, but we strongly suggest that you use Lua 5.1 to maintain source compatibility with ESP8266 code. This will allow you not only to unit test some modules on your PC in a rich development environment, but you can also use `luac` to generate a bytecode listing of your code and to validate new code syntactically before downloading to the ESP8266. This will also allow you to develop server-side applications and embedded applications in a common language.
|
||||||
|
|
||||||
|
## Firmware and Lua app development
|
||||||
|
|
||||||
|
### How to save memory?
|
||||||
|
* The NodeMCU development team recommends that you consider using a tailored firmware build, which only includes the modules that you plan to use before developing any Lua application. Once you have the ability to make and flash custom builds, the you also have the option of moving time sensitive or logic intensive code into your own custom module. Doing this can save a large amount of RAM as C code can be run directly from Flash memory. If you want an easy-to-use intermediate option then why note try the [cloud based NodeMCU custom build service](http://frightanic.com/NodeMCU-custom-build)?.
|
||||||
|
|
||||||
|
## Hardware Specifics
|
||||||
|
|
||||||
|
### Why file writes fail all the time on DEVKIT V1.0?
|
||||||
|
|
||||||
|
* NodeMCU DEVKIT V1.0 uses ESP12-E-DIO(ESP-12-D) module. This module runs the Flash memory in [[#What's the different between DIO and QIO mode?|Dual IO SPI]] (DIO) mode. This firmware will not be correctly loaded if you uses old flashtool version, and the filesystem will not work if you used a pre 0.9.6 firmware version (<0.9.5) or old. The easiest way to resolve this problem s update all the firmware and flash tool to current version.
|
||||||
|
- Use the latest [esptool.py](https://github.com/themadinventor/esptool) with DIO support and command option to flash firmware, or
|
||||||
|
- Use the latest [NodeMCU flasher](https://github.com/NodeMCU/NodeMCU-flasher) with default option. (You must select the `restore to default` option in advanced menu tab), or
|
||||||
|
- Use the latest Espressif's flash tool -- see [this Espressif forum topic](http://bbs.espressif.com/viewtopic.php?f=5&t=433) (without auto download support). Use DIO mode and 32M flash size option, and flash latest firmware to 0x00000. Before flashing firmware, remember to hold FLASH button, and press RST button once. Note that the new NodeMCU our firmware download tool, when released, will be capable of flashing firmware automatically without any button presses.
|
||||||
|
|
||||||
|
### What's the different between DIO and QIO mode?
|
||||||
|
<TODO>
|
||||||
|
|
||||||
|
### How to use DEVKIT V0.9 on Mac OS X?
|
||||||
|
<TODO>
|
||||||
|
|
||||||
|
### How does DEVKIT use DTR and RTS enter download mode?
|
||||||
|
<TODO>
|
|
@ -0,0 +1,26 @@
|
||||||
|
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
|
|
@ -0,0 +1,12 @@
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,49 @@
|
||||||
|
# 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()
|
||||||
|
```
|
||||||
|
___
|
|
@ -0,0 +1,171 @@
|
||||||
|
# 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.
|
||||||
|
___
|
|
@ -0,0 +1,109 @@
|
||||||
|
# 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")))
|
||||||
|
```
|
||||||
|
___
|
|
@ -0,0 +1,342 @@
|
||||||
|
# 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()`
|
||||||
|
___
|
|
@ -0,0 +1,158 @@
|
||||||
|
# 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
|
||||||
|
```
|
||||||
|
___
|
|
@ -0,0 +1,396 @@
|
||||||
|
# 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()`
|
||||||
|
___
|
|
@ -0,0 +1,159 @@
|
||||||
|
# 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()`
|
||||||
|
___
|
|
@ -0,0 +1,62 @@
|
||||||
|
# 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()`
|
||||||
|
___
|
|
@ -0,0 +1,112 @@
|
||||||
|
# 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
|
||||||
|
```
|
||||||
|
___
|
|
@ -0,0 +1,43 @@
|
||||||
|
# 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()`
|
||||||
|
___
|
|
@ -0,0 +1,90 @@
|
||||||
|
# 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)
|
||||||
|
```
|
||||||
|
___
|
||||||
|
|
|
@ -0,0 +1,5 @@
|
||||||
|
# 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.
|
|
@ -0,0 +1,7 @@
|
||||||
|
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.
|
Binary file not shown.
After Width: | Height: | Size: 1.9 KiB |
|
@ -0,0 +1,10 @@
|
||||||
|
# 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).
|
||||||
|
|
||||||
|
[English](en/index.md)
|
||||||
|
|
||||||
|
[Deutsch](de/index.md)
|
||||||
|
|
|
@ -0,0 +1,125 @@
|
||||||
|
var nodemcu = nodemcu || {};
|
||||||
|
(function () {
|
||||||
|
'use strict';
|
||||||
|
var languageCodeToNameMap = {en: 'English', de: 'Deutsch'};
|
||||||
|
var languageNames = values(languageCodeToNameMap);
|
||||||
|
var defaultLanguageCode = 'en';
|
||||||
|
|
||||||
|
$(document).ready(function () {
|
||||||
|
hideNavigationForAllButSelectedLanguage();
|
||||||
|
addLanguageSelectorToRtdFlyOutMenu();
|
||||||
|
});
|
||||||
|
|
||||||
|
function hideNavigationForAllButSelectedLanguage() {
|
||||||
|
var selectedLanguageCode = determineSelectedLanguageCode();
|
||||||
|
var selectedLanguageName = languageCodeToNameMap[selectedLanguageCode];
|
||||||
|
// Finds all subnav elements and hides them if they're /language/ subnavs. Hence, all 'Modules' subnav elements
|
||||||
|
// won't be hidden.
|
||||||
|
// <ul class="subnav">
|
||||||
|
// <li><span>Modules</span></li>
|
||||||
|
// <li class="toctree-l1 ">
|
||||||
|
// <a class="" href="EN/modules/node/">node</a>
|
||||||
|
// </li>
|
||||||
|
$('.subnav li span').not(':contains(' + selectedLanguageName + ')').each(function (index) {
|
||||||
|
var spanElement = $(this);
|
||||||
|
if ($.inArray(spanElement.text(), languageNames) > -1) {
|
||||||
|
spanElement.parent().parent().hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a language selector to the RTD fly-out menu found bottom left. Example:
|
||||||
|
*
|
||||||
|
* <dl>
|
||||||
|
* <dt>Languages</dt>
|
||||||
|
* <dd><a href="http://nodemcu.readthedocs.org/en/<branch>/de/">de</a></dd>
|
||||||
|
* <strong>
|
||||||
|
* <dd><a href="http://nodemcu.readthedocs.org/en/<branch>/en/">en</a></dd>
|
||||||
|
* </strong>
|
||||||
|
* </dl>
|
||||||
|
*
|
||||||
|
* UGLY! That fly-out menu is added by RTD with an AJAX call after page load. Hence, we need to
|
||||||
|
* react to the subsequent DOM manipulation using a DOM4 MutationObserver. The provided structure
|
||||||
|
* is as follows:
|
||||||
|
*
|
||||||
|
* <div class="rst-other-versions">
|
||||||
|
* <!-- Inserted RTD Footer -->
|
||||||
|
* <div class="injected">
|
||||||
|
*/
|
||||||
|
function addLanguageSelectorToRtdFlyOutMenu() {
|
||||||
|
var flyOutWrapper = $('.rst-other-versions');
|
||||||
|
// only relevant on RTD
|
||||||
|
if (flyOutWrapper.size() > 0) {
|
||||||
|
var observer = new MutationObserver(function (mutations) {
|
||||||
|
// since mutation on the target node was triggered we can safely assume the injected RTD div has now been added
|
||||||
|
var injectedDiv = $('.rst-other-versions .injected');
|
||||||
|
var selectedLanguageCode = determineSelectedLanguageCode();
|
||||||
|
var dl = document.createElement('dl');
|
||||||
|
var dt = document.createElement('dt');
|
||||||
|
dl.appendChild(dt);
|
||||||
|
dt.appendChild(document.createTextNode('Languages'));
|
||||||
|
for (var languageCode in languageCodeToNameMap) {
|
||||||
|
dl.appendChild(createLanguageLinkFor(languageCode, selectedLanguageCode === languageCode));
|
||||||
|
}
|
||||||
|
injectedDiv.prepend(dl);
|
||||||
|
// no need for that observer anymore
|
||||||
|
observer.disconnect();
|
||||||
|
});
|
||||||
|
|
||||||
|
// observed target node is the fly-out wrapper, the only event we care about is when children are modified
|
||||||
|
observer.observe(flyOutWrapper[0], {childList: true});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function createLanguageLinkFor(languageCode, isCurrentlySelected) {
|
||||||
|
var strong;
|
||||||
|
// split[0] is an '' because the path starts with the separator
|
||||||
|
var pathSegments = window.location.pathname.split('/');
|
||||||
|
var dd = document.createElement("dd");
|
||||||
|
var href = document.createElement("a");
|
||||||
|
href.setAttribute('href', '/' + pathSegments[1] + '/' + pathSegments[2] + '/' + languageCode);
|
||||||
|
href.appendChild(document.createTextNode(languageCode));
|
||||||
|
dd.appendChild(href);
|
||||||
|
if (isCurrentlySelected) {
|
||||||
|
strong = document.createElement("strong");
|
||||||
|
strong.appendChild(dd);
|
||||||
|
return strong;
|
||||||
|
} else {
|
||||||
|
return dd;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Analyzes the URL of the current page to find out what the selected language is. It's usually
|
||||||
|
* part of the location path. The code needs to distinguish between running MkDocs standalone
|
||||||
|
* and docs served from RTD. If no valid language could be determined the default language is
|
||||||
|
* returned.
|
||||||
|
*
|
||||||
|
* @returns 2-char language code
|
||||||
|
*/
|
||||||
|
function determineSelectedLanguageCode() {
|
||||||
|
var selectedLanguageCode, path = window.location.pathname;
|
||||||
|
if (window.location.origin.indexOf('readthedocs') > -1) {
|
||||||
|
// path is like /en/<branch>/<lang>/build/ -> extract 'lang'
|
||||||
|
// split[0] is an '' because the path starts with the separator
|
||||||
|
selectedLanguageCode = path.split('/')[3];
|
||||||
|
} else {
|
||||||
|
// path is like /<lang>/build/ -> extract 'lang'
|
||||||
|
selectedLanguageCode = path.substr(1, 2);
|
||||||
|
}
|
||||||
|
if (!selectedLanguageCode || selectedLanguageCode.length > 2) {
|
||||||
|
selectedLanguageCode = defaultLanguageCode;
|
||||||
|
}
|
||||||
|
return selectedLanguageCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
function values(associativeArray) {
|
||||||
|
var values = [];
|
||||||
|
for (var key in associativeArray) {
|
||||||
|
if (associativeArray.hasOwnProperty(key)) {
|
||||||
|
values.push(associativeArray[key]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
}());
|
|
@ -0,0 +1,57 @@
|
||||||
|
# node Module
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
####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)
|
||||||
|
```
|
||||||
|
___
|
|
@ -0,0 +1,44 @@
|
||||||
|
site_name: NodeMCU Documentation
|
||||||
|
site_description: Description of the NodeMCU documentation
|
||||||
|
repo_url: https://github.com/nodemcu/nodemcu-firmware/
|
||||||
|
|
||||||
|
theme: readthedocs
|
||||||
|
strict: true
|
||||||
|
|
||||||
|
markdown_extensions:
|
||||||
|
#http://pythonhosted.org/Markdown/extensions/admonition.html
|
||||||
|
- admonition:
|
||||||
|
- toc:
|
||||||
|
permalink: True
|
||||||
|
|
||||||
|
#requird due to https://github.com/rtfd/readthedocs.org/issues/1313
|
||||||
|
#see http://mkdocs.readthedocs.org/en/latest/user-guide/styling-your-docs/#customising-a-theme
|
||||||
|
extra_css:
|
||||||
|
- css/extra.css
|
||||||
|
extra_javascript:
|
||||||
|
- js/extra.js
|
||||||
|
|
||||||
|
site_favicon: img/favicon.png
|
||||||
|
|
||||||
|
pages:
|
||||||
|
- Overview: 'index.md'
|
||||||
|
- English:
|
||||||
|
- Home: 'en/index.md'
|
||||||
|
- Building the firmware: 'en/build.md'
|
||||||
|
- Flashing the firmware: 'en/flash.md'
|
||||||
|
- FAQ: 'en/faq.md'
|
||||||
|
- Support: 'en/support.md'
|
||||||
|
- Modules:
|
||||||
|
- 'adc': 'en/modules/adc.md'
|
||||||
|
- 'bit': 'en/modules/bit.md'
|
||||||
|
- 'crypto': 'en/modules/crypto.md'
|
||||||
|
- 'gpio': 'en/modules/gpio.md'
|
||||||
|
- 'node': 'en/modules/node.md'
|
||||||
|
- 'file': 'en/modules/file.md'
|
||||||
|
- 'rtcmem': 'en/modules/rtcmem.md'
|
||||||
|
- 'rtctime': 'en/modules/rtctime.md'
|
||||||
|
- 'rtcfifo': 'en/modules/rtcfifo.md'
|
||||||
|
- 'sntp': 'en/modules/sntp.md'
|
||||||
|
- 'uart': 'en/modules/uart.md'
|
||||||
|
- Deutsch:
|
||||||
|
- Home: 'de/index.md'
|
Loading…
Reference in New Issue