`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.
Creates a closed serial port object.
port = serial(); print(port.is_open()); // false
Opens `port` using the default baud rate `115200`. Returns `true` on success.
port = serial(); ok = port.open('COM1');
Opens `port` using `baud`. Returns `true` on success.
port = serial(); ok = port.open('COM1', 9600);
Closes the serial port and returns `true` on success.
port.close();
Returns `true` when the serial port is open.
if (port.is_open()) { print('serial ready'); }
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);
Reads up to 256 bytes and returns a `data_array`.
data = port.read();
Reads up to `maxBytes` bytes and returns a `data_array`.
data = port.read(64);
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); }
Stops asynchronous monitoring and returns `true` if monitoring was active.
port.stop_monitor();
Returns `true` while asynchronous monitoring is active.
Returns the last serial error message, or an empty string when no error is stored.
if (!port.open('COM1')) { print(port.last_error()); }
Clears the stored error message and returns `true`.