Superstack Lua reference
Superstack devices such as the S2 Module run Lua. You upload your code with the Superstack CLI, and the device runs it. This reference lists every function your code can call to read sensors, drive IO, make web requests and receive messages from your application.
Each function runs C code in the firmware. Lua can’t reach the parts of the firmware that check in with Superstack and install updates, so no code you upload can stop the device from receiving new code.
Complete, ready-to-run code is in the example repository. If you write code with an AI agent, the Superstack plugin for Claude Code and Codex teaches it this reference.
Contents
- Function summary
- Coding principles and notation
- Standard libraries
- Hardware libraries
- Networking libraries
- System libraries
Function summary
Every function and constant on this page, in page order. Each links to its full description.
| Function | What it does |
|---|---|
device.digital.set_output() | Set or clear a digital output on a pin |
device.digital.get_input() | Get the digital value on a pin |
device.digital.assign_input_event() | Assign an event handler for a pin input change |
device.digital.unassign_input_event() | Disable an input event handler on a pin |
device.pwm.set_output() | Output a PWM signal on a pin |
device.analog.get_input() | Read the analog value on a pin |
device.analog.get_differential_input() | Read the differential analog value across two pins |
device.i2c.read() | Read bytes from an I2C device |
device.i2c.write() | Write bytes to an I2C device |
device.i2c.write_read() | Write then read bytes from an I2C device |
device.i2c.scan() | Scan for I2C devices |
device.spi.write_read() | Write then read bytes from an SPI device |
device.spi.write() | Write bytes to an SPI device |
device.spi.read() | Read bytes from an SPI device |
device.spi.transact() | Transact bytes with an SPI device (write and read in parallel) |
device.uart.write() | Write UART data |
device.uart.assign_read_event() | Assign an event handler for UART data |
device.uart.unassign_read_event() | Disable the UART read event handler |
device.pdm.read() | Record audio from a PDM microphone |
device.pdm.assign_read_event() | Assign an event handler for microphone audio |
device.pdm.unassign_read_event() | Disable the microphone read event handler |
device.ws2812.write() | Set the colors of addressable LEDs |
network.get() | Send a GET or DELETE request to a web service |
network.delete() | Send a GET or DELETE request to a web service |
network.post() | Send a POST, PUT or PATCH request to a web service |
network.put() | Send a POST, PUT or PATCH request to a web service |
network.patch() | Send a POST, PUT or PATCH request to a web service |
network.assign_message_event() | Assign an event handler for messages |
network.unassign_message_event() | Disable the message event handler |
network.connected() | Check if the network is connected |
network.low_power_mode() | Set low power mode |
location.enable() | Enable GPS |
location.get_latest() | Get the latest GPS data |
location.disable() | Disable GPS |
print() | Post log to Superstack |
device.sleep() | Sleep for a duration |
device.sleep_ms() | Sleep for a short duration |
device.power.battery.set_charger_cv_cc() | Configure the battery charger |
device.power.battery.get_voltage() | Get the battery voltage |
device.power.battery.get_charging_status() | Get the battery charging status |
device.power.set_vout() | Set the IO voltage for all ports |
require() | Run another code file |
time.get_unix_time() | Get the current Unix timestamp |
time.get_time_date() | Get the current time and date |
device.HARDWARE_VERSION | Hardware version constant |
device.FIRMWARE_VERSION | Firmware version constant |
json.encode() | Encode a value as JSON |
json.decode() | Decode JSON text |
Coding principles and notation
The functions described in this reference typically represent single, atomic operations. For example device.digital.set_output() will output a high, or low voltage on a specified pin. Unlike most hardware level programming, a separate configuration step isn’t needed. All configuration is optional and is passed directly into this function if desired.
The functions may accept a combination of positional and named arguments. Positional arguments always come first, with the named arguments provided at the end as a Lua table of key-value pairs.
Most of the named arguments will take on a default value if not provided. These are marked as optional.
A pin name is the port letter and the pin number on that port: A0, A1, B0, B1, C0 to C4, D0 to D4, E0, E1, F0 and F1. The S2 pinout shows where each one is. Any other name raises an error, such as invalid pin.
-- Calling a function with only positional arguments
device.digital.set_output("A0", true)
-- Calling a function with both positional and named arguments
device.i2c.write(0x12, "\x4F\x01", { sda_pin="B0", scl_pin="B1" })
-- Calling a function with only named arguments. Note how the () can be omitted
location.enable{ accuracy="LOW" }
Event handlers, such as those assigned with device.digital.assign_input_event(), run only while the code is running. Code that reaches the end of main.lua ends, and its handlers stop. To keep handling events, end main.lua with a loop:
while true do
device.sleep(1)
end
An error that the code doesn’t catch with pcall ends the code. The log shows Code crashed: followed by the error, and the code’s run state becomes crashed. An error inside a handler or a request callback ends the code the same way. Handlers and callbacks can’t call coroutine.yield(), and doing so raises an error. To run the code again, upload it or run superstack device start <imei>.
If the code makes the S2 restart, the S2 doesn’t run it again after the restart. The log shows Code crashed the device, so it was not started again.
Standard libraries
The device runs Lua 5.5. Most of the standard Lua libraries that you would find on the desktop installation of Lua are included:
- ✅ Basic functions
- ✅ Math functions
- ✅ String manipulation
- ✅ Table manipulation
- ✅ UTF-8 support
- ✅ Coroutine manipulation
The remaining standard libraries are not included:
- ❎ File IO functions - Lua has no file access beyond
require - ❎ Operating system functions - Replaced by the timekeeping and device information libraries
- ❎ Debug library
- ❎ Package library -
requireloads code files without it
Three basic functions differ from desktop Lua:
requireloads another code file. See code filesloadaccepts only text, not precompiled bytecodedofileandloadfileare not available. Userequireinstead
Hardware libraries
Digital IO
Set or clear a digital output on a pin
device.digital.set_output(pin, value)
Parameters
pin- string - The pin name. E.g."A0"value- boolean - The level to set.truefor high,falsefor low
Returns
- nil
Setting an output on a pin removes any input event handler assigned to the pin.
Example
-- Set pin B1 to a high value device.digital.set_output("B1", true)
Get the digital value on a pin
device.digital.get_input(pin, { pull="PULL_DOWN" })
Parameters
pin- string - The pin name. E.g."A0"
Optional parameters
pull- string - The pull mode on the pin. Can be"PULL_UP","PULL_DOWN", or"NO_PULL"
Returns
- boolean -
trueif the pin is high,falseif low
Reading a pin removes any input event handler assigned to the pin.
Example
-- Print the value on pin D0 local val = device.digital.get_input("D0") print(val)
Assign an event handler for a pin input change
device.digital.assign_input_event(pin, handler, { pull="PULL_DOWN" })
Parameters
pin- string - The pin name. E.g."A0"handler- function - The function to call when the pin goes high or low. Called with two arguments:
pin- string - The pin name that generated the event. E.g."A0"state- boolean - The pin value when the event occurred.trueif high,falseif low
Optional parameters
pull- string - The pull mode on the pin. Can be"PULL_UP","PULL_DOWN", or"NO_PULL"
Returns
- nil
If the pin changes several times before the handler runs, the handler runs once, with the latest state. Using the pin for anything else, such as PWM, an analog read or I2C, stops the handler firing.
Example
-- Assign a function that triggers when the input value of C3 changes function my_pin_handler(pin, state) if state == true then print(pin.." went high") else print(pin.." went low") end end device.digital.assign_input_event("C3", my_pin_handler)
Disable an input event handler on a pin
device.digital.unassign_input_event(pin)
Parameters
pin- string - The pin name. E.g."A0"
Returns
- nil
Example
-- Disable the event and detach the pin from the handler device.digital.unassign_input_event("C3")
PWM output
Output a PWM signal on a pin
device.pwm.set_output(pin, duty_cycle, { frequency=1000 })
Parameters
pin- string - The pin name. E.g."A0"duty_cycle- number - The percentage of each period that the pin is high. From0to100
Optional parameters
frequency- number - The PWM frequency in Hz. From4to5000000
Returns
- nil
Up to four pins can output PWM at once. Starting PWM on a fifth pin stops it on the pin that started first. Any other function that uses the pin, such as
device.digital.set_output(), also stops it.
Example
-- Dim an LED on pin A0 to 25% brightness device.pwm.set_output("A0", 25, { frequency=2000 })
Analog input
Read the analog value on a pin
device.analog.get_input(pin, { acquisition_time=10 })
Parameters
pin- string - The pin name. Must be an analog capable pin:"C2"to"C4", or"D0"to"D4"
Optional parameters
acquisition_time- integer - The measurement time in microseconds. Can be3,5,10,15,20, or40. Higher values support greater source resistances (10kΩ, 40kΩ, 100kΩ, 200kΩ, 400kΩ, 800kΩ respectively)
Returns
- number - The voltage present on the pin in volts
Example
-- Read the analog voltage on pin D0 local voltage = device.analog.get_input("D0") print(voltage)
Read the differential analog value across two pins
device.analog.get_differential_input(positive_pin, negative_pin, { acquisition_time=10 })
Parameters
positive_pin- string - The pin name of the positive pin. Must be an analog capable pin. E.g."D0"negative_pin- string - The pin name of the negative pin. Must be an analog capable pin, and different frompositive_pin. E.g."D1"
Optional parameters
acquisition_time- integer - The measurement time in microseconds. Can be3,5,10,15,20, or40. Higher values support greater source resistances (10kΩ, 40kΩ, 100kΩ, 200kΩ, 400kΩ, 800kΩ respectively)
Returns
- number - The voltage across the pins in volts. Negative when
negative_pinis at the higher voltage
Example
-- Read the differential analog voltage across pins D0 and D1 local voltage = device.analog.get_differential_input("D0", "D1") print(voltage)
I2C communication
Optional parameters for every I2C function
port- string - The 4-pin port the I2C device is connected to. Can be"PORTA","PORTB","PORTE", or"PORTF". Defaults to"PORTA". Assumes the Stemma QT/Qwiic pinout, with SDA on pin 3 and SCL on pin 4. Cannot be used withscl_pinandsda_pinscl_pin- string - The pin name for the SCL signal, for any other pins or pin order. E.g."C3". Must be used withsda_pinsda_pin- string - The pin name for the SDA signal. E.g."C4". Must be used withscl_pinfrequency- integer - The I2C frequency in kHz. Can be100,250, or400. Defaults to100
A single I2C transaction may read or write at most 8191 bytes. A transaction fails, and returns
success=false, if the device does not acknowledge or does not finish within 2 seconds.
Read bytes from an I2C device
device.i2c.read(address, length, { port="PORTA", frequency=100 })
Parameters
address- integer - The 7-bit address of the I2C devicelength- integer - The number of bytes to read
Returns
- table - A table of key-value pairs:
success- boolean -trueif the transaction was successful,falseotherwisedata- string - The bytes read. Always of sizelength. Absent ifsuccessisfalsevalue- integer - The first byte read, useful if only one byte was requested. Absent ifsuccessisfalseorlengthis0
Example
-- Read multiple bytes from the device and print the fourth byte local result = device.i2c.read(0x23, 4) if result.success then print(string.byte(result.data, 4)) end
Write bytes to an I2C device
device.i2c.write(address, data, { port="PORTA", frequency=100 })
Parameters
address- integer - The 7-bit address of the I2C devicedata- string - The data to write to the device. Can be a hexadecimal string containing zeros. E.g."\x1A\x50\x00\xF1"
Returns
- table - A table of key-value pairs:
success- boolean -trueif the transaction was successful,falseotherwise
Example
-- Write 0x1234 to the register 0xF9 device.i2c.write(0x23, "\xF9\x12\x34")
Write then read bytes from an I2C device
device.i2c.write_read(address, write_data, read_length, { port="PORTA", frequency=100 })
Parameters
address- integer - The 7-bit address of the I2C devicewrite_data- string - The data to write to the device. Can be a hexadecimal string containing zeros. E.g."\x1A\x50\x00\xF1"read_length- integer - The number of bytes to read
Returns
- table - A table of key-value pairs:
success- boolean -trueif both the write and the read were successful,falseotherwisedata- string - The bytes read. Always of sizeread_length. Absent ifsuccessisfalsevalue- integer - The first byte read, useful if only one byte was requested. Absent ifsuccessisfalseorread_lengthis0
Example
-- Read a byte from register 0x1F on a device with address 0x23 local result = device.i2c.write_read(0x23, "\x1F", 1) if result.success then print(result.value) end
Scan for I2C devices
device.i2c.scan({ port="PORTA", frequency=100 })
Returns
- nil - The scan logs
Scanning for I2C devices, thenDevice found: 0x23for each device it finds, thenI2C scan complete
Example
-- Log the address of every device on PORTF device.i2c.scan({ port="PORTF" })
SPI communication
Optional parameters for every SPI function
sclk_pin- string - The pin name for the SCK signal. Defaults to"C0"mosi_pin- string - The pin name for the MOSI signal. Defaults to"C1"miso_pin- string - The pin name for the MISO signal. Defaults to"C2"cs_pin- string - The pin name for the CS signal. Defaults to"C3"mode- integer - The SPI mode. Can be0,1,2, or3. Defaults to0frequency- integer - The SPI frequency in kHz. Can be125,250,500,1000,2000,4000, or8000. Defaults to4000bit_order- string - The bit order for transactions. Can be"MSB_FIRST"or"LSB_FIRST". Defaults to"MSB_FIRST"hold_cs- boolean - Iftrue, the CS pin remains held after the transaction completes. Useful for multi-step transactions. Defaults tofalsecs_active_high- boolean - Iftrue, the CS pin is set high during the transaction and low once completed. Defaults tofalsemiso_pull- string - The pull mode on the MISO pin. Can be"PULL_UP","PULL_DOWN", or"NO_PULL". Defaults to"NO_PULL"
The pin options
sclk_pin,mosi_pin,miso_pinandcs_pinmust all be specified together. Providing only some of them raises an error. A single transfer may read or write at most 8191 bytes.
Write then read bytes from an SPI device
device.spi.write_read(write_data, read_length, { mode=0, frequency=4000 })
Parameters
write_data- string - The data to write to the deviceread_length- integer - The number of bytes to read from the device after the write. CS stays active between the two
Returns
- string - The bytes read. Always of size
read_length
Example
-- Read data from an SPI flash device local data = device.spi.write_read("\x03\x00\x00\x00", 11) print(data)
Write bytes to an SPI device
device.spi.write(data, { mode=0, frequency=4000 })
Parameters
data- string - The data to write to the device
Returns
- nil
Example
-- Wake up the flash with the 0xAB command device.spi.write("\xAB")
Read bytes from an SPI device
device.spi.read(length, { mode=0, frequency=4000 })
Parameters
length- integer - The number of bytes to read from the device
Returns
- string - The bytes read. Always of size
length
Example
-- Read 4 bytes from an SPI device local data = device.spi.read(4) print(data)
Transact bytes with an SPI device (write and read in parallel)
device.spi.transact(write_data, read_length, { mode=0, frequency=4000 })
Parameters
write_data- string - The data to write to the deviceread_length- integer - The number of bytes to read from the device while writing
Returns
- string - The bytes read. Always of size
read_length
Example
-- Write and read data simultaneously local data = device.spi.transact("\x9F", 3) print(data)
UART communication
Write UART data
device.uart.write(data, { tx_pin="A1", baudrate=9600, parity=false, stop_bits=1 })
Parameters
data- string - The data to send
Optional parameters
tx_pin- string - The pin name for the transmit signal. E.g."C1"baudrate- integer - The baudrate in bits-per-second. Can be1200,2400,4800,9600,14400,19200,28800,31250,38400,56000,57600,76800,115200,230400,250000,460800,921600, or1000000parity- boolean - Iftrue, enables the parity bitstop_bits- integer - The number of stop bits. Can be1or2
Returns
- nil - Returns once all the data is sent
Example
-- Send UART data device.uart.write("Hello there. This is some data\n", { baudrate=19200 })
Assign an event handler for UART data
device.uart.assign_read_event(terminator, handler, { rx_pin="A0", baudrate=9600, parity=false, stop_bits=1 })
Parameters
terminator- string - The character to wait for before callinghandler. E.g."\n". A string that isn’t exactly one character raises an error. Ifnil,handleris called with whatever data has arrivedhandler- function - The function to call when data is received. Called with one argument:
data- string - The bytes received since the last call, including the terminator
Optional parameters
rx_pin- string - The pin name for the receive signal. E.g."C0"baudrate- integer - The baudrate in bits-per-second. Takes the same values asdevice.uart.write()parity- boolean - Iftrue, enables the parity bitstop_bits- integer - The number of stop bits. Can be1or2
Returns
- nil
Only one UART read event can be assigned at a time. Assigning another replaces it. If 512 bytes arrive without a terminator,
handleris called with them anyway. If more than 2048 bytes arrive before the code handles them, they are dropped.
Example
-- Log each line received device.uart.assign_read_event("\n", function(line) print("Got a new line: " .. line) end, { baudrate=19200 })
Disable the UART read event handler
device.uart.unassign_read_event()
Returns
- nil
Example
-- Stop receiving UART data device.uart.unassign_read_event()
Microphone (PDM)
Record audio from a PDM microphone
device.pdm.read(samples, { port="PORTA", channel="LEFT", sample_rate=16000, gain=0 })
Parameters
samples- integer - The number of samples to record from each channel. E.g.16000for one second at the default sample rate
Optional parameters
port- string - The 4-pin port the microphone is connected to. Can be"PORTA","PORTB","PORTE", or"PORTF". Defaults to"PORTA". The clock is on pin 4 and the data on pin 3, the pins that carry SCL and SDA in the Stemma QT/Qwiic pinout. Cannot be used withclk_pinanddata_pinclk_pin- string - The pin name for the clock. E.g."C0". Must be specified withdata_pindata_pin- string - The pin name for the data. E.g."C1". Must be specified withclk_pinchannel- string - The channel to record. Can be"LEFT","RIGHT", or"STEREO". A PDM microphone sends the left or the right channel, which a pin or jumper on the microphone selects."STEREO"records two microphones that share the clock and data pins, one set to each channel. Defaults to"LEFT"sample_rate- integer - The samples per second. Can be12500,16000, or20000. Defaults to16000gain- number - The gain in dB. From-20to20in steps of0.5. Defaults to0
Returns
- string - The samples, each a signed 16-bit little-endian integer. Read one with
string.unpack("<i2", data, position). In stereo, left and right samples alternate, starting with the left. Returns once every sample is recorded
Each read starts the microphone, which sends nothing for its start-up time, often tens of milliseconds. The S2 also filters out the steady level of the audio, and this filter takes about a second to settle after the start. Until it does, the audio sits on an offset that fades. The offset can’t be heard, but code that measures the level in that first second includes it, and at a high gain the first samples can reach the limit of the range. To record without the start-up, keep a read event running.
A read holds all its samples in memory, so one read can hold about 4 seconds of audio from one channel at 16000 samples per second. A larger read raises
not enough memory. Only one read or read event can use the microphone at a time. Another raisesthe microphone is already being read.
Example
-- Record two seconds, and log the loudest sample once the start-up has settled local data = device.pdm.read(32000) local loudest = 0 for position = 32001, #data, 2 do loudest = math.max(loudest, math.abs(string.unpack("<i2", data, position))) end print("Loudest sample: " .. loudest)
Assign an event handler for microphone audio
device.pdm.assign_read_event(samples, handler, { port="PORTA", channel="LEFT", sample_rate=16000, gain=0 })
Parameters
samples- integer - The number of samples from each channel in every block. From1to32767, or16383in stereohandler- function - The function to call with each block. Called with one argument:
data- string - The block’s samples, in the same form thatdevice.pdm.read()returns
Optional parameters
port,clk_pin,data_pin,channel,sample_rate, andgain- The same options asdevice.pdm.read()
Returns
- nil
The microphone records without a break until the event is unassigned or the code ends, so each block follows on from the last. The first second of blocks carries the start-up that
device.pdm.read()describes. Only one PDM read event can be assigned at a time. Assigning another replaces it. If the code falls more than three blocks behind, the blocks waiting for it are dropped.
Example
-- Keep the most recent second of audio, ready for the moment it's needed local recent = {} device.pdm.assign_read_event(1600, function(block) table.insert(recent, block) if #recent > 10 then table.remove(recent, 1) end end) -- Later, such as when a button is pressed local audio = table.concat(recent)
Disable the microphone read event handler
device.pdm.unassign_read_event()
Returns
- nil
Example
-- Stop recording device.pdm.unassign_read_event()
Addressable LEDs (WS2812)
Set the colors of addressable LEDs
device.ws2812.write(pin, colors, { order="GRB", frequency=800000 })
Parameters
pin- string - The pin name connected to the data input of the first LED. E.g."B0"colors- table - One color for each LED, in the order the LEDs are chained. Each color is a table of red, green and blue values, then white whenorderincludesW, each an integer from0to255. E.g.{ { 255, 0, 0 }, { 0, 0, 255 } }
Optional parameters
order- string - The order in which the LEDs take each color’s values, as the lettersR,G,B, and optionallyW, each once. E.g."GRB"for most WS2812 and SK6812 LEDs, or"GRBW"for most RGBW LEDs. Check the LEDs’ datasheet. Defaults to"GRB"frequency- integer - The data rate in Hz. Can be800000, or400000for LEDs such as the WS2811 in its slow mode. Defaults to800000
Returns
- nil - Returns once every color is sent
One write can set up to 1365 LEDs, or 1023 when
orderincludesW. The LEDs keep their colors until the next write. A write uses one of the four PWM instances while it sends. When PWM uses all four, the pin that started PWM first stops.The data swings to the IO voltage of the port, which starts at 1.8V, so call
device.power.set_vout(3.3)first. PORTA to PORTC share 100mA, as do PORTD to PORTF, and a single LED at full brightness can draw tens of milliamps. Power more LEDs than that allows from a separate supply.
Example
-- Light a ring of 12 RGBW LEDs dim red device.power.set_vout(3.3) local colors = {} for led = 1, 12 do colors[led] = { 32, 0, 0, 0 } end device.ws2812.write("B0", colors, { order="GRBW" })
Networking libraries
Networking (LTE)
Send a GET or DELETE request to a web service
network.get(url, { headers=nil, callback=nil })
network.delete(url, { headers=nil, callback=nil })
Parameters
url- string - The full address, starting withhttps://orhttp://, including any query string. E.g."https://example.com/api?city=Oslo". It must name a host, and any port must be a number. It can’t contain control characters or invalid UTF-8, and outside the query a%must start an escape such as%20
Optional parameters
headers- table - The request headers, as names mapped to values. E.g.{ ["Authorization"]="Bearer abc" }. A name can contain only letters, digits and!#$%&'*+-.^_`|~. A value can’t contain control characters other than tab, or invalid UTF-8callback- function - If given, the call returns at once and this function is called when the request finishes. Called with the sameresponseanderrorthat the call would otherwise return
Returns
response- table - A table of key-value pairs, orniliferroris set:
status- integer - The HTTP status code. E.g.200content- string - The response bodyerror- string -nil, or the reason no response arrived:
"no network"- The request did not reach Superstack, or Superstack did not accept it"timeout"- The web service did not answer in time, or its answer did not reach the device"connection failed"- Superstack could not connect to the web service"too large"- The response body was too long"no credit"- The fleet has no credit, so the device did not send the requestWith
callback, the call returns onlyerror, which isnil
Superstack makes the request on the device’s behalf. Receive requests from a device lists the limits the web service must meet, how Superstack follows redirects, and which responses reach Lua. Only one request can wait at a time, with or without
callback, and making another raises an error.A
urlorheadersthat breaks a rule above raises an error that names the rule. The URL and headers fit in about 5000 bytes, and a longer request raises the errorurl and headers are too long.
Example
local response, err = network.get("https://example.com/api/weather?city=Oslo") if response then print(response.status, response.content) else print("Request failed: " .. err) end
Send a POST, PUT or PATCH request to a web service
network.post(url, body, { headers=nil, callback=nil })
network.put(url, body, { headers=nil, callback=nil })
network.patch(url, body, { headers=nil, callback=nil })
Parameters
url- string - The full address, with the same rules asnetwork.get()body- string - The request body, sent unchanged. At most 4096 bytes
Optional parameters
headers- table - The request headers, with the same rules asnetwork.get()callback- function - Called withresponseanderrorwhen the request finishes
Returns
responseanderror- The same asnetwork.get()
The URL and headers fit in about 980 bytes beside a 4096-byte body. A longer request raises the error
url and headers are too long.
Example
-- Send a reading as JSON without waiting for the answer network.post("https://example.com/api/readings", json.encode{ temperature=21.5 }, { headers={ ["Content-Type"]="application/json" }, callback=function(response, err) print(err or response.status) end, })
Assign an event handler for messages
network.assign_message_event(handler)
Parameters
handler- function - The function to call when a message arrives from your application through Superstack. Called with one argument:
content- string - The message exactly as your application sent it
Returns
- nil
A message that arrives while no handler is assigned, or while the code is stopped, is discarded. How a message reaches a device describes when messages arrive and how many the device holds.
Example
-- Switch an output from a JSON message such as {"led":true} network.assign_message_event(function(content) device.digital.set_output("B1", json.decode(content).led) end)
Disable the message event handler
network.unassign_message_event()
Returns
- nil
Example
-- Stop handling messages. Later messages are discarded network.unassign_message_event()
Check if the network is connected
network.connected()
Returns
- boolean -
trueif the LTE network is connected,falseotherwise
Example
if network.connected() then print("Network is up") end
Example
-- Keep the newest 200 readings in RAM while the network is down local readings = {} while not network.connected() do if #readings == 200 then table.remove(readings, 1) end table.insert(readings, device.power.battery.get_voltage()) device.sleep(60) end -- Send the buffered readings once the network returns if #readings > 0 then network.post("https://example.com/api/readings", table.concat(readings, "\n")) end
A Lua table is held in RAM, so buffered readings are lost when the code ends, crashes, stops or restarts, or when the S2 restarts. A table that outgrows the free memory raises
not enough memory. The example keeps 200 readings so that they fit in one 4096-byte request body.
Set low power mode
network.low_power_mode(enabled)
Parameters
enabled- boolean -trueto enable PSM (Power Saving Mode),falseto disable it
Returns
- nil
Enabling PSM introduces up to 15 minutes of latency for code uploads, messages, and starting, stopping or restarting the code, because the S2 receives them only at its check-in every 15 minutes. To return to real-time updates, call
network.low_power_mode(false)and wait up to 15 minutes for the modem to re-register.PSM stays on after the code ends, crashes or is stopped, until code turns it off or the S2 restarts.
Example
-- Enable low power mode when the network is not needed network.low_power_mode(true)
Location (GPS)
Enable GPS
location.enable{ accuracy="HIGH", power_saving="OFF", tracking_interval=1 }
Optional parameters
The table itself is required. Pass
{}to use every default
accuracy- string - The accuracy of the fix."LOW"requires three satellites,"HIGH"requires four satellitespower_saving- string - The power saving level. Can be"OFF","MEDIUM", or"MAX". Higher power saving reduces accuracy and increases time to fixtracking_interval- integer - The period to poll for new location updates.1for continuous 1-second updates, or a value between10and65535seconds for slower updates to save power
Returns
- nil
location.enable()automatically activates PSM to allow the modem to share hardware with the GPS. This introduces up to 15 minutes of latency for code uploads, messages, and starting, stopping or restarting the code. To return to real-time updates, calllocation.disable()followed bynetwork.low_power_mode(false), then wait up to 15 minutes.GPS and PSM stay on after the code ends, crashes or is stopped, until code turns them off or the S2 restarts.
Example
-- Start GPS with default settings location.enable{} -- Start GPS with low accuracy to save power location.enable{ accuracy="LOW", power_saving="MAX" }
Get the latest GPS data
location.get_latest()
Returns
- table - A table of key-value pairs:
valid- boolean -trueif the latest fix is valid. Iffalse, the location and speed values are from the last valid fix, or0before the first. The latest fix stays until the S2 restarts, even afterlocation.disable()or after the code ends, sovalidcan betruefor a fix from an earlier runlatitude- number - The latitude in degreeslongitude- number - The longitude in degreesaltitude- number - The altitude in metersaccuracy- number - The location accuracy in metersspeed- number - The horizontal speed in meters per secondspeed_accuracy- number - The speed accuracy in meters per secondsatellites- table - A table of key-value pairs:
tracked- integer - The number of satellites currently being trackedin_fix- integer - The number of satellites currently being used for measurementunhealthy- integer - The number of satellites that could not be used for measurement
Example
-- GPS must be enabled before getting a location fix location.enable{} -- Avoid network activity while waiting for a fix. It competes -- for the modem hardware and delays acquisition device.sleep(60) local fix = location.get_latest() if fix.valid then print(string.format("%.5f, %.5f", fix.latitude, fix.longitude)) else print("No fix yet. Tracking " .. fix.satellites.tracked .. " satellites") end
Disable GPS
location.disable()
Returns
- nil
Disabling GPS alone does not restore real-time code updates. PSM remains active until
network.low_power_mode(false)is called. After calling it, wait up to 15 minutes for the modem to re-register before code updates arrive in real time.
Example
-- Stop GPS and restore real-time connectivity location.disable() network.low_power_mode(false)
System libraries
Logging
Post log to Superstack
print(...)
Parameters
...- any - One or more values to print. They are converted to strings and joined with tabs into one log
Returns
- nil
Example
-- Simple print print("hello world") -- Print several values in one log, separated by tabs print("count", 4 + 3) -- C printf style formatted prints print(string.format("pi = %.4f", math.pi))
Sleep
Sleep for a duration
device.sleep(time)
Parameters
time- number - The duration to sleep in seconds. E.g.1.5
Returns
- nil
Assigned event handlers continue to fire during sleep. See assign an event handler.
Example
-- Sleep for 1.5 seconds device.sleep(1.5)
Sleep for a short duration
device.sleep_ms(time)
Parameters
time- integer - The duration to sleep in milliseconds. From0to1000
Returns
- nil
Event handlers do not fire during
device.sleep_ms(), and stopping the code waits for it to return. Usedevice.sleep()for anything longer.
Example
-- Pulse pin B1 high for 5 milliseconds device.digital.set_output("B1", true) device.sleep_ms(5) device.digital.set_output("B1", false)
Power
Configure the battery charger
device.power.battery.set_charger_cv_cc(voltage, current)
Parameters
voltage- number - The termination voltage. Can be3.50,3.55,3.60,3.65,4.00,4.05,4.10,4.15,4.20,4.25,4.30,4.35,4.40, or4.45current- integer - The constant charge current in mA. Must be between32and800in steps of2
Returns
- nil
This setting reverts to the firmware default (3.50V termination, 32mA charge current) at reboot. Configure the charger near the top of your code so that it is reapplied whenever the code restarts.
Example
-- Configure the battery charger for a 4.2V 200mAh rated Li-Po cell device.power.battery.set_charger_cv_cc(4.2, 200)
Get the battery voltage
device.power.battery.get_voltage()
Returns
- number - The voltage of the cell in volts
Example
local voltage = device.power.battery.get_voltage() print("Battery voltage is "..tostring(voltage).."V")
Get the battery charging status
device.power.battery.get_charging_status()
Returns
- string - The charging status:
"charging","charged", or"discharging"if a battery is connected, or"external_power"if no battery is installed or the battery has a fault
Example
local status = device.power.battery.get_charging_status() if status ~= "external_power" then print("Battery is "..status) else print("Battery not connected. On external power") end
Set the IO voltage for all ports
device.power.set_vout(voltage)
Parameters
voltage- number - The IO voltage ofPORTA-PORTF. Can be between1.8and3.3in steps of0.1, or0to switch the power pins of every port off. Any other value raisesvoltage must be between 1.8 and 3.3 in steps of 0.1
Returns
- nil
At boot, the port rails default to 1.8V. If a connected sensor requires a higher IO voltage, call this function before communicating with it. The voltage applies to every port at once. It stays set after the code ends, until the code changes it or the S2 restarts.
Example
-- Set the voltage of Vout to 3.3V device.power.set_vout(3.3)
Code files
Run another code file
require(name)
Parameters
name- string - The path of a code file in the bundle, without.lua. E.g."sensors"forsensors.lua, or"lib/sensors"forlib/sensors.lua
Returns
- any - The value the file returns, or
trueif it returns nothing
A file runs once. Later calls with the same name return the value from the first call without running the file again. Files can require other files up to 8 levels deep. A deeper
requireraisesrequire is nested too deeply, and a missing file raisesmodule not found.Unlike desktop Lua, a
.in the name is not a folder separator, sorequire("lib.sensors")looks forlib.sensors.lua. To putsensors.luain alibfolder on the device, upload the folder that holdslib. See what an upload sends.
Example
-- sensors.lua returns a table of functions local sensors = require("sensors") print(sensors.read_temperature())
Timekeeping
The time is not known until the device first checks in to Superstack, which sets its clock to within 2 seconds and corrects it whenever it drifts further. While location is enabled, each GPS fix also sets the clock, to the millisecond of the fix.
Get the current Unix timestamp
time.get_unix_time()
Returns
- integer - The current Unix timestamp (i.e the number of non-leap milliseconds that have elapsed since 00:00:00 UTC on 1 January 1970), or if the time is not yet known, returns the uptime of the device in milliseconds
Example
-- Repeat something for 30 seconds local t = time.get_unix_time() while t + 30000 > time.get_unix_time() do print("waiting") device.sleep(5) endNote: the returned value is in milliseconds, so 30 seconds is
30000
Get the current time and date
time.get_time_date({ unix_epoch=nil, timezone="+00:00" })
Optional parameters
unix_epoch- integer - A Unix timestamp in milliseconds to convert, as returned bytime.get_unix_time(). Ifnil, the current time is used, and an error is raised if the time is not yet knowntimezone- string - The timezone offset as"+HH:MM"or"-HH:MM", from"-12:59"to"+14:59". E.g."+02:00"or"-07:30". Defaults to"+00:00"
Returns
- table - A table of key-value pairs:
year- integer - The current yearmonth- integer - The current monthday- integer - The current dayyearday- integer - The day of the year.1on 1 Januaryweekday- integer - The days since Sunday.0on Sundayhour- integer - The current hourminute- integer - The current minutesecond- integer - The current second
Example
-- Print the current time and date local now = time.get_time_date() print(string.format("The current time is: %02d:%02d", now.hour, now.minute)) print(string.format("The current date is: %d/%d/%d", now.year, now.month, now.day))
Device information
Hardware version constant
device.HARDWARE_VERSION
Returns
- string - Always
"s2-module"
Example
print(device.HARDWARE_VERSION)
Firmware version constant
device.FIRMWARE_VERSION
Returns
- string - A string representing the current firmware version. E.g.
"3.0.0"
Example
print(device.FIRMWARE_VERSION)
JSON
Encode a value as JSON
json.encode(value)
Parameters
value- any - A table, string, number, boolean,nilorjson.null.nilandjson.nullbecomenull. A table whose keys are all whole numbers from 1 up becomes an array, withnullfor each missing key. E.g.{[1]=1, [3]=3}becomes[1,null,3]. Any other table becomes an object. An empty table becomes{}
Returns
- string - The JSON text
Tables can nest up to 16 levels deep. A value that JSON cannot hold, such as a function, raises an error.
An array table whose highest key is above 10 and more than twice its number of keys, such as
{[20]=1}, raises the errorCannot serialise table: excessively sparse array.An integer is written exactly. Any other number is written to 14 significant digits. A
/in a string is written as\/, so"https://example.com"becomes"https:\/\/example.com", which any JSON parser reads back as the same string.
Example
-- Prints {"temperature":21.5,"readings":[1,2,3]}, with the keys in any order print(json.encode{ temperature=21.5, readings={1, 2, 3} })
Decode JSON text
json.decode(text)
Parameters
text- string - The JSON text
Returns
- any - The decoded value. Objects and arrays become tables, and
nullbecomesjson.null
Text that is not valid JSON, or that nests more than 16 levels deep, raises an error. Use
pcallto handle text that might be invalid.
Example
local ok, message = pcall(json.decode, '{"led":true,"level":null}') if ok and message.level == json.null then print("No level given") end