Commit 82b19c4c authored by Marcel Stör's avatar Marcel Stör
Browse files

Merge branch 'newdocs' into dev

parents 7e8c5489 96a05dcd
# i2c Module
## i2c.address()
Setup I²C address and read/write mode for the next transfer.
#### Syntax
`i2c.address(id, device_addr, direction)`
#### Parameters
- `id` always 0
- `device_addr` device address
- `direction` `i2c.TRANSMITTER` for writing mode , `i2c. RECEIVER` for reading mode
#### Returns
`true` if ack received, `false` if no ack received.
#### See also
[i2c.read()](#i2cread)
## i2c.read()
Read data for variable number of bytes.
#### Syntax
`i2c.read(id, len)`
#### Parameters
- `id` always 0
- `len` number of data bytes
#### Returns
`string` of received data
#### Example
```lua
id = 0
sda = 1
scl = 2
-- initialize i2c, set pin1 as sda, set pin2 as scl
i2c.setup(id, sda, scl, i2c.SLOW)
-- user defined function: read from reg_addr content of dev_addr
function read_reg(dev_addr, reg_addr)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, reg_addr)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.RECEIVER)
c = i2c.read(id, 1)
i2c.stop(id)
return c
end
-- get content of register 0xAA of device 0x77
reg = read_reg(0x77, 0xAA)
print(string.byte(reg))
```
####See also
[i2c.write()](#i2cwrite)
## i2c.setup()
Initialize the I²C module.
#### Syntax
`i2c.setup(id, pinSDA, pinSCL, speed)`
####Parameters
- `id` always 0
- `pinSDA` 1~12, IO index
- `pinSCL` 1~12, IO index
- `speed` only `i2c.SLOW` supported
#### Returns
`speed` the selected speed
####See also
[i2c.read()](#i2cread)
## i2c.start()
Send an I²C start condition.
#### Syntax
`i2c.start(id)`
#### Parameters
`id` always 0
#### Returns
`nil`
####See also
[i2c.read()](#i2cread)
## i2c.stop()
Send an I²C stop condition.
#### Syntax
`i2c.stop(id)`
####Parameters
`id` always 0
#### Returns
`nil`
####See also
[i2c.read()](#i2cread)
## i2c.write()
Write data to I²C bus. Data items can be multiple numbers, strings or lua tables.
####Syntax
`i2c.write(id, data1[, data2[, ..., datan]])`
####Parameters
- `id` always 0
- `data` data can be numbers, string or lua table.
#### Returns
`number` number of bytes written
#### Example
```lua
i2c.write(0, "hello", "world")
```
#### See also
[i2c.read()](#i2cread)
# MQTT Module
The client adheres to version 3.1.1 of the [MQTT](https://en.wikipedia.org/wiki/MQTT) protocol. Make sure that your broker supports and is correctly configured for version 3.1.1. The client is backwards incompatible with brokers running MQTT 3.1.
## mqtt.Client()
Creates a MQTT client.
#### Syntax
`mqtt.Client(clientid, keepalive, username, password[, cleansession])`
#### Parameters
- `clientid` client ID
- `keepalive` keepalive seconds
- `username` user name
- `password` user password
- `cleansession` 0/1 for `false`/`true`
#### Returns
MQTT client
#### Example
```lua
-- init mqtt client with keepalive timer 120sec
m = mqtt.Client("clientid", 120, "user", "password")
-- setup Last Will and Testament (optional)
-- Broker will publish a message with qos = 0, retain = 0, data = "offline"
-- to topic "/lwt" if client don't send keepalive packet
m:lwt("/lwt", "offline", 0, 0)
m:on("connect", function(client) print ("connected") end)
m:on("offline", function(client) print ("offline") end)
-- on publish message receive event
m:on("message", function(client, topic, data)
print(topic .. ":" )
if data ~= nil then
print(data)
end
end)
-- for TLS: m:connect("192.168.11.118", secure-port, 1)
m:connect("192.168.11.118", 1880, 0, function(client) print("connected") end)
-- Calling subscribe/publish only makes sense once the connection
-- was successfully established. In a real-world application you want
-- move those into the 'connect' callback or make otherwise sure the
-- connection was established.
-- subscribe topic with qos = 0
m:subscribe("/topic",0, function(client) print("subscribe success") end)
-- publish a message with data = hello, QoS = 0, retain = 0
m:publish("/topic","hello",0,0, function(client) print("sent") end)
m:close();
-- you can call m:connect again
```
# MQTT Client
## mqtt.client:close()
Closes connection to the broker.
#### Syntax
`mqtt:close()`
#### Parameters
none
#### Returns
`nil`
## mqtt.client:connect()
Connects to the broker specified by the given host, port, and secure options.
#### Syntax
`mqtt:connect(host, port, secure, function(client))`
#### Parameters
- `host` host, domain or IP (string)
- `port` broker port (number)
- `secure` 0/1 for `false`/`true`, default 0. [As per #539](https://github.com/nodemcu/nodemcu-firmware/issues/539#issuecomment-170298120) secure connections use TLS 1.2.
- `function(client)` call back function for when the connection was established
#### Returns
`nil`
## mqtt.client:lwt()
Setup [Last Will and Testament](http://www.hivemq.com/blog/mqtt-essentials-part-9-last-will-and-testament) (optional). A broker will publish a message with qos = 0, retain = 0, data = "offline" to topic "/lwt" if client does not send keepalive packet.
#### Syntax
`mqtt:lwt(topic, message, qos, retain)`
#### Parameters
- `topic` the topic to publish to (string)
- `message` the message to publish, (buffer or string)
- `qos` QoS level, default 0
- `retain` retain flag, default 0
#### Returns
`nil`
## mqtt.client:on()
Registers a callback function for an event.
#### Syntax
`mqtt:on(event, function(client[, topic[, message]]))`
#### Parameters
- `event` can be "connect", "message" or "offline"
- `function(client[, topic[, message]])` callback function. The first parameter is the client. If event is "message", the 2nd and 3rd param are received topic and message (strings).
#### Returns
`nil`
## mqtt.client:publish()
Publishes a message.
#### Syntax
`mqtt:publish(topic, payload, qos, retain, function(client))`
#### Parameters
- `topic` the topic to publish to ([topic string](http://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices))
- `message` the message to publish, (buffer or string)
- `qos` QoS level, default 0
- `retain` retain flag, default 0
- `function(client)` callback fired when PUBACK received
#### Returns
`nil`
## mqtt.client:subscribe()
Subscribes to one or several topics.
#### Syntax
`mqtt:subscribe(topic, qos, function(client, topic, message))`
#### Parameters
- `topic` a [topic string](http://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices)
- `qos` QoS subscription level, default 0
- `function(client, topic, message)` callback fired when message received
#### Returns
`nil`
\ No newline at end of file
# net Module
## Constants
`net.TCP`, `net.UDP`
## net.createConnection()
Creates a client.
#### Syntax
`net.createConnection(type, secure)`
#### Parameters
- `type` `net.TCP` or `net.UDP`
- `secure` 1 for encrypted, 0 for plain
#### Returns
net.socket sub module
#### Example
```lua
net.createConnection(net.UDP, 0)
```
#### See also
[`net.createServer()`](#netcreateserver)
## net.createServer()
Creates a server.
#### Syntax
`net.createServer(type, timeout)`
#### Parameters
- `type` `net.TCP` or `net.UDP`
- `timeout` for a TCP server timeout is 1~28'800 seconds (for an inactive client to be disconnected)
#### Returns
net.server sub module
#### Example
```lua
net.createServer(net.TCP, 30) -- 30s timeout
```
#### See also
[`net.createConnection()`](#netcreateconnection)
# net.server Module
## net.server:close()
Closes the server.
#### Syntax
`net.server.close()`
#### Parameters
none
#### Returns
`nil`
#### Example
```lua
-- creates a server
sv = net.createServer(net.TCP, 30)
-- closes the server
sv:close()
```
#### See also
[`net.createServer()`](#netcreateserver)
## net.server:listen()
Listen on port from IP address.
#### Syntax
`net.server.listen(port,[ip],function(net.socket))`
#### Parameters
- `port` port number
- `ip` IP address string, can be omitted
- `function(net.socket)` callback function, pass to caller function as param if a connection is created successfully
#### Returns
`nil`
#### Example
```lua
-- 30s time out for a inactive client
sv = net.createServer(net.TCP, 30)
-- server listens on 80, if data received, print data to console and send "hello world" back to caller
sv:listen(80, function(c)
c:on("receive", function(c, pl)
print(pl)
end)
c:send("hello world")
end)
```
#### See also
[`net.createServer()`](#netcreateserver)
# net.socket Module
## net.socket:close()
Closes socket.
#### Syntax
`close()`
#### Parameters
none
#### Returns
`nil`
#### See also
[`net.createServer()`](#netcreateserver)
## net.socket:connect()
Connect to a remote server.
#### Syntax
`connect(port, ip|domain)`
#### Parameters
- `port` port number
- `ip` IP address or domain name string
#### Returns
`nil`
#### See also
[`net.socket:on()`](#netsocketon)
## net.socket:dns()
Provides DNS resolution for a hostname.
#### Syntax
`dns(domain, function(net.socket, ip))`
#### Parameters
- `domain` domain name
- `function(net.socket, ip)` callback function. The first parameter is the socket, the second parameter is the IP address as a string.
#### Returns
`nil`
#### Example
```lua
sk = net.createConnection(net.TCP, 0)
sk:dns("www.nodemcu.com", function(conn, ip) print(ip) end)
sk = nil
```
#### See also
[`net.createServer()`](#netcreateserver)
## net.socket:on()
Register callback functions for specific events.
#### Syntax
`on(event, function())`
#### Parameters
- `event` string, which can be "connection", "reconnection", "disconnection", "receive" or "sent"
- `function(net.socket[, string])` callback function. The first parameter is the socket. If event is "receive", the second parameter is the received data as string.
#### Returns
`nil`
#### Example
```lua
sk = net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c) print(c) end )
sk:connect(80,"192.168.0.66")
sk:on("connection", function(sck,c)
-- Wait for connection before sending.
sk:send("GET / HTTP/1.1\r\nHost: 192.168.0.66\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
end)
```
#### See also
[`net.createServer()`](#netcreateserver)
## net.socket:send()
Sends data to server.
#### Syntax
`send(string, function(sent))`
#### Parameters
- `string` data in string which will be sent to server
- `function(sent)` callback function for sending string
#### Returns
`nil`
#### Note
Multiple consecutive `send()` calls aren't guaranteed to work (and often don't) as network requests are treated as separate tasks by the SDK. Instead, subscribe to the "sent" event on the socket and send additional data (or close) in that callback. See [#730](https://github.com/nodemcu/nodemcu-firmware/issues/730#issuecomment-154241161) for an example and explanation.
#### See also
[`net.socket:on()`](#netsocketon)
# net.dns Module
## net.dns.getdnsserver()
Gets the IP address of the DNS server used to resolve hostnames.
#### Syntax
`net.dns.getdnsserver(dns_index)`
#### Parameters
dns_index which DNS server to get (range 0~1)
#### Returns
IP address (string) of DNS server
#### Example
```lua
print(net.dns.getdnsserver(0)) -- 208.67.222.222
print(net.dns.getdnsserver(1)) -- nil
net.dns.setdnsserver("8.8.8.8", 0)
net.dns.setdnsserver("192.168.1.252", 1)
print(net.dns.getdnsserver(0)) -- 8.8.8.8
print(net.dns.getdnsserver(1)) -- 192.168.1.252
```
#### See also
[`net.dns:setdnsserver()`](#netdnssetdnsserver)
## net.dns.resolve()
Resolve a hostname to an IP address. Doesn't require a socket like [`net.socket.dns()`](#netsocketdns).
#### Syntax
`net.dns.resolve(host, function(ip))`
#### Parameters
- `host` hostname to resolve
- `function(sk, ip)` callback called when the name was resolved. Don't use `sk`, it's a socket used internally to resolve the hostname.
#### Returns
`nil`
#### Example
```lua
net.dns.resolve("www.google.com", function(sk, ip)
if (ip == nil) then print("DNS fail!") else print(ip) end
end)
```
#### See also
[`net.socket:dns()`](#netsocketdns)
## net.dns.setdnsserver()
Sets the IP of the DNS server used to resolve hostnames. Default: resolver1.opendns.com (208.67.222.222). You can specify up to 2 DNS servers.
#### Syntax
`net.dns.setdnsserver(dns_ip_addr, dns_index)`
#### Parameters
- `dns_ip_addr` IP address of a DNS server
- `dns_index` which DNS server to set (range 0~1). Hence, it supports max. 2 servers.
#### Returns
`nil`
#### See also
[`net.dns:getdnsserver()`](#netdnsgetdnsserver)
# 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 and extended reset info.
The first value returned 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)
The second value returned is the extended reset cause. Values are:
- 0, power-on
- 1, hardware watchdog reset
- 2, exception reset
- 3, software watchdog reset
- 4, software restart
- 5, wake from deep sleep
- 6, external reset
In general, the extended reset cause supercedes the raw code. The raw code is kept for backwards compatibility only. For new applications it is highly recommended to use the extended reset cause instead.
In case of extended reset cause 3 (exception reset), additional values are returned containing the crash information. These are, in order, EXCCAUSE, EPC1, EPC2, EPC3, EXCVADDR, and DEPC.
#### Syntax
`node.bootreason()`
#### Parameters
none
#### Returns
`rawcode, reason [, exccause, epc1, epc2, epc3, excvaddr, depc ]`
#### Example
```lua
_, reset_reason = node.bootreason()
if reset_reason == 0 then print("Power UP!") end
```
## node.chipid()
Returns the ESP chip ID.
#### Syntax
`node.chipid()`
#### Parameters
none
#### Returns
chip ID (number)
## node.compile()
Compiles a Lua text file into Lua bytecode, and saves it as .lc file.
#### Syntax
`node.compile("file.lua")`
#### 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.dsleep()
Enters deep sleep mode, wakes 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.
!!! note "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.
#### Syntax
`node.dsleep(us, option)`
#### 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 `nil`, it will use last alive setting as default option.
- 0, init data byte 108 is valuable
- \> 0, init data byte 108 is valueless
- 0, RF_CAL or not after deep-sleep wake up, depends on init data byte 108
- 1, RF_CAL after deep-sleep wake up, there will belarge current
- 2, no RF_CAL after deep-sleep wake up, there will only be small current
- 4, disable RF after deep-sleep wake up, just like modem sleep, there will be the smallest current
#### 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.flashid()
Returns the flash chip ID.
#### Syntax
`node.flashid()`
#### Parameters
none
#### Returns
flash ID (number)
## 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
none
#### Returns
system heap size left in bytes (number)
## node.info()
Returns NodeMCU version, chipid, flashid, flash size, flash mode, flash speed.
#### Syntax
`node.info()`
#### Parameters
none
#### 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.input()
Submits 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()`](#nodeoutput)
## node.key() --deprecated
Defines 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()`](#nodeled-deprecated)
## node.led() --deprecated
Sets the on/off time for the LED (on the old devkit 0.9), with the LED connected to GPIO16, multiplexed with [`node.key()`](#nodekey-deprecated).
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
- `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()`](#nodekey-deprecated)
## 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(function(str), 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()`](#nodeinput)
## node.readvdd33() --deprecated
Moved to [`adc.readvdd33()`](adc/#adcreadvdd33).
## node.restart()
Restarts the chip.
#### Syntax
`node.restart()`
#### Parameters
none
#### Returns
`nil`
## node.restore()
Restores 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
none
#### Returns
`nil`
#### Example
```lua
node.restore()
node.restart() -- ensure the restored settings take effect
```
## node.setcpufreq()
Change the working CPU Frequency.
#### Syntax
`node.setcpufreq(speed)`
#### Parameters
`speed` constant 'node.CPU80MHZ' or 'node.CPU160MHZ'
#### Returns
target CPU frequency (number)
#### Example
```lua
node.setcpufreq(node.CPU80MHZ)
```
## node.stripdebug()
Controls the amount of debug information kept during [`node.compile()`](#nodecompile), 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()`](#nodecompile)
# 1-Wire Module
This module provides functions to work with the [1-Wire](https://en.wikipedia.org/wiki/1-Wire) device communications bus system.
## ow.check_crc16()
Computes the 1-Wire CRC16 and compare it against the received CRC.
#### Syntax
`ow.check_crc16(buf, inverted_crc0, inverted_crc1[, crc])`
#### Parameters
- `buf` string value, data to be calculated check sum in string
- `inverted_crc0` LSB of received CRC
- `inverted_crc1` MSB of received CRC
- `crc` CRC starting value (optional)
#### Returns
true if the CRC matches, false otherwise
## ow.crc16()
Computes a Dallas Semiconductor 16 bit CRC. This is required to check the integrity of data received from many 1-Wire devices. Note that the CRC computed here is **not** what you'll get from the 1-Wire network, for two reasons:
1. The CRC is transmitted bitwise inverted.
2. Depending on the endian-ness of your processor, the binary representation of the two-byte return value may have a different byte order than the two bytes you get from 1-Wire.
#### Syntax
`ow.crc16(buf[, crc])`
#### Parameters
- `buf` string value, data to be calculated check sum in string
- `crc` CRC starting value (optional)
#### Returns
the CRC16 as defined by Dallas Semiconductor
## ow.crc8()
Computes a Dallas Semiconductor 8 bit CRC, these are used in the ROM and scratchpad registers.
#### Syntax
`ow.crc8(buf)`
#### Parameters
`buf` string value, data to be calculated check sum in string
#### Returns
CRC result as byte
## ow.depower()
Stops forcing power onto the bus. You only need to do this if you used the 'power' flag to `ow.write()` or used a `ow.write_bytes()` and aren't about to do another read or write.
#### Syntax
`ow.depower(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
`nil`
####See also
- [ow.write()](#owwrite)
- [ow.write_bytes()](#owwrite_bytes)
## ow.read()
Reads a byte.
####Syntax
`ow.read(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
byte read from slave device
## ow.read_bytes()
Reads multi bytes.
#### Syntax
`ow.read_bytes(pin, size)`
#### Parameters
- `pin` 1~12, I/O index
- `size` number of bytes to be read from slave device
#### Returns
`string` bytes read from slave device
## ow.reset()
Performs a 1-Wire reset cycle.
#### Syntax
`ow.reset(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
- `1` if a device responds with a presence pulse
- `0` if there is no device or the bus is shorted or otherwise held low for more than 250 µS
## ow.reset_search()
Clears the search state so that it will start from the beginning again.
#### Syntax
`ow.reset_search(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
`nil`
## ow.search()
Looks for the next device.
#### Syntax
`ow.search(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
`rom_code` string with length of 8 upon success. It contains the rom code of slave device. Returns `nil` if search was unsuccessful.
#### See also
[ow.target_search()](#owtargetsearch)
## ow.select()
Issues a 1-Wire rom select command. Make sure you do the `ow.reset(pin)` first.
#### Syntax
`ow.select(pin, rom)`
#### Parameters
- `pin` 1~12, I/O index
- `rom` string value, len 8, rom code of the salve device
#### Returns
`nil`
#### Example
```lua
-- 18b20 Example
pin = 9
ow.setup(pin)
count = 0
repeat
count = count + 1
addr = ow.reset_search(pin)
addr = ow.search(pin)
tmr.wdclr()
until (addr ~= nil) or (count > 100)
if addr == nil then
print("No more addresses.")
else
print(addr:byte(1,8))
crc = ow.crc8(string.sub(addr,1,7))
if crc == addr:byte(8) then
if (addr:byte(1) == 0x10) or (addr:byte(1) == 0x28) then
print("Device is a DS18S20 family device.")
repeat
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
tmr.delay(1000000)
present = ow.reset(pin)
ow.select(pin, addr)
ow.write(pin,0xBE,1)
print("P="..present)
data = nil
data = string.char(ow.read(pin))
for i = 1, 8 do
data = data .. string.char(ow.read(pin))
end
print(data:byte(1,9))
crc = ow.crc8(string.sub(data,1,8))
print("CRC="..crc)
if crc == data:byte(9) then
t = (data:byte(1) + data:byte(2) * 256) * 625
t1 = t / 10000
t2 = t % 10000
print("Temperature="..t1.."."..t2.."Centigrade")
end
tmr.wdclr()
until false
else
print("Device family is not recognized.")
end
else
print("CRC is not valid!")
end
end
```
####See also
[ow.reset()](#owreset)
## ow.setup()
Sets a pin in onewire mode.
#### Syntax
`ow.setup(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
`nil`
## ow.skip()
Issues a 1-Wire rom skip command, to address all on bus.
#### Syntax
`ow.skip(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
`nil`
## ow.target_search()
Sets up the search to find the device type `family_code`. The search itself has to be initiated with a subsequent call to `ow.search()`.
#### Syntax
`ow.target_search(pin, family_code)`
#### Parameters
- `pin` 1~12, I/O index
- `family_code` byte for family code
#### Returns
`nil`
####See also
[ow.search()](#owsearch)
## ow.write()
Writes a byte. If `power` is 1 then the wire is held high at the end for parasitically powered devices. You are responsible for eventually depowering it by calling `ow.depower()` or doing another read or write.
#### Syntax
`ow.write(pin, v, power)`
#### Parameters
- `pin` 1~12, I/O index
- `v` byte to be written to salve device
- `power` 1 for wire being held high for parasitically powered devices
#### Returns
`nil`
####See also
[ow.depower()](#owdepower)
## ow.write_bytes()
Writes multi bytes. If `power` is 1 then the wire is held high at the end for parasitically powered devices. You are responsible for eventually depowering it by calling `ow.depower()` or doing another read or write.
#### Syntax
`ow.write_bytes(pin, buf, power)`
#### Parameters
- `pin` 1~12, IO index
- `buf` string to be written to slave device
- `power` 1 for wire being held high for parasitically powered devices
#### Returns
`nil`
####See also
[ow.depower()](#owdepower)
# pwm Module
## pwm.close()
Quit PWM mode for the specified GPIO pin.
#### Syntax
`pwm.close(pin)`
#### Parameters
`pin` 1~12, IO index
#### Returns
`nil`
#### See also
[pwm.start()](#pwmstart)
## pwm.getclock()
Get selected PWM frequency of pin.
#### Syntax
`pwm.getclock(pin)`
#### Parameters
`pin` 1~12, IO index
#### Returns
`number` PWM frequency of pin
#### See also
[pwm.setclock()](#pwmsetclock)
#### See also
[pwm.getduty()](#pwmgetduty)
## pwm.getduty()
Get selected duty cycle of pin.
#### Syntax
`pwm.getduty(pin)`
#### Parameters
`pin` 1~12, IO index
#### Returns
`number` duty cycle, max 1023
#### See also
[pwm.setduty()](#pwmsetduty)
## pwm.setclock()
Set PWM frequency.
**Note:** Setup of the PWM frequency will synchronously change other setups as well if there are any. Only one PWM frequency can be allowed for the system.
#### Syntax
`pwm.setclock(pin, clock)`
#### Parameters
- `pin` 1~12, IO index
- `clock` 1~1000, PWM frequency
#### Returns
`nil`
#### See also
[pwm.getclock()](#pwmgetclock)
## pwm.setduty()
Set duty cycle for a pin.
#### Syntax
`pwm.setduty(pin, duty)`
#### Parameters
- `pin` 1~12, IO index
- `duty` 0~1023, pwm duty cycle, max 1023 (10bit)
#### Returns
`nil`
#### Example
```lua
-- D1 is connected to green led
-- D2 is connected to blue led
-- D3 is connected to red led
pwm.setup(1, 500, 512)
pwm.setup(2, 500, 512)
pwm.setup(3, 500, 512)
pwm.start(1)
pwm.start(2)
pwm.start(3)
function led(r, g, b)
pwm.setduty(1, g)
pwm.setduty(2, b)
pwm.setduty(3, r)
end
led(512, 0, 0) -- set led to red
led(0, 0, 512) -- set led to blue.
```
## pwm.setup()
Set pin to PWM mode. Only 6 pins can be set to PWM mode at the most.
#### Syntax
`pwm.setup(pin, clock, duty)`
#### Parameters
- `pin` 1~12, IO index
- `clock` 1~1000, pwm frequency
- `duty` 0~1023, pwm duty cycle, max 1023 (10bit)
#### Returns
`nil`
#### Example
```lua
-- set pin index 1 as pwm output, frequency is 100Hz, duty cycle is half.
pwm.setup(1, 100, 512)
```
#### See also
[pwm.start()](#pwmstart)
## pwm.start()
PWM starts, the waveform is applied to the GPIO pin.
#### Syntax
`pwm.start(pin)`
####Parameters
`pin` 1~12, IO index
#### Returns
`nil`
#### See also
[pwm.stop()](#pwmstop)
## pwm.stop()
Pause the output of the PWM waveform.
#### Syntax
`pwm.stop(pin)`
#### Parameters
`pin` 1~12, IO index
#### Returns
`nil`
#### See also
[pwm.start()](#pwmstart)
# 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](https://en.wikipedia.org/wiki/Real-time_clock) 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()`](#rtcfifoprepare) is called.
This is a companion module to the [rtcmem](rtcmem.md) and [rtctime](rtctime.md) modules.
## 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)`](rtctime.md#rtctimedsleep_aligned) where `interval_us` is what was given to [`rtcfifo.prepare()`](#rtcfifoprepare).
####Syntax
`rtcfifo.dsleep_until_sample(minsleep_us)`
####Parameter
`minsleep_us` minimum sleep time, in microseconds
####Example
```lua
-- deep sleep until it's time to take the next sample
rtcfifo.dsleep_until_sample(0)
```
####See also
[`rtctime.dsleep_aligned()`](rtctime.md#rtctimedsleep_aligned)
## 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()`](#rtcfifoput).
- `timestamp` timestamp in seconds
- `value` the value
- `neg_e` scaling factor
- `name` 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
none
####Returns
The values returned match the input arguments used to [`rtcfifo.put()`](#rtcfifoput).
- `timestamp` timestamp in seconds
- `value` the value
- `neg_e` scaling factor
- `name` 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.prepare()
Initializes the rtcfifo module for use.
Calling [`rtcfifo.prepare()`](#rtcfifoprepare) 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()`](#rtcfifosleep_until_sample) function, this field sets the sample interval (in microseconds) to use. It is effectively the first argument of [`rtctime.dsleep_aligned()`](rtctime.md#rtctimedsleep_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
-- Initialize with default values
rtcfifo.prepare()
```
```lua
-- Use RTC slots 19 and up for variable storage
rtcfifo.prepare({storage_begin=21, storage_end=128})
```
####See also
[`rtcfifo.ready()`](#rtcfifoready)
####See also
[`rtcfifo.prepare()`](#rtcfifoprepare)
## 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()`](rtctime.md#rtctimeget).
- `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()`](#rtcfifoprepare)) names in use, the rtcfifo evicts all earlier samples.
####Returns
`nil`
####Example
```lua
-- Obtain a sample value from somewhere
local sample = ...
-- Store sample with no scaling, under the name "foo"
rtcfifo.put(rtctime.get(), sample, 0, "foo")
```
## rtcfifo.ready()
Returns non-zero if the rtcfifo has been prepared and is ready for use, zero if not.
####Syntax:
`rtcfifo.ready()`
####Parameters
none
####Returns
Non-zero if the rtcfifo has been prepared and is ready for use, zero if not.
####Example
```lua
-- Prepare the rtcfifo if not already done
if not rtcfifo.ready() then
rtcfifo.prepare()
end
```
\ No newline at end of file
# rtcmem Module
The rtcmem module provides basic access to the [RTC](https://en.wikipedia.org/wiki/Real-time_clock) (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.
This is a companion module to the [rtctime](rtctime.md) and [rtcfifo](rtcfifo.md) modules.
## rtcmem.read32()
Reads one or more 32bit values from RTC user memory.
#### Syntax
`rtcmem.read32(idx [, num])`
#### Parameters
- `idx` zero-based index to start reading from
- `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()`](#rtcmemwrite32)
## 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` zero-based index to start writing to. Auto-increments if multiple values are given.
- `val` value to store (32bit)
- `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()`](#rtcmemread32)
\ No newline at end of file
# rtctime Module
The rtctime module provides advanced timekeeping support for NodeMCU, including keeping time across deep sleep cycles (provided [`rtctime.dsleep()`](#rtctimedsleep) is used instead of [`node.dsleep()`](node.md#nodedsleep)). 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](https://en.wikipedia.org/wiki/Network_Time_Protocol) (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](https://en.wikipedia.org/wiki/Real-time_clock), 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()`](#rtctimeset)). 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()`](#rtctimeset) (or [`sntp.sync()`](sntp.md#sntpsync)) has been called these RTC memory slots will be used.
This is a companion module to the [rtcmem](rtcmem.md) and [SNTP](sntp.md) modules.
## rtctime.dsleep()
Puts the ESP8266 into deep sleep mode, like [`node.dsleep()`](node.md#nodedsleep). It differs from [`node.dsleep()`](node.md#nodedsleep) in the following ways:
- Time is kept across the deep sleep. I.e. [`rtctime.get()`](#rtctimeget) 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()`](node.md#nodedsleep).
- 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` number of microseconds to sleep for. Maxmium value is 4294967295us, or ~71 minutes.
- `option` sleep option, see [`node.dsleep()`](node.md#nodedsleep) for specifics.
#### Returns
This function does not return.
#### Example
```lua
-- sleep for a minute
rtctime.dsleep(60*1000000)
```
```lua
-- sleep for 5 seconds, do not start RF on wakeup
rtctime.dsleep(5000000, 4)
```
## 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` 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
-- sleep at least 3 seconds, then wake up on the next 5-second boundary
rtctime.dsleep_aligned(5*1000000, 3*1000000)
```
## rtctime.get()
Returns the current time. If current time is not available, zero is returned.
#### Syntax
`rtctime.get()`
#### Parameters
none
#### 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()`](#rtctimeset)
## 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()`](#rtctimeget) *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 (see [SNTP module](sntp.md)), 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
-- Set time to 2015 July 9, 18:29:49
rtctime.set(1436430589, 0)
```
#### See also
[`sntp.sync()`](sntp.md#sntpsync)
\ No newline at end of file
# SNTP Module
The SNTP module implements a [Simple Network Time Procotol](https://en.wikipedia.org/wiki/Network_Time_Protocol#SNTP) client. This includes support for the "anycast" [NTP](https://en.wikipedia.org/wiki/Network_Time_Protocol) 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](rtctime.md) 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.
## sntp.sync()
Attempts to obtain time synchronization.
#### Syntax
`sntp.sync([server_ip], [callback], [errcallback])`
#### Parameters
- `server_ip` if 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` Iif provided it will be invoked on a successful synchronization, with three parameters: seconds, microseconds, and server. Note that when the [rtctime](rtctime.md) module is available, there is no need to explicitly call [`rtctime.set()`](rtctime.md#rtctimeset) - this module takes care of doing so internally automatically, for best accuracy.
- `errcallback` failure callback with no parameters. The module automatically performs a number of retries before giving up and reporting the error.
#### 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()`](rtctime.md#rtctimeset)
#spi module
All transactions for sending and receiving are most-significant-bit first and least-significant last.
For technical details of the underlying hardware refer to [metalphreak's ESP8266 HSPI articles](http://d.av.id.au/blog/tag/hspi/).
## High Level Functions
The high level functions provide a send & receive API for half- and
full-duplex mode. Sent and received data items are restricted to 1 - 32 bit
length and each data item is surrounded by (H)SPI CS inactive.
## spi.recv()
Receive data from SPI.
#### Syntax
`spi.recv(id, size[, default_data])`
#### Parameters
- `id` SPI ID number: 0 for SPI, 1 for HSPI
- `size` number of data items to be read
- `default_data` default data being sent on MOSI (all-1 if omitted)
#### Returns
String containing the bytes read from SPI.
####See also
[spi.send()](#spisend)
## spi.send()
Send data via SPI in half-duplex mode. Send & receive data in full-duplex mode.
#### Syntax
HALFDUPLEX:<br />
`wrote = spi.send(id, data1[, data2[, ..., datan]])`
FULLDUPLEX:<br />
`wrote[, rdata1[, ..., rdatan]] = spi.send(id, data1[, data2[, ..., datan]])`
#### Parameters
- `id` SPI ID number: 0 for SPI, 1 for HSPI
- `data` data can be either a string, a table or an integer number.<br/>Each data item is considered with `databits` number of bits.
#### Returns
- `wrote` number of written bytes
- `rdata` received data when configured with `spi.FULLDUPLEX`<br />Same data type as corresponding data parameter.
#### Example
```lua
=spi.send(1, 0, 255, 255, 255)
4 255 192 32 0
x = {spi.send(1, 0, 255, 255, 255)}
=x[1]
4
=x[2]
255
=x[3]
192
=x[4]
32
=x[5]
0
=x[6]
nil
=#x
5
_, _, x = spi.send(1, 0, {255, 255, 255})
=x[1]
192
=x[2]
32
=x[3]
0
```
#### See also
- [spi.setup()](#spisetup)
- [spi.recv()](#spirecv)
## spi.setup()
Set up the SPI configuration.
Refer to [Serial Peripheral Interface Bus](https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Clock_polarity_and_phase) for details regarding the clock polarity and phase definition.
#### Syntax
`spi.setup(id, mode, cpol, cpha, databits, clock_div[, duplex_mode])`
#### Parameters
- `id` SPI ID number: 0 for SPI, 1 for HSPI
- `mode` select master or slave mode
- `spi.MASTER`
- `spi.SLAVE` - **not supported currently**
- `cpol` clock polarity selection
- `spi.CPOL_LOW`
- `spi.CPOL_HIGH` - **not supported currently**
- `cpha` clock phase selection
- `spi.CPHA_LOW`
- `spi.CPHA_HIGH`
- `databits` number of bits per data item 1 - 32
- `clock_div` SPI clock divider, f(SPI) = f(CPU) / `clock_div`
- `duplex_mode` duplex mode
- `spi.HALFDUPLEX` (default when omitted)
- `spi.FULLDUPLEX`
#### Returns
Number: 1
## Low Level Hardware Functions
The low level functions provide a hardware-centric API for application
scenarios that need to excercise more complex SPI transactions. The
programming model is built up around the HW send and receive buffers and SPI
transactions are initiated with full control over the hardware features.
## spi.get_miso()
Extract data items from MISO buffer after `spi.transaction()`.
#### Syntax
`data1[, data2[, ..., datan]] = spi.get_miso(id, offset, bitlen, num)`
#### Parameters
- `id` SPI ID number: 0 for SPI, 1 for HSPI
- `offset` bit offset into MISO buffer for first data item
- `bitlen` bit length of a single data item
- `num` number of data items to retrieve
####Returns
`num` data items
#### See also
[spi.transaction()](#spitransaction)
## spi.set_mosi()
Insert data items into MOSI buffer for `spi.transaction()`.
#### Syntax
`spi.set_mosi(id, offset, bitlen, data1[, data2[, ..., datan]])`
####Parameters
- `id` SPI ID number: 0 for SPI, 1 for HSPI
- `offset` bit offset into MOSI buffer for inserting data1 and subsequent items
- `bitlen` bit length of data1, data2, ...
- `data` data items where `bitlen` number of bits are considered for the transaction.
#### Returns
`nil`
#### See also
[spi.transaction()](#spitransaction)
## spi.transaction()
Start an SPI transaction, consisting of up to 5 phases:
1. Command
2. Address
3. MOSI
4. Dummy
5. MISO
#### Syntax
`spi.transaction(id, cmd_bitlen, cmd_data, addr_bitlen, addr_data, mosi_bitlen, dummy_bitlen, miso_bitlen)`
#### Parameters
- `id` SPI ID number: 0 for SPI, 1 for HSPI
- `cmd_bitlen` bit length of the command phase (0 - 16)
- `cmd_data` data for command phase
- `addr_bitlen` bit length for address phase (0 - 32)
- `addr_data` data for command phase
- `mosi_bitlen` bit length of the MOSI phase (0 - 512)
- `dummy_bitlen` bit length of the dummy phase (0 - 256)
- `miso_bitlen` bit length of the MISO phase (0 - 512) for half-duplex.<br />Full-duplex mode is activated with a negative value.
####Returns
`nil`
####See also
- [spi.set_mosi()](#spisetmosi)
- [spi.get_miso()](#spigetmiso)
# tmr Module
The tmr module allows access to simple timers, the system counter and uptime.
It is aimed at setting up regularly occurring tasks, timing out operations, and provide low-resolution deltas.
What the tmr module is *not* however, is a time keeping module. While most timeouts are expressed in milliseconds or even microseconds, the accuracy is limited and compounding errors would lead to rather inaccurate time keeping. Consider using the [rtctime](rtctime.md) module for "wall clock" time.
NodeMCU provides 7 timers, numbered 0-6. It is currently up to the user to keep track of which timers are used for what.
## tmr.alarm()
This is a convenience function combining [`tmr.register()`](#tmrregister) and [`tmr.start()`](#tmrstart) into a single call.
To free up the resources with this timer when done using it, call [`tmr.unregister()`](#tmrunregister) on it. For one-shot timers this is not necessary, unless they were stopped before they expired.
#### Parameters
- `id` timer id (0-6)
- `interval_ms` timer interval in milliseconds. Maximum value is 12884901. In SDKs <= 1.5.0 values >6871948 result in incorrect behaviour.
- `mode` timer mode:
- `tmr.ALARM_SINGLE` a one-shot alarm (and no need to call [`tmr.unregister()`](#tmrunregister))
- `tmr.ALARM_SEMI` manually repeating alarm (call [`tmr.start()`](#tmrstart) to restart)
- `tmr.ALARM_AUTO` automatically repeating alarm
#### Returns
`true` if the timer was started, `false` on error
#### Example
```lua
if not tmr.alarm(0, 5000, tmr.ALARM_SINGLE, function() print("hey there") end) then print("whoopsie") end
```
#### See also
- [`tmr.register()`](#tmrregister)
- [`tmr.start()`](#tmrstart)
- [`tmr.unregister()`](#tmrunregister)
## tmr.delay()
Busyloops the processor for a specified number of microseconds.
This is in general a **bad** idea, because nothing else gets to run, and the networking stack (and other things) can fall over as a result. The only time `tmr.delay()` may be appropriate to use is if dealing with a peripheral device which needs a (very) brief delay between commands, or similar. *Use with caution!*
Also note that the actual amount of time delayed for may be noticeably greater, both as a result of timing inaccuracies as well as interrupts which may run during this time.
#### Syntax
`tmr.delay(us)`
#### Parameters
`us` microseconds to busyloop for
#### Returns
`nil`
#### Example
```lua
tmr.delay(100)
```
## tmr.interval()
Changes a registered timer's expiry interval.
#### Syntax
`tmr.interval(id, interval_ms)`
#### Parameters
- `id` timer id (0-6)
- `interval_ms` new timer interval in milliseconds. Maximum value is 12884901. In SDKs <= 1.5.0 values >6871948 result in incorrect behaviour.
#### Returns
`nil`
#### Example
```lua
tmr.register(0, 5000, tmr.ALARM_SINGLE, function() print("hey there") end)
tmr.interval(0, 3000) -- actually, 3 seconds is better!
```
## tmr.now()
Returns the system counter, which counts in microseconds. Limited to 31 bits, after that it wraps around back to zero. That is essential if you use this function to [debounce or throttle GPIO input](https://github.com/hackhitchin/esp8266-co-uk/issues/2).
#### Syntax
`tmr.now()`
#### Parameters
none
#### Returns
the current value of the system counter
#### Example
```lua
print(tmr.now())
print(tmr.now())
```
## tmr.register()
Configures a timer and registers the callback function to call on expiry.
To free up the resources with this timer when done using it, call [`tmr.unregister()`](#tmrunregister) on it. For one-shot timers this is not necessary, unless they were stopped before they expired.
#### Syntax
`tmr.register(id, interval_ms, mode, func)`
#### Parameters
- `id` timer id (0-6)
- `interval_ms` timer interval in milliseconds. Maximum value is 12884901. In SDKs <= 1.5.0 values >6871948 result in incorrect behaviour.
- `mode` timer mode:
- `tmr.ALARM_SINGLE` a one-shot alarm (and no need to call [`tmr.unregister()`](#tmrunregister))
- `tmr.ALARM_SEMI` manually repeating alarm (call [`tmr.start()`](#tmrunregister) to restart)
- `tmr.ALARM_AUTO` automatically repeating alarm
Note that registering does *not* start the alarm.
#### Returns
`nil`
#### Example
```lua
tmr.register(0, 5000, tmr.ALARM_SINGLE, function() print("hey there") end)
tmr.start(0)
```
#### See also
[`tmr.alarm()`](#tmralarm)
## tmr.softwd()
Provides a simple software watchdog, which needs to be re-armed or disabled before it expires, or the system will be restarted.
#### Syntax
`tmr.softwd(timeout_s)`
#### Parameters
`timeout_s` watchdog timeout, in seconds. To disable the watchdog, use -1 (or any other negative value).
#### Returns
`nil`
#### Example
```lua
function on_success_callback()
tmr.softwd(-1)
print("Complex task done, soft watchdog disabled!")
end
tmr.softwd(5)
-- go off and attempt to do whatever might need a restart to recover from
complex_stuff_which_might_never_call_the_callback(on_success_callback)
```
## tmr.start()
Starts or restarts a previously configured timer.
#### Syntax
`tmr.start(id)`
#### Parameters
`id` timer id (0-6)
#### Returns
`true` if the timer was started, `false` on error
#### Example
```lua
tmr.register(0, 5000, tmr.ALARM_SINGLE, function() print("hey there") end)
if not tmr.start(0) then print("uh oh") end
```
#### See also
- [`tmr.register()`](#tmrregister)
- [`tmr.stop()`](#tmrstop)
- [`tmr.unregister()`](#tmrunregister)
## tmr.state()
Checks the state of a timer.
#### Syntax
`tmr.state(id)`
#### Parameters
`id` timer id (0-6)
#### Returns
(bool, int) or `nil`
If the specified timer is registered, returns whether it is currently started and its mode. If the timer is not registered, `nil` is returned.
#### Example
```lua
running, mode = tmr.state(0)
```
## tmr.stop()
Stops a running timer, but does *not* unregister it. A stopped timer can be restarted with [`tmr.start()`](#tmrstart).
#### Syntax
`tmr.stop(id)`
#### Parameters
`id` timer id (0-6)
#### Returns
`true` if the timer was stopped, `false` on error
#### Example
```lua
if not tmr.stop(2) then print("timer 2 not stopped, not registered?") end
```
#### See also
- [`tmr.register()`](#tmrregister)
- [`tmr.stop()`](#tmrstop)
- [`tmr.unregister()`](#tmrunregister)
## tmr.time()
Returns the system uptime, in seconds. Limited to 31 bits, after that it wraps around back to zero.
#### Syntax
`tmr.time()`
#### Parameters
none
#### Returns
the system uptime, in seconds, possibly wrapped around
#### Example
```lua
print("Uptime (probably):", tmr.time())
```
## tmr.unregister()
Stops the timer (if running) and unregisters the associated callback.
This isn't necessary for one-shot timers (`tmr.ALARM_SINGLE`), as those automatically unregister themselves when fired.
#### Syntax
`tmr.unregister(id)`
#### Parameters
`id` timer id (0-6)
#### Returns
`nil`
#### Example
```lua
tmr.unregister(0)
```
#### See also
[`tmr.register()`](#tmrregister)
## tmr.wdclr()
Feed the system watchdog.
*In general, if you ever need to use this function, you are doing it wrong.*
The event-driven model of NodeMCU means that there is no need to be sitting in hard loops waiting for things to occur. Rather, simply use the callbacks to get notified when somethings happens. With this approach, there should never be a need to manually feed the system watchdog.
#### Syntax
`tmr.wdclr()`
#### Parameters
none
#### Returns
`nil`
\ No newline at end of file
# TSL2561 Module
## tsl2561.getlux()
Reads sensor values from the device and returns calculated lux value.
#### Syntax
`tsl2561.getlux()`
#### Parameters
none
#### Returns
- `lux` the calculated illuminance in lux (lx)
- `status` value indicating success or failure as explained below:
* `tsl2561.TSL2561_OK`
* `tsl2561.TSL2561_ERROR_I2CINIT` can't initialize I²C bus
* `tsl2561.TSL2561_ERROR_I2CBUSY` I²C bus busy
* `tsl2561.TSL2561_ERROR_NOINIT` initialize I²C bus before calling function
* `tsl2561.TSL2561_ERROR_LAST`
#### Example
``` lua
status = tsl2561.init(5, 6, tsl2561.ADDRESS_FLOAT, tsl2561.PACKAGE_T_FN_CL)
if status == tsl2561.TSL2561_OK then
lux = tsl2561.getlux()
print("Illuminance: "..lux.." lx")
end
```
## tsl2561.getrawchannels()
Reads the device's 2 sensors and returns their values.
#### Syntax
`tsl2561.getrawchannels()`
#### Parameters
none
#### Returns
- `ch0` value of the broad spectrum sensor
- `ch1` value of the IR sensor
- `status` value indicating success or failure as explained below:
* `tsl2561.TSL2561_OK`
* `tsl2561.TSL2561_ERROR_I2CINIT` can't initialize I²C bus
* `tsl2561.TSL2561_ERROR_I2CBUSY` I²C bus busy
* `tsl2561.TSL2561_ERROR_NOINIT` initialize I²C bus before calling function
* `tsl2561.TSL2561_ERROR_LAST`
#### Example
``` lua
status = tsl2561.init(5, 6, tsl2561.ADDRESS_FLOAT, tsl2561.PACKAGE_T_FN_CL)
if status == tsl2561.TSL2561_OK then
ch0, ch1 = tsl2561.getrawchannels()
print("Raw values: "..ch0, ch1)
lux = tsl2561.getlux()
print("Illuminance: "..lux.." lx")
end
```
## tsl2561.init()
Initializes the device on pins sdapin & sclpin. Optionally also configures the devices address and package. Default: address pin floating (0x39) and FN package.
#### Syntax
` tsl2561.init(sdapin, sclpin[, address[, package]])`
#### Parameters
- `sdapin` pin number of the device's I²C sda connection
- `sclpin` pin number of the device's I²C scl connection
- `address` optional address of the device on the I²C bus
* `tsl2561.ADDRESS_GND`
* `tsl2561.ADDRESS_FLOAT` (default when omitted)
* `tsl2561.ADDRESS_VDD`
- `package` optional device's package type (slight difference in lux calculation)
* `tsl2561.PACKAGE_CS`
* `tsl2561.PACKAGE_T_FN_CL` (default when omitted)
#### Returns
`status` value indicating success or failure as explained below:
- `tsl2561.TSL2561_OK`
- `tsl2561.TSL2561_ERROR_I2CINIT` can't initialize I²C bus
- `tsl2561.TSL2561_ERROR_I2CBUSY` I²C bus busy
- `tsl2561.TSL2561_ERROR_NOINIT` Initialize I²C bus before calling function
- `tsl2561.TSL2561_ERROR_LAST`
#### Example
``` lua
status = tsl2561.init(5, 6, tsl2561.ADDRESS_FLOAT, tsl2561.PACKAGE_T_FN_CL)
if status == tsl2561.TSL2561_OK then
lux = tsl2561.getlux()
print("Illuminance: "..lux.." lx")
end
```
## tsl2561.settiming()
Sets the integration time and gain settings of the device. When `tls2561.init()` is called, these values default to 402 ms and no gain.
#### Syntax
`tsl2561.settiming(integration, gain)`
#### Parameters
- `integration` sets the device's integration period. Valid options are:
* `tsl2561.INTEGRATIONTIME_13MS`
* `tsl2561.INTEGRATIONTIME_101MS`
* `tsl2561.INTEGRATIONTIME_402MS` (default when omitted)
- `gain` sets the device's gain. Valid options are:
* `tsl2561.GAIN_1X` (default when omitted)
* `tsl2561.GAIN_16X`
#### Returns
`status` value indicating success or failure as explained below:
- `tsl2561.TSL2561_OK`
- `tsl2561.TSL2561_ERROR_I2CINIT` can't initialize I²C bus
- `tsl2561.TSL2561_ERROR_I2CBUSY` I²C bus busy
- `tsl2561.TSL2561_ERROR_NOINIT` initialize I²C bus before calling function
- `tsl2561.TSL2561_ERROR_LAST`
#### Example
``` lua
status = tsl2561.init(5, 6, tsl2561.ADDRESS_FLOAT, tsl2561.PACKAGE_T_FN_CL)
if status == tsl2561.TSL2561_OK then
status = tsl2561.settiming(tsl2561.INTEGRATIONTIME_101MS, tsl2561.GAIN_16X)
end
if status == tsl2561.TSL2561_OK then
lux = tsl2561.getlux()
print("Illuminance: "..lux.." lx")
end
```
\ No newline at end of file
# u8g Module
U8glib is a graphics library developed at [olikraus/u8glib](https://github.com/olikraus/u8glib) with support for many different displays. The NodeMCU firmware supports a subset of these.
I²C and SPI mode:
- sh1106_128x64
- ssd1306 - 128x64 and 64x48 variants
- ssd1309_128x64
- ssd1327_96x96_gr
- uc1611 - dogm240 and dogxl240 variants
SPI only:
- ld7032_60x32
- pcd8544_84x48
- pcf8812_96x65
- ssd1322_nhd31oled - bw and gr variants
- ssd1325_nhd27oled - bw and gr variants
- ssd1351_128x128 - gh and hicolor variants
- st7565_64128n - variants 64128n, dogm128/132, lm6059/lm6063, c12832/c12864
- uc1601_c128032
- uc1608 - 240x128 and 240x64 variants
- uc1610_dogxl160 - bw and gr variants
- uc1611 - dogm240 and dogxl240 variants
- uc1701 - dogs102 and mini12864 variants
This integration is based on [v1.18.1](https://github.com/olikraus/U8glib_Arduino/releases/tag/1.18.1).
## Overview
### I²C Connection
Hook up SDA and SCL to any free GPIOs. Eg. [u8g_graphics_test.lua](https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_examples/u8glib/u8g_graphics_test.lua) expects SDA=5 (GPIO14) and SCL=6 (GPIO12). They are used to set up nodemcu's I²C driver before accessing the display:
```lua
sda = 5
scl = 6
i2c.setup(0, sda, scl, i2c.SLOW)
```
### SPI connection
The HSPI module is used ([more information](http://d.av.id.au/blog/esp8266-hardware-spi-hspi-general-info-and-pinout/)), so certain pins are fixed:
- HSPI CLK = GPIO14
- HSPI MOSI = GPIO13
- HSPI MISO = GPIO12 (not used)
All other pins can be assigned to any available GPIO:
- CS
- D/C
- RES (optional for some displays)
Also refer to the initialization sequence eg in [u8g_graphics_test.lua](https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_examples/u8glib/u8g_graphics_test.lua):
```lua
spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, 8, 8)
```
### Library Usage
The Lua bindings for this library closely follow u8glib's object oriented C++ API. Based on the u8g class, you create an object for your display type.
SSD1306 via I²C:
```lua
sla = 0x3c
disp = u8g.ssd1306_128x64_i2c(sla)
```
SSD1306 via SPI:
```lua
cs = 8 -- GPIO15, pull-down 10k to GND
dc = 4 -- GPIO2
res = 0 -- GPIO16, RES is optional YMMV
disp = u8g.ssd1306_128x64_hw_spi(cs, dc, res)
```
This object provides all of u8glib's methods to control the display. Again, refer to [u8g_graphics_test.lua](https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_examples/u8glib/u8g_graphics_test.lua) to get an impression how this is achieved with Lua code. Visit the [u8glib homepage](https://github.com/olikraus/u8glib) for technical details.
### Displays
I²C and HW SPI based displays with support in u8glib can be enabled. To get access to the respective constructors, add the desired entries to the I²C or SPI display tables in [app/include/u8g_config.h](https://github.com/nodemcu/nodemcu-firmware/blob/master/app/include/u8g_config.h):
```c
#define U8G_DISPLAY_TABLE_I2C \
U8G_DISPLAY_TABLE_ENTRY(ssd1306_128x64_i2c) \
#define U8G_DISPLAY_TABLE_SPI \
U8G_DISPLAY_TABLE_ENTRY(ssd1306_128x64_hw_spi) \
U8G_DISPLAY_TABLE_ENTRY(pcd8544_84x48_hw_spi) \
U8G_DISPLAY_TABLE_ENTRY(pcf8812_96x65_hw_spi) \
```
### Fonts
u8glib comes with a wide range of fonts for small displays. Since they need to be compiled into the firmware image, you'd need to include them in [app/include/u8g_config.h](https://github.com/nodemcu/nodemcu-firmware/blob/master/app/include/u8g_config.h) and recompile. Simply add the desired fonts to the font table:
```c
#define U8G_FONT_TABLE \
U8G_FONT_TABLE_ENTRY(font_6x10) \
U8G_FONT_TABLE_ENTRY(font_chikita)
```
They'll become available as `u8g.<font_name>` in Lua.
### Bitmaps
Bitmaps and XBMs are supplied as strings to `drawBitmap()` and `drawXBM()`. This off-loads all data handling from the u8g module to generic methods for binary files. See [u8g_bitmaps.lua](https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_examples/u8glib/u8g_bitmaps.lua).
In contrast to the source code based inclusion of XBMs into u8glib, it's required to provide precompiled binary files. This can be performed online with [Online-Utility's Image Converter](http://www.online-utility.org/image_converter.jsp): Convert from XBM to MONO format and upload the binary result with [nodemcu-uploader.py](https://github.com/kmpm/nodemcu-uploader).
## I²C Display Drivers
Initialize a display via I²C.
- `u8g.sh1106_128x64_i2c()`
- `u8g.ssd1306_128x64_i2c()`
- `u8g.ssd1306_64x48_i2c()`
- `u8g.ssd1309_128x64_i2c()`
- `u8g.ssd1327_96x96_gr_i2c()`
- `u8g.uc1611_dogm240_i2c()`
- `u8g.uc1611_dogxl240_i2c()`
####Syntax
`u8g.ssd1306_128x64_i2c(address)`
####Parameters
`address` I²C slave address of display
####Returns
u8g display object
####Example
```lua
sda = 5
scl = 6
i2c.setup(0, sda, scl, i2c.SLOW)
sla = 0x3c
disp = u8g.ssd1306_128x64_i2c(sla)
```
####See also
[SPI Display Drivers](#spi-display-drivers)
## SPI Display Drivers
Initialize a display via Hardware SPI.
- `u8g.ld7032_60x32_hw_spi()`
- `u8g.pcd8544_84x48_hw_spi()`
- `u8g.pcf8812_96x65_hw_spi()`
- `u8g.sh1106_128x64_hw_spi()`
- `u8g.ssd1306_128x64_hw_spi()`
- `u8g.ssd1306_64x48_hw_spi()`
- `u8g.ssd1309_128x64_hw_spi()`
- `u8g.ssd1322_nhd31oled_bw_hw_spi()`
- `u8g.ssd1322_nhd31oled_gr_hw_spi()`
- `u8g.ssd1325_nhd27oled_bw_hw_spi()`
- `u8g.ssd1325_nhd27oled_gr_hw_spi()`
- `u8g.ssd1327_96x96_gr_hw_spi()`
- `u8g.ssd1351_128x128_332_hw_spi()`
- `u8g.ssd1351_128x128gh_332_hw_spi()`
- `u8g.ssd1351_128x128_hicolor_hw_spi()`
- `u8g.ssd1351_128x128gh_hicolor_hw_spi()`
- `u8g.ssd1353_160x128_332_hw_spi()`
- `u8g.ssd1353_160x128_hicolor_hw_spi()`
- `u8g.st7565_64128n_hw_spi()`
- `u8g.st7565_dogm128_hw_spi()`
- `u8g.st7565_dogm132_hw_spi()`
- `u8g.st7565_lm6059_hw_spi()`
- `u8g.st7565_lm6063_hw_spi()`
- `u8g.st7565_nhd_c12832_hw_spi()`
- `u8g.st7565_nhd_c12864_hw_spi()`
- `u8g.uc1601_c128032_hw_spi()`
- `u8g.uc1608_240x128_hw_spi()`
- `u8g.uc1608_240x64_hw_spi()`
- `u8g.uc1610_dogxl160_bw_hw_spi()`
- `u8g.uc1610_dogxl160_gr_hw_spi()`
- `u8g.uc1611_dogm240_hw_spi()`
- `u8g.uc1611_dogxl240_hw_spi()`
- `u8g.uc1701_dogs102_hw_spi()`
- `u8g.uc1701_mini12864_hw_spi()`
#### Syntax
`u8g.ssd1306_128x64_spi(cs, dc[, res])`
#### Parameters
- `cs` GPIO pin for /CS
- `dc` GPIO pin for DC
- `res` GPIO pin for /RES (optional)
#### Returns
u8g display object
#### Example
```lua
spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, 8, 8)
cs = 8 -- GPIO15, pull-down 10k to GND
dc = 4 -- GPIO2
res = 0 -- GPIO16, RES is optional YMMV
disp = u8g.ssd1306_128x64_hw_spi(cs, dc, res)
```
#### See also
[I²C Display Drivers](#i2c-display-drivers)
___
## Constants
Constants for various functions.
`u8g.DRAW_UPPER_RIGHT`, `u8g.DRAW_UPPER_LEFT`, `u8g.DRAW_LOWER_RIGHT`, `u8g.DRAW_LOWER_LEFT`, `u8g.DRAW_ALL`,
`u8g.MODE_BW`, `u8g.MODE_GRAY2BIT`
`u8g.font_6x10`, ...
# u8g.disp Sub-Module
## u8g.disp:begin()
See [u8glib begin()](https://github.com/olikraus/u8glib/wiki/userreference#begin).
## u8g.disp:drawBitmap()
Draw a bitmap at the specified x/y position (upper left corner of the bitmap).
Parts of the bitmap may be outside the display boundaries. The bitmap is specified by the array bitmap. A cleared bit means: Do not draw a pixel. A set bit inside the array means: Write pixel with the current color index. For a monochrome display, the color index 0 will usually clear a pixel and the color index 1 will set a pixel.
#### Syntax
`disp:drawBitmap(x, y, cnt, h, bitmap)`
#### Parameters
- `x` X-position (left position of the bitmap)
- `y` Y-position (upper position of the bitmap)
- `cnt` number of bytes of the bitmap in horizontal direction. The width of the bitmap is cnt*8.
- `h` height of the bitmap
- `bitmap` bitmap data supplied as string
#### Returns
`nil`
#### See also
- [u8glib drawBitmap()](https://github.com/olikraus/u8glib/wiki/userreference#drawbitmap)
- [lua_examples/u8glib/u8g_bitmaps.lua](https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_examples/u8glib/u8g_bitmaps.lua)
- [u8g.disp:drawXBM()](#u8gdispdrawxbm)
## u8g.disp:drawBox()
See [u8glib drawBox()](https://github.com/olikraus/u8glib/wiki/userreference#drawbox).
## u8g.disp:drawCircle()
See [u8glib drawCircle()](https://github.com/olikraus/u8glib/wiki/userreference#drawcircle).
## u8g.disp:drawDisc()
See [u8glib drawDisc()](https://github.com/olikraus/u8glib/wiki/userreference#drawdisc).
## u8g.disp:drawEllipse()
See [u8glib drawEllipse()](https://github.com/olikraus/u8glib/wiki/userreference#drawellipse).
## u8g.disp:drawFilledEllipse()
See [u8glib drawFilledEllipse](https://github.com/olikraus/u8glib/wiki/userreference#drawfilledellipse).
## u8g.disp:drawFrame()
See [u8glib drawFrame()](https://github.com/olikraus/u8glib/wiki/userreference#drawframe).
## u8g.disp:drawHLine()
See [u8glib drawHLine()](https://github.com/olikraus/u8glib/wiki/userreference#drawhline).
## u8g.disp:drawLine()
See [u8glib drawLine()](https://github.com/olikraus/u8glib/wiki/userreference#drawline).
## u8g.disp:drawPixel()
See [u8glib drawPixel()](https://github.com/olikraus/u8glib/wiki/userreference#drawpixel).
## u8g.disp:drawRBox()
See [u8glib drawRBox()](https://github.com/olikraus/u8glib/wiki/userreference#drawrbox).
## u8g.disp:drawRFrame()
See [u8glib drawRFrame()](https://github.com/olikraus/u8glib/wiki/userreference#drawrframe).
## u8g.disp:drawStr()
See [u8glib drawStr()](https://github.com/olikraus/u8glib/wiki/userreference#drawstr).
## u8g.disp:drawStr90()
See [u8glib drawStr90](https://github.com/olikraus/u8glib/wiki/userreference#drawstr90).
## u8g.disp:drawStr180()
See [u8glib drawStr180()](https://github.com/olikraus/u8glib/wiki/userreference#drawstr180).
## u8g.disp:drawStr270()
See [u8glib drawStr270()](https://github.com/olikraus/u8glib/wiki/userreference#drawstr270).
## u8g.disp:drawTriangle()
See [u8glib drawTriangle()](https://github.com/olikraus/u8glib/wiki/userreference#drawtriangle).
## u8g.disp:drawVLine()
See [u8glib drawVLine()](https://github.com/olikraus/u8glib/wiki/userreference#drawvline).
## u8g.disp:drawXBM()
Draw a XBM Bitmap. Position (x,y) is the upper left corner of the bitmap.
XBM contains monochrome, 1-bit bitmaps. This procedure only draws pixel values 1. The current color index is used for drawing (see setColorIndex). Pixel with value 0 are not drawn (transparent).
Bitmaps and XBMs are supplied as strings to `drawBitmap()` and `drawXBM()`. This off-loads all data handling from the u8g module to generic methods for binary files. In contrast to the source code based inclusion of XBMs into u8glib, it's required to provide precompiled binary files. This can be performed online with [Online-Utility's Image Converter](http://www.online-utility.org/image_converter.jsp): Convert from XBM to MONO format and upload the binary result with [nodemcu-uploader.py](https://github.com/kmpm/nodemcu-uploader) or [ESPlorer](http://esp8266.ru/esplorer/).
#### Syntax
`disp:drawXBM(x, y, w, h, bitmap)`
#### Parameters
- `x` X-position (left position of the bitmap)
- `y` Y-position (upper position of the bitmap)
- `w` width of the bitmap
- `h` height of the bitmap
- `bitmap` XBM data supplied as string
#### Returns
`nil`
#### See also
- [u8glib drawXBM()](https://github.com/olikraus/u8glib/wiki/userreference#drawxbm)
- [lua_examples/u8glib/u8g_bitmaps.lua](https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_examples/u8glib/u8g_bitmaps.lua)
- [u8g.disp:drawBitmap()](#u8gdispdrawbitmap)
## u8g.disp:firstPage()
See [u8glib firstPage()](https://github.com/olikraus/u8glib/wiki/userreference#firstpage).
## u8g.disp:getColorIndex()
See [u8glib getColorIndex()](https://github.com/olikraus/u8glib/wiki/userreference#getcolorindex).
## u8g.disp:getFontAscent()
See [u8glib getFontAscent()](https://github.com/olikraus/u8glib/wiki/userreference#getfontascent).
## u8g.disp:getFontDescent()
See [u8glib getFontDescent()](https://github.com/olikraus/u8glib/wiki/userreference#getfontdescent).
## u8g.disp:getFontLineSpacing()
See [u8glib getFontLineSpacing()](https://github.com/olikraus/u8glib/wiki/userreference#getfontlinespacing).
## u8g.disp:getHeight()
See [u8glib getHeight()](https://github.com/olikraus/u8glib/wiki/userreference#getheight).
## u8g.disp:getMode()
See [u8glib getMode()](https://github.com/olikraus/u8glib/wiki/userreference#getmode).
## u8g.disp:getWidth()
See [u8glib getWidth()](https://github.com/olikraus/u8glib/wiki/userreference#getwidth).
## u8g.disp:getStrWidth()
See [u8glib getStrWidth](https://github.com/olikraus/u8glib/wiki/userreference#getstrwidth).
## u8g.disp:nextPage()
See [u8glib nextPage()(https://github.com/olikraus/u8glib/wiki/userreference#nextpage).
## u8g.disp:setColorIndex()
See [u8glib setColorIndex()](https://github.com/olikraus/u8glib/wiki/userreference#setcolortndex).
## u8g.disp:setDefaultBackgroundColor()
See [u8glib setDefaultBackgroundColor()](https://github.com/olikraus/u8glib/wiki/userreference#setdefaultbackgroundcolor).
## u8g.disp:setDefaultForegroundColor()
See [u8glib setDefaultForegroundColor()](https://github.com/olikraus/u8glib/wiki/userreference#setdefaultforegroundcolor).
## u8g.disp:setFont()
u8glib comes with a wide range of fonts for small displays.
Since they need to be compiled into the firmware image, you'd need to include them in `app/include/u8g_config.h` and recompile. Simply add the desired fonts to the font table:
```c
#define U8G_FONT_TABLE \
U8G_FONT_TABLE_ENTRY(font_6x10) \
U8G_FONT_TABLE_ENTRY(font_chikita)
```
They'll be available as `u8g.<font_name>` in Lua.
#### Syntax
`disp:setFont(font)`
#### Parameters
`font` Constant to indentify pre-compiled font
#### Returns
`nil`
#### Example
```lua
disp:setFont(u8g.font_6x10)
```
#### See also
- [u8glib setFont()](https://github.com/olikraus/u8glib/wiki/userreference#setfont)
## u8g.disp:setFontLineSpacingFactor()
See [u8glib setFontLineSpacingFactor()](https://github.com/olikraus/u8glib/wiki/userreference#setfontlinespacingfactor).
## u8g.disp:setFontPosBaseline()
See [u8glib setFontPosBaseline()](https://github.com/olikraus/u8glib/wiki/userreference#setfontposbaseline).
## u8g.disp:setFontPosBottom()
See [u8glib setFontPosBottom()](https://github.com/olikraus/u8glib/wiki/userreference#setfontposbottom).
## u8g.disp:setFontPosCenter()
See [u8glib setFontPosCenter()](https://github.com/olikraus/u8glib/wiki/userreference#setfontposcenter).
## u8g.disp:setFontPosTop()
See [u8glib setFontPosTop()](https://github.com/olikraus/u8glib/wiki/userreference#setfontpostop).
## u8g.disp:setFontRefHeightAll()
See [u8glib setFontRefHeightAll()](https://github.com/olikraus/u8glib/wiki/userreference#setfontrefheightall).
## u8g.disp:setFontRefHeightExtendedText()
See [u8glib setFontRefHeightExtendedText()](https://github.com/olikraus/u8glib/wiki/userreference#setfontrefheightextendedtext).
## u8g.disp:setFontRefHeightText()
See [u8glib setFontRefHeightText()](https://github.com/olikraus/u8glib/wiki/userreference#setfontrefheighttext).
## u8g.disp:setRot90()
See [u8glib setRot90()](https://github.com/olikraus/u8glib/wiki/userreference#setrot90).
## u8g.disp:setRot180()
See [u8glib setRot180()](https://github.com/olikraus/u8glib/wiki/userreference#setrot180).
## u8g.disp:setRot270()
See [u8glib setRot270()](https://github.com/olikraus/u8glib/wiki/userreference#setrot270).
## u8g.disp:setScale2x2()
See [u8glib setScale2x2()](https://github.com/olikraus/u8glib/wiki/userreference#setscale2x2).
## u8g.disp:sleepOn()
See [u8glib sleepOn()](https://github.com/olikraus/u8glib/wiki/userreference#sleepon).
## u8g.disp:sleepOff()
See [u8glib sleepOff()](https://github.com/olikraus/u8glib/wiki/userreference#sleepoff).
## u8g.disp:undoRotation()
See [u8glib undoRotation()](https://github.com/olikraus/u8glib/wiki/userreference#undorotation).
## u8g.disp:undoScale()
See [u8glib undoScale()](https://github.com/olikraus/u8glib/wiki/userreference#undoscale).
## Unimplemented Functions
- Cursor handling
- disableCursor()
- enableCursor()
- setCursorColor()
- setCursorFont()
- setCursorPos()
- setCursorStyle()
- General functions
- setContrast()
- setPrintPos()
- setHardwareBackup()
- setRGB()
- setDefaultMidColor()
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
# 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.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment