Table of Contents

serial

`serial` opens a serial port, writes data, reads data, and can monitor incoming data asynchronously.

Read operations return `data_array` objects. Write operations accept a `data_array`, string, or single byte number.


Constructor

serial()

Creates a closed serial port object.

port = serial();
print(port.is_open());       // false

Methods

open(port)

Opens `port` using the default baud rate `115200`. Returns `true` on success.

port = serial();
ok = port.open('COM1');

open(port, baud)

Opens `port` using `baud`. Returns `true` on success.

port = serial();
ok = port.open('COM1', 9600);

close()

Closes the serial port and returns `true` on success.

port.close();

is_open()

Returns `true` when the serial port is open.

if (port.is_open())
{
    print('serial ready');
}

write(data)

Writes data and returns the number of bytes written. If writing fails, returns `none()` and stores the error text.

Arguments:

Argument Description
`data` `data_array`, string, or number. A number is written as one byte.
port.write('G0 X0 Y0\n');
port.write(13);

read()

Reads up to 256 bytes and returns a `data_array`.

data = port.read();

read(maxBytes)

Reads up to `maxBytes` bytes and returns a `data_array`.

data = port.read(64);

monitor(callback)

Starts asynchronous reading and returns `true` on success. The callback receives one argument: a `data_array` containing the received bytes.

function OnSerialData(data)
{
    print('bytes: ', data.size());
}
 
port = serial();
if (port.open('COM1', 115200))
{
    port.monitor(OnSerialData);
}

stop_monitor()

Stops asynchronous monitoring and returns `true` if monitoring was active.

port.stop_monitor();

is_monitoring()

Returns `true` while asynchronous monitoring is active.

last_error()

Returns the last serial error message, or an empty string when no error is stored.

if (!port.open('COM1'))
{
    print(port.last_error());
}

clear_error()

Clears the stored error message and returns `true`.

help()

Returns a short text summary of serial methods.

Previous: Comm

Next: Dialogs