### Start Captive Portal with Callbacks Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/enduser-setup.md This example shows how to start the captive portal with optional parameters for the AP SSID, a connected callback, an error callback, and a debug callback. The `print` function is used as a simple debug callback. ```lua enduser_setup.start( function() print("Connected to WiFi as:" .. wifi.sta.getip()) end, function(err, str) print("enduser_setup: Err #" .. err .. ": " .. str) end, print -- Lua print function can serve as the debug callback ) ``` -------------------------------- ### sobj:setup() Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/lua-modules/bme280.md Re-initializes the sensor using the same parameters as the initial setup. ```APIDOC ### sobj:setup() Re-initializes the sensor. ### Parameters Parameters are the same as for the [bme280.setup](#bme280setup) function. ### Return Returned values are the same as for the [bme280.setup](#bme280setup) function. ``` -------------------------------- ### Build NodeMCU Firmware with Make Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/build.md Use this command to start the build process in a native Linux environment. The default setup minimizes output verbosity. ```bash make ``` -------------------------------- ### Initial Page Load and Setup Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/app/modules/enduser_setup/enduser_setup.html Sets up event listeners and initiates the first status and network scan upon page load. Handles URL parameters to potentially start in a specific state. ```javascript window.onload = function() { let trying = $.urlParam('trying'); ab.innerText = 'Scan for Networks'; ab.onclick = refrAp; $('#aplist').onchange = function () { $('#ssid').value = $('#aplist').value; let pw = $('#wifi_password'); if ($('#aplist').selectedOptions[0].dataset.auth > 0) { pw.placeholder = "Password"; pw.disabled = false; pw.required = true; } else { pw.placeholder = "Open -- no password"; pw.disabled = true; pw.required = false; } }; $('#bk2').onclick = function () { cur('#f1') } rs = to(refr, 0.5); if( trying ) cur("#f3"); refrAp(); } ``` -------------------------------- ### Full Redis Example Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/lua-modules/redis.md A comprehensive example demonstrating connecting to Redis, publishing a message, and subscribing to a channel to receive and print messages. ```lua local redis = dofile("redis.lua").connect(host, port) redis:publish("chan1", "foo") redis:subscribe("chan1", function(channel, msg) print(channel, msg) end) ``` -------------------------------- ### Setup and Example Usage of DCC Module Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/dcc.md This snippet demonstrates how to set up the DCC module with a specific pin, a command callback, and a CV callback. It also shows how to define CV values and handle different DCC commands like turnout, speed, and function commands. The `bit` module is used for bitwise operations on the accessory decoder address. ```lua local PIN = 2 -- GPIO4 local addr = 0x12a CV = {[29]=0, [1]=bit.band(addr, 0x3f), --CV_ACCESSORY_DECODER_ADDRESS_LSB (6 bits) [9]=bit.band(bit.rshift(addr,6), 0x7) --CV_ACCESSORY_DECODER_ADDRESS_MSB (3 bits) } local function DCC_command(cmd, params) if cmd == dcc.DCC_IDLE then return elseif cmd == dcc.DCC_TURNOUT then print("Turnout command") elseif cmd == dcc.DCC_SPEED then print("Speed command") elseif cmd == dcc.DCC_FUNC then print("Function command") else print("Other command", cmd) end for i,j in pairs(params) do print(i, j) end print(("="):rep(80)) end local function CV_callback(operation, param) local oper = "" local result if operation == dcc.CV_WRITE then oper = "Write" CV[param.CV]=param.Value elseif operation == dcc.CV_READ then oper = "Read" result = CV[param.CV] elseif operation == dcc.CV_VALID then oper = "Valid" result = 1 elseif operation == CV_RESET then oper = "Reset" CV = {} end print(('[CV_callback] %s CV %d%s'):format(oper, param.CV or `nil`, param.Value and "\tValue: "..param.Value or "\tValue: nil")) return result end dcc.setup(PIN, DCC_command, dcc.MAN_ID_DIY, 1, --bit.bor(dcc.FLAGS_AUTO_FACTORY_DEFAULT, dcc.FLAGS_DCC_ACCESSORY_DECODER, dcc.FLAGS_MY_ADDRESS_ONLY), bit.bor(dcc.FLAGS_AUTO_FACTORY_DEFAULT), 0, -- ??? CV_callback) ``` -------------------------------- ### Start SmartConfig for WiFi Setup Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/wifi.md Initiates the SmartConfig process to automatically set up the WiFi SSID and password. This is intended for use with companion mobile apps and requires SmartConfig to be enabled in the firmware build. ```lua wifi.setmode(wifi.STATION) wifi.startsmart(0, function(ssid, password) print(string.format("Success. SSID:%s ; PASSWORD:%s", ssid, password)) end ) ``` -------------------------------- ### Install esptool.py Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/getting-started.md Install the esptool.py utility and its dependency pySerial using pip. This is the recommended tool for flashing firmware to ESPxxx chips. ```bash $ pip install esptool ``` -------------------------------- ### Start and Stop Performance Monitoring Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/perf.md Starts a performance monitoring session, runs a loop, and then stops the session to retrieve and print the performance histogram. This example demonstrates basic usage for identifying CPU time spent in different code sections. ```lua perf.start() for j = 0, 100 do str = "str"..j end tot, out, tbl, binsize = perf.stop() print(tot, out) local keyset = {} local n = 0 for k,v in pairs(tbl) do n=n+1 keyset[n]=k end table.sort(keyset) for kk,k in ipairs(keyset) do print(string.format("%x - %x",k, k + binsize - 1),tbl[k]) end ``` -------------------------------- ### Example: Creating and Populating a SPIFFS Image Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/spiffs.md This example demonstrates how to create a SPIFFS disk image and import files into it using the spiffsimg tool interactively. It shows importing Lua scripts and HTML files, followed by listing the contents. ```bash # spiffsimg -f flash.img -S 32m -U 524288 -i > import myapp/lua/init.lua init.lua > import myapp/lua/httpd.lua httpd.lua > import myapp/html/index.html http/index.html > import myapp/html/favicon.ico http/favicon.ico > ls f 122 init.lua f 5169 httpd.lua f 2121 http/index.html f 880 http/favicon.ico >^D # ``` -------------------------------- ### Configure and Start Gossip Service Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/lua-modules/gossip.md Sets up the gossip module with a seed list and debug options, then starts the service. Ensure the 'gossip' module is required before calling this configuration. ```lua config = { seedList = { '192.168.0.1', '192.168.0.15' }, debug = true, debugOutput = print } gossip = require ("gossip") gossip.setConfig(config) gossip.start() ``` -------------------------------- ### Full WPS Example with Retries and Event Monitoring Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/wps.md This comprehensive example shows how to use WPS with event monitoring for station connection and IP acquisition. It includes a retry mechanism for WPS failures and a callback function to manage the WPS process, including retries on failure, timeout, or scan errors. The example also registers event handlers for station connection and IP assignment. ```lua do -- Register wifi station event callbacks wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T) print("\n\tSTA - CONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: ".. T.BSSID.."\n\tChannel: "..T.channel) end) wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T) print("\n\tSTA - GOT IP".."\n\tStation IP: "..T.IP.."\n\tSubnet mask: ".. T.netmask.."\n\tGateway IP: "..T.gateway) end) wifi.setmode(wifi.STATION) wps_retry_func = function() if wps_retry_count == nil then wps_retry_count = 0 end if wps_retry_count < 3 then wps.disable() wps.enable() wps_retry_count = wps_retry_count + 1 wps_retry_timer = tmr.create() wps_retry_timer:alarm(3000, tmr.ALARM_SINGLE, function() wps.start(wps_cb) end) print("retry #"..wps_retry_count) else wps_retry_count = nil wps_retry_timer = nil wps_retry_func = nil wps_cb = nil end end wps_cb = function(status) if status == wps.SUCCESS then wps.disable() print("WPS: success, connecting to AP...") wifi.sta.connect() wps_retry_count = nil wps_retry_timer = nil wps_retry_func = nil wps_cb = nil return elseif status == wps.FAILED then print("WPS: Failed") wps_retry_func() return elseif status == wps.TIMEOUT then print("WPS: Timeout") wps_retry_func() return elseif status == wps.WEP then print("WPS: WEP not supported") elseif status == wps.SCAN_ERR then print("WPS: AP not found") wps_retry_func() return else print(status) end wps.disable() wps_retry_count = nil wps_retry_timer = nil wps_retry_func = nil wps_cb = nil end wps.enable() wps.start(wps_cb) end ``` -------------------------------- ### Install esptool for Python 2.7 Source: https://github.com/nodemcu/nodemcu-firmware/wiki/Windows-Docker-LFS-esptool-ESPlorer-Workflow-Cheat-Sheet Installs the esptool utility for Python 2.7. Navigate to the scripts directory before running. ```bash - cd C:\python27\scripts - pip install esptool ``` -------------------------------- ### Enable and Start WPS Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/wps.md This snippet demonstrates the basic usage of enabling WPS and starting the process. It includes a callback to handle the WPS status and attempts to connect to the AP upon success. WPS is disabled after the process completes. ```lua wifi.setmode(wifi.STATION) wps.enable() wps.start(function(status) if status == wps.SUCCESS then wps.disable() print("WPS: Success, connecting to AP...") wifi.sta.connect() return elseif status == wps.FAILED then print("WPS: Failed") elseif status == wps.TIMEOUT then print("WPS: Timeout") elseif status == wps.WEP then print("WPS: WEP not supported") elseif status == wps.SCAN_ERR then print("WPS: AP not found") else print(status) end wps.disable() end) ``` -------------------------------- ### Create and Use CoAP Client Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/coap.md Demonstrates creating a CoAP client instance and issuing GET and POST requests to a server. Note that GET request results are only printed to the console. ```lua cc = coap.Client() -- assume there is a coap server at ip 192.168.100 cc:get(coap.CON, "coap://192.168.18.100:5683/.well-known/core") -- GET is not complete, the result/payload only print out in console. cc:post(coap.NON, "coap://192.168.18.100:5683/", "Hello") ``` -------------------------------- ### Enable Manual AP Configuration and Start Captive Portal Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/enduser-setup.md This snippet demonstrates how to manually configure an access point using `wifi.setmode` and `wifi.ap.config`, then enables manual mode for the `enduser_setup` module. Finally, it starts the captive portal and defines callbacks for successful connection and error handling. ```lua wifi.setmode(wifi.STATIONAP) wifi.ap.config({ssid="MyPersonalSSID", auth=wifi.OPEN}) enduser_setup.manual(true) enduser_setup.start( function() print("Connected to WiFi as:" .. wifi.sta.getip()) end, function(err, str) print("enduser_setup: Err #" .. err .. ": " .. str) end ) ``` -------------------------------- ### Start Playback with Specific Rate Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/pcm.md Starts audio playback at a specified sample rate. Supported rates include pcm.RATE_1K, pcm.RATE_2K, pcm.RATE_4K, pcm.RATE_5K, pcm.RATE_8K, pcm.RATE_10K, pcm.RATE_12K, and pcm.RATE_16K. ```lua drv:play(pcm.RATE_16K) ``` -------------------------------- ### wifi.ap.dhcp.start Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/wifi.md Starts the DHCP service. ```APIDOC ## wifi.ap.dhcp.start() ### Description Starts the DHCP service. ### Parameters none ### Returns - `boolean` - `true` indicating success, `false` otherwise. ``` -------------------------------- ### pwm.start() Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/pwm.md Starts the PWM output waveform on the specified GPIO pin. ```APIDOC ## pwm.start() ### Description PWM starts, the waveform is applied to the GPIO pin. ### Syntax `pwm.start(pin)` ### Parameters * `pin` (number) - Required - IO index (1-12) ### Returns * `nil` ### See also * [pwm.stop()](#pwmstop) ``` -------------------------------- ### enduser_setup.start() Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/enduser-setup.md Starts the captive portal. If the module is already running, stop() will be invoked first. Allows for optional AP SSID, and callbacks for connection success, errors, and debugging. ```APIDOC ## enduser_setup.start() ### Description Starts the captive portal. Note: Calling start() while EUS is already running is an error, and will result in stop() to be invoked to shut down EUS. ### Syntax `enduser_setup.start([AP_SSID,] [onConnected()], [onError(err_num, string)], [onDebug(string)])` ### Parameters #### Parameters - `AP_SSID` (string) - Optional - The SSID to use for the AP. Defaults to `NodeMCU_`. - `onConnected()` (function) - Callback fired when an IP-address has been obtained, just before the enduser_setup module will terminate itself. - `onError(err_num, string)` (function) - Callback fired if an error is encountered. `err_num` is a number describing the error, and `string` contains a description of the error. - `onDebug(string)` (function) - Callback disabled by default (controlled by `#define ENDUSER_SETUP_DEBUG_ENABLE` in `enduser_setup.c`). Intended to be used to find internal issues in the module. `string` contains a description of what is going on. ### Returns `nil` ### Example ```lua enduser_setup.start( function() print("Connected to WiFi as:" .. wifi.sta.getip()) end, function(err, str) print("enduser_setup: Err #" .. err .. ": " .. str) end, print -- Lua print function can serve as the debug callback ) ``` ``` -------------------------------- ### tz.getoffset() Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/lua_examples/timezone/README.md Gets the timezone offset in seconds for a given time, along with the start and end times of that offset. ```APIDOC ## tz.getoffset() ### Description Gets the offset (in seconds) of the time passed as the argument. ### Syntax tz.getoffset(time) ### Parameters #### Path Parameters * **time** (number) - Required - The number of seconds since the epoch (same value as used by the `sntp` module). ### Returns * **number** - The number of seconds of offset. West of Greenwich is negative. * **number** - The start time (in epoch seconds) of this offset. * **number** - The end time (in epoch seconds) of this offset. ### Example ```lua tz = require('tz') tz.setzone('eastern') sntp.sync(nil, function(now) local tm = rtctime.epoch2cal(now + tz.getoffset(now)) print(string.format("%04d/%02d/%02d %02d:%02d:%02d", tm["year"], tm["mon"], tm["day"], tm["hour"], tm["min"], tm["sec"])) end) ``` ``` -------------------------------- ### node.startup() Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/node.md Get or set options that control the NodeMCU startup process. This includes options for displaying a startup banner, setting the initial CPU frequency, delaying SPIFFS filesystem mounting, and specifying an initial command to run. ```APIDOC ## node.startup() Get/set options that control the startup process. This interface will grow over time. #### Syntax `node.startup([{table}])` #### Parameters If the argument is omitted, then no change is made to the current set of startup options. If the argument is the empty table `{}` then all options are reset to their default values. - `table` one or more options: - `banner` - set to true or false to indicate whether the startup banner should be displayed or not. (default: true) - `frequency` - set to node.CPU80MHZ or node.CPU160MHZ to indicate the initial CPU speed. (default: node.CPU80MHZ) - `delay_mount` - set to true or false to indicate whether the SPIFFS filesystem mount is delayed until it is first needed or not. (default: false) - `command` - set to a string which is the initial command that is run. This is the same string as in the `node.startupcommand`. #### Returns `table` This is the complete set of options in the state that will take effect on the next boot. Note that the `command` key may be missing -- in which case the default value will be used. #### Example ```lua node.startup({banner=false, frequency=node.CPU160MHZ}) -- Prevent printing the banner and run at 160MHz ``` ``` -------------------------------- ### HTML for Custom End-User Setup Page Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/enduser-setup.md If `enduser_setup.html` exists on the filesystem, it will be served. This file should contain all necessary HTML, CSS, and JavaScript. It can be gzipped for smaller size, and the module will add the `Content-Encoding` header. ```html ``` -------------------------------- ### Get Partition Table Information Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/node.md Retrieves LFS and SPIFFS partition information, including addresses and sizes. The example prints the LFS size. ```lua print("The LFS size is " .. node.getpartitiontable().lfs_size) ``` -------------------------------- ### Execute Startup Command from File Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/node.md Sets a command to be executed on NodeMCU startup, specifying a compiled Lua file (.lc) to run. ```lua node.startupcommand("@myappstart.lc") -- Execute the compiled file myappstart.lc on startup ``` -------------------------------- ### BME280 Setup with Custom Parameters Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/bme280.md Configures the BME280 sensor with specific oversampling, mode, duration, and filter settings. This example uses 'game mode' settings. ```lua bme280.setup(1, 3, 0, 3, 0, 4) ``` -------------------------------- ### NodeMCU init.lua Example for WiFi Connection and Startup Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/upload.md This Lua script configures WiFi connection, handles connection events, and sets up a delayed startup sequence for the main application. It includes error handling for connection failures and a mechanism to abort startup within a short window. ```lua -- load credentials, 'SSID' and 'PASSWORD' declared and initialize in there dofile("credentials.lua") function startup() if file.open("init.lua") == nil then print("init.lua deleted or renamed") else print("Running") file.close("init.lua") -- the actual application is stored in 'application.lua' -- dofile("application.lua") end end -- Define WiFi station event callbacks wifi_connect_event = function(T) print("Connection to AP("..T.SSID.." ) established!") print("Waiting for IP address...") if disconnect_ct ~= nil then disconnect_ct = nil end end wifi_got_ip_event = function(T) -- Note: Having an IP address does not mean there is internet access! -- Internet connectivity can be determined with net.dns.resolve(). print("Wifi connection is ready! IP address is: "..T.IP) print("Startup will resume momentarily, you have 3 seconds to abort.") print("Waiting...") tmr.create():alarm(3000, tmr.ALARM_SINGLE, startup) end wifi_disconnect_event = function(T) if T.reason == wifi.eventmon.reason.ASSOC_LEAVE then --the station has disassociated from a previously connected AP return end -- total_tries: how many times the station will attempt to connect to the AP. Should consider AP reboot duration. local total_tries = 75 print("\nWiFi connection to AP("..T.SSID.." ) has failed!") --There are many possible disconnect reasons, the following iterates through --the list and returns the string corresponding to the disconnect reason. for key,val in pairs(wifi.eventmon.reason) do if val == T.reason then print("Disconnect reason: "..val.."("..key.." )") break end end if disconnect_ct == nil then disconnect_ct = 1 else disconnect_ct = disconnect_ct + 1 end if disconnect_ct < total_tries then print("Retrying connection...(attempt "..(disconnect_ct+1).." of "..total_tries..")") else wifi.sta.disconnect() print("Aborting connection to AP!") disconnect_ct = nil end end -- Register WiFi Station event callbacks wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, wifi_connect_event) wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, wifi_got_ip_event) wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, wifi_disconnect_event) print("Connecting to WiFi access point...") wifi.setmode(wifi.STATION) wifi.sta.config({ssid=SSID, pwd=PASSWORD}) -- wifi.sta.connect() not necessary because config() uses auto-connect=true by default ``` -------------------------------- ### Sleep for 5 seconds without RF wakeup Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/rtctime.md Use rtctime.dsleep with an option to prevent the RF module from starting upon wakeup. This example sleeps for 5 seconds. ```lua -- sleep for 5 seconds, do not start RF on wakeup rtctime.dsleep(5000000, 4) ``` -------------------------------- ### l3g4200d.setup() Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/l3g4200d.md Initializes the L3G4200D gyroscope module. ```APIDOC ## l3g4200d.setup() ### Description Initializes the module. ### Syntax l3g4200d.setup() ### Parameters None ### Returns `nil` ``` -------------------------------- ### si7021.setup() Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/si7021.md Initializes the Si7021 device on the I²C bus at the default address (0x40). This function should be called once before using other module functions. ```APIDOC ## si7021.setup() ### Description Initializes the device on fixed I²C device address (0x40). ### Syntax `si7021.setup()` ### Parameters none ### Returns `nil` ### Example ```lua local sda, scl = 6, 5 i2c.setup(0, sda, scl, i2c.SLOW) -- call i2c.setup() only once si7021.setup() ``` ``` -------------------------------- ### Get file attributes Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/file.md This example retrieves and prints various attributes of a file, including its name, size, timestamp, and type (file or directory), as well as read-only and hidden status. ```lua s = file.stat("/SD0/myfile") print("name: " .. s.name) print("size: " .. s.size) t = s.time print(string.format("%02d:%02d:%02d", t.hour, t.min, t.sec)) print(string.format("%04d-%02d-%02d", t.year, t.mon, t.day)) if s.is_dir then print("is directory") else print("is file") end if s.is_rdonly then print("is read-only") else print("is writable") end if s.is_hidden then print("is hidden") else print("is not hidden") end if s.is_sys then print("is system") else print("is not system") end if s.is_arch then print("is archive") else print("is not archive") end s = nil t = nil ``` -------------------------------- ### ow.setup() Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/ow.md Sets a specified pin to operate in one-wire mode, preparing it for communication with 1-Wire devices. ```APIDOC ## ow.setup() ### Description Sets a pin in onewire mode. ### Syntax `ow.setup(pin)` ### Parameters * `pin` (number) - Required - 1~12, I/O index ### Returns `nil` ``` -------------------------------- ### i2c.setup() Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/i2c.md Initializes the I2C bus with a specified bus ID, SDA and SCL pins, and the desired communication speed. ```APIDOC ## i2c.setup() ### Description Initialize the I2C bus with the selected bus number, pins and speed. ### Syntax i2c.setup(id, pinSDA, pinSCL, speed) ### Parameters - `id` (number) - bus number - `pinSDA` (number) - GPIO pin number for SDA - `pinSCL` (number) - GPIO pin number for SCL - `speed` (number) - communication speed (e.g., `i2c.STANDARD`, `i2c.FAST`, `i2c.FASTPLUS`) ``` -------------------------------- ### Get Software Version Information Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/node.md Retrieves software version details, including Git branch, commit ID, release tag, and commit timestamp. The example specifically prints the Git release tag. ```lua print(node.info("sw_version").git_release) ``` -------------------------------- ### BME680 Sensor Setup and Data Reading Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/bme680.md Initializes the I2C interface and the BME680 sensor, then starts a readout process. This snippet is used for obtaining temperature, pressure, humidity, gas resistance, and QNH values from the sensor. ```lua alt=320 -- altitude of the measurement place sda, scl = 3, 4 i2c.setup(0, sda, scl, i2c.SLOW) -- call i2c.setup() only once bme680.setup() -- delay calculated by formula provided by Bosch: 121 ms, minimum working (empirical): 150 ms bme680.startreadout(150, function () T, P, H, G, QNH = bme680.read(alt) if T then local Tsgn = (T < 0 and -1 or 1); T = Tsgn*T print(string.format("T=%s%d.%02d", Tsgn<0 and "-" or "", T/100, T%100)) print(string.format("QFE=%d.%03d", P/100, P%100)) print(string.format("QNH=%d.%03d", QNH/100, QNH%100)) print(string.format("humidity=%d.%03d%%", H/1000, H%1000)) print(string.format("gas resistance=%d", G)) D = bme680.dewpoint(H, T) local Dsgn = (D < 0 and -1 or 1); D = Dsgn*D print(string.format("dew_point=%s%d.%02d", Dsgn<0 and "-" or "", D/100, D%100)) end end) ``` -------------------------------- ### Write Data to I2C Device Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/i2c.md Writes data to an I2C device. This example defines a helper function to send a start condition, set the device address, write a register address, write the data, and send a stop condition. It demonstrates writing a single byte and a string. ```lua id = 0 sda = 1 scl = 2 -- initialize i2c, set pin 1 as sda, set pin 2 as scl i2c.setup(id, sda, scl, i2c.FAST) -- user defined function: write some data to device -- with address dev_addr starting from reg_addr function write_reg(id, dev_addr, reg_addr, data) i2c.start(id) i2c.address(id, dev_addr, i2c.TRANSMITTER) i2c.write(id, reg_addr) c = i2c.write(id, data) i2c.stop(id) return c end -- set register with address 0x45 of device 0x77 with value 1 count = write_reg(id, 0x77, 0x45, 1) print(count, " bytes written") -- write text into i2c EEPROM starting with memory address 0 count = write_reg(id, 0x50, 0, "Sample") print(count, " bytes written") ``` -------------------------------- ### dcc.setup() Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/dcc.md Initializes the DCC module and links callback functions for handling DCC commands and CV operations. ```APIDOC ## dcc.setup() ### Description Initializes the dcc module and links callback functions. ### Syntax `dcc.setup(Pin, [AckPin, ] DCC_command, ManufacturerId, VersionId, Flags, OpsModeAddressBaseCV [, CV_table] [, CV_callback])` ### Parameters - `Pin` (number) - The GPIO pin number connected to the DCC detector (must be interrupt capable pin). - `AckPin` (number) - Optional. The GPIO pin number connected to the ACK mechanism. Will be set HIGH to signal an ACK. - `DCC_command` (function) - Callback function that is called when a DCC command is decoded. `cmd` parameters is one of the following values. `params` contains a collection of parameters specific to given command. - `dcc.DCC_RESET`: no additional parameters, `params` is `nil`. - `dcc.DCC_IDLE`: no additional parameters, `params` is `nil`. - `dcc.DCC_SPEED`: parameters collection members are `Addr`, `AddrType`, `Speed`, `Dir`, `SpeedSteps`. - `dcc.DCC_SPEED_RAW`: parameters collection members are `Addr`, `AddrType`, `Raw`. - `dcc.DCC_FUNC`: parameters collection members are `Addr`, `AddrType`, `FuncGrp`, `FuncState`. - `dcc.DCC_TURNOUT`: parameters collection members are `BoardAddr`, `OutputPair`, `Direction`, `OutputPower` or `Addr`, `Direction`, `OutputPower`. - `dcc.DCC_ACCESSORY`: parameters collection has one member `BoardAddr` or `Addr` or `State`. - `dcc.DCC_RAW`: parameters collection member are `Size`, `PreambleBits`, `Data1` to `Data6`. - `dcc.DCC_SERVICEMODE`: parameters collection has one member `InServiceMode`. - `ManufacturerId` (number) - Manufacturer ID returned in CV 8. Commonly `dcc.MAN_ID_DIY`. - `VersionId` (number) - Version ID returned in CV 7. - `Flags` (number) - One of or combination (OR operator) of: - `dcc.FLAGS_MY_ADDRESS_ONLY`: Only process packets with My Address. - `dcc.FLAGS_DCC_ACCESSORY_DECODER`: Decoder is an accessory decode. - `dcc.FLAGS_OUTPUT_ADDRESS_MODE`: This flag applies to accessory decoders only. Accessory decoders normally have 4 paired outputs and a single address refers to all 4 outputs. Setting this flag causes each address to refer to a single output. - `dcc.FLAGS_AUTO_FACTORY_DEFAULT`: Call DCC command callback with `dcc.CV_RESET` command if CV 7 & 8 == 255. - `OpsModeAddressBaseCV` (number) - Ops Mode base address. Set it to 0? - `CV_table` (table) - Optional. The CV values will be directly accessed from this table. metamethods will be invoked if needed. Any errors thrown will cause the CV to be considered invalid. Using this option will prevent `CV_VALID`, `CV_READ`, `CV_WRITE` and `CV_ACK_COMPLETE` from happening. - `CV_callback` (function) - Optional. Callback function that is called when any manipulation with CV ([Configuarion Variable](https://dccwiki.com/Configuration_Variable)) is requested. - `dcc.CV_VALID`: To determine if a given CV is valid and (possibly) writable. This callback must determine if a CV is readable or writable and return the appropriate value (0/1/true/false). The `param` collection has members `CV` and `Writable`. - `dcc.CV_READ`: To read a CV. This callback must return the value of the CV. The `param` collection has one member `CV` determining the CV number to be read. - `dcc.CV_WRITE`: To write a value to a CV. This callback must write the Value to the CV and return the value of the CV. The `param` collection has members `CV` and `Value`. Ideally, the final value should be returned -- this may differ from the requested value. - `dcc.CV_RESET`: Called when CVs must be reset to their factory defaults. - `dcc.CV_ACK_COMPLETE`: Called when an ACK pulse has finished being sent. Only invoked if `AckPin` is specified. ### Returns `nil` ``` -------------------------------- ### Starting a Timer and Handling Errors Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/tmr.md Starts a previously registered timer and checks for errors during the start operation. Essential for ensuring timers are active. ```lua mytimer = tmr.create() mytimer:register(5000, tmr.ALARM_SINGLE, function() print("hey there") end) if not mytimer:start() then print("uh oh") end ``` -------------------------------- ### Start Gossip Service Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/lua-modules/gossip.md Starts the gossip service, setting the 'started' flag and initiating the revision number. The revision acts as a persistent heartbeat. ```lua gossip.start() ``` -------------------------------- ### pwm.setup() Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/pwm.md Configures a GPIO pin for PWM output with specified frequency and duty cycle. ```APIDOC ## pwm.setup() ### Description Set pin to PWM mode. Only 6 pins can be set to PWM mode at the most. ### Syntax `pwm.setup(pin, clock, duty)` ### Parameters * `pin` (number) - Required - IO index (1-12) * `clock` (number) - Required - PWM frequency (1-1000) * `duty` (number) - Required - 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) ``` -------------------------------- ### Pack and Unpack Example Source: https://github.com/nodemcu/nodemcu-firmware/blob/release/docs/modules/struct.md Demonstrates packing and unpacking a structure with a char and an array of integers using a format string. ```lua struct.pack("