serial

RS-485 serial ports: initialise, transmit, and receive delimited messages with a callback.

The serial object drives the device's RS-485 serial ports:

Port Hardware
1 RS-485 port

Initialise the port with a baud rate, register a delimiter-based receive callback, and transmit with serial.tx(). For device-to-device links over untrusted wiring, combine with aes.enc/aes.dec and bin.toHex/ bin.fromHex to send encrypted, checksummed messages — see the Serial Port: Encrypted Device-to-Device example.

The same ports can also speak Modbus RTU directly via modbus.read() / modbus.write() with the matching port number — see the Serial Modbus (RS-485) example.

Functions

serial.init()

serial.init(port, baud) → number

Initialises a serial port at the given baud rate.

Specify a parameter object for advanced usage

serial.init(port,{baud:9600,stopBits:1,parity:"odd",mode:"0,swap:false,invert:false});

:Mode 0: tx+rx, 1: rx only, 2: tx only,

:Invert Invert the RS485 high low signaling (Experimental)

Arguments

NameTypeRequiredDefaultDescription
port number yes 1 = isolated RS-485, 2 = non-isolated RS-485.
baud | config number | object yes Baud rate, e.g. 9600, 19200. for standard 8n1 settings otherwise supply a json object with parameters

Returns

number Status code — 0 on success.

Example

let port = 1;             // isolated RS-485
serial.init(port, 19200);

serial.listen()

serial.listen(port, delimiter, callback)

Buffers received bytes and calls the callback whenever the delimiter character arrives.

Fills the receive buffer while watching for the delimiter character, then executes the callback with a message object:

Field Meaning
msg.port Port the message arrived on.
msg.ovf true if the receive buffer overflowed — discard the message.
msg.data The received data.

Arguments

NameTypeRequiredDefaultDescription
port number yes 1 = isolated RS-485, 2 = non-isolated RS-485.
delimiter string yes End-of-message character, e.g. "\r".
callback function yes Callback function(msg){ … } — see the field table.

Example

function serialRxCallback(msg){
  print("Received Serial Msg");
  print("Port:", msg.port);
  print("Overflowed:", msg.ovf);
  print("Data:", msg.data);
}

serial.listen(port, "\r", serialRxCallback);

serial.tx()

serial.tx(port, data)

Transmits data on a serial port.

Sends data out the port. Remember to append your protocol's end-of-message delimiter (e.g. "\r") so the receiver's serial.listen() fires.

Arguments

NameTypeRequiredDefaultDescription
port number yes 1 = isolated RS-485, 2 = non-isolated RS-485.
data string yes Data to send — hex-encode binary payloads with bin.toHex().

Example

serial.tx(port, "Hello World over serial!\r");