UART

uart.start(tx, rx, baud)

Starts asynchronous communication using UART.

To initialize the communication, specify the IO pin numbers for TX (transmit) and RX (receive), along with the baud rate (communication speed).

  • tx: IO pin number for transmission from your obniz Device.
  • rx: IO pin number for reception to your obniz Device.
  • baud: Communication speed (e.g., 9600, 115200).

Occupancy and Retention
A UART session initiated from Lua is exclusively reserved for Lua, making it unavailable for external use by other interfaces like obniz.js.

Additionally, once a UART session is started, calling uart.start() again from Lua while the device is running may not apply the new settings, or may result in an error. To change configurations such as the TX pin, call uart.stop() first (OS7.1.0 and later). On OS7.0.x, a reboot is required.

If you do not need to change the configurations, the UART interface remains active even if a subsequent uart.start() call fails. As a result, you can continue to use UART-related functions such as uart.send().


uart.send(string)

Sends data through the initialized UART interface.

This function is synchronous; it will wait and block further execution until the data transmission is completely finished.


uart.recv()

Received data is automatically stored in an internal buffer. You can retrieve this accumulated data by calling uart.recv().


uart.stop()

Closes the UART and returns the TX / RX IO to the initial (input) state.

Available for OS7.1.0 and later

After uart.stop(), you can call uart.start() again with different settings without rebooting.

The return value is 0 on success, and 1 if UART has not been started.

uart.stop();
uart.start(1, 2, 9600); -- restart with a different baud rate

uart.isUsed()

Returns whether the UART interface is currently in use.

Available for OS7.1.0 and later

The return value is true once uart.start() has succeeded, and false otherwise. Use it to skip re-initialization. To change the settings, call uart.stop() first.

if not uart.isUsed() then
  uart.start(1, 2, 115200);
end

Example

The following example demonstrates how to receive UART data and send it to the cloud. This script is designed to handle data even if it was received while the device was offline; once the connection is established, the data will be uploaded to the cloud sequentially.

```lua
os.log(" - Lua Start");

-- Set IO pins to retain their state
io.retain(1, true);
io.retain(2, true);

-- Initialize UART on IO1 (TX) and IO2 (RX) at 115200 baud
uart.start(1, 2, 115200);

-- Send initial message
uart.send("Hello World");

function on_online_loop()
-- Retrieve received data from the buffer
local ret = uart.recv();

-- Example: Limit receive buffer to 1 byte
-- local ret = uart.recv(1);

if #ret > 0 then
-- Echo back the received data via UART and also send it to the cloud
uart.send(ret);
cloud.pluginSend(ret);
end
end