Skip to content

About

Arduino library to transfer dynamic, packetized data fast and reliably via Serial, I2C, etc.

Topics

Resources

Code of conduct

Stars

487 stars

Watchers

21 watching

Forks

Repository files navigation

SerialTransfer

GitHub version arduino-library-badge

SerialTransfer is an easy to use Arduino library for transferring packetized data fast and reliably via Serial and I²C interfaces. Interconnect your Arduinos today minus the headache with SerialTransfer!

A mirror library is also available for Python!

SerialTransfer sends messages of up to 255 bytes over Arduino Serial/UART or I²C. Each message carries a packet ID and a checksum. A sketch can send a sensor reading, receive a command, or split a file across several packets. For a computer talking to a board over USB serial, use the companion pySerialTransfer library.

Quick start: echo a packet over USB

You need one Arduino-compatible board, a USB data cable, the Arduino IDE, and Python on your computer. If you want to connect two boards instead, start with the example guide.

1. Install both ends

Install the Arduino library from this checkout. If it is already at <sketchbook>/libraries/SerialTransfer, it is ready to use. Otherwise, place the library folder there, with library.properties directly inside it, then restart the IDE. You can also import the library ZIP using Sketch > Include Library > Add .ZIP Library. Arduino library installation guide

Plug in the board, then open a terminal in the pySerialTransfer repository folder and run the following. Use the companion checkout that documents START | ID | LENGTH | PAYLOAD | CRC. Older releases using byte stuffing and a stop byte use a different protocol.

python -m pip install -e .
pySerialTransfer ports

Make a note of the device name, for example COM3 or /dev/ttyACM0.

2. Upload the echo sketch

Connect the board to the computer with a USB data cable. The sketch below uses the board port exposed to the computer as Serial. Select the board and port in the Arduino IDE, paste the sketch into a new sketch window, and upload it. Close the IDE's Serial Monitor before opening the port in Python.

#include <SerialTransfer.h>

SerialTransfer transfer;

void setup() {
  Serial.begin(115200);
  transfer.begin(Serial, false);
}

void loop() {
  if (transfer.tick()) {
    // Return the original payload and packet ID.
    memcpy(transfer.packet.txBuff, transfer.packet.rxBuff, transfer.bytesRead);
    transfer.sendData(transfer.bytesRead, transfer.currentPacketID());
  }
}

For a USB-to-UART adapter, use a board with an available hardware UART such as Serial1. Change both occurrences of Serial in setup() to that UART. Connect adapter TX to board RX1, adapter RX to board TX1, and GND to GND. Use an adapter with logic levels compatible with the board. Select the adapter's port in Python. On a direct USB connection, the USB cable handles both directions.

3. Send a packet from Python

Save the following as echo.py. It sends the word hello with packet ID 1, waits for its reply on the same open connection, then closes the port.

import sys
import time
from pySerialTransfer import pySerialTransfer as txfer

port = sys.argv[1]
link = txfer.SerialTransfer(port, baud=115200)
try:
    if not link.open():
        raise OSError(f"Could not open {port}")
    time.sleep(2)  # Some boards restart when the port opens.
    size = link.tx_obj("hello")
    if size is None or not link.send(size, packet_id=1):
        raise OSError("Could not send hello")

    deadline = time.monotonic() + 3
    while time.monotonic() < deadline:
        link.available()
        if link.status == txfer.Status.NEW_DATA and link.id_byte == 1:
            print(bytes(link.rx_buff[:link.bytes_read]).decode("utf-8"))
            break
        time.sleep(0.001)
    else:
        raise TimeoutError("No echo within three seconds")
finally:
    link.close()

Run python echo.py COM3 with the port you found earlier. On Linux or macOS, substitute the full device name. Printing hello confirms that the packet reached the board and the reply reached Python.

If the echo times out

  • Run pySerialTransfer ports again after unplugging and reconnecting the cable to identify the board. Close programs already using that port.
  • Check the stream used in setup() and the baud rate at both ends (115200 here). Keep Serial.print() diagnostics off the port that carries packets.
  • If the board resets when its port opens, allow it to finish booting before sending. If you see repeated CRC errors, check the wiring and that both checkouts describe the same frame.

Working with payloads

txObj(value, offset) copies the bytes of a value and returns the next offset. Chain those offsets to pack several fields. sendData(length, id) writes one packet. transmissionStatus == 0 means the transport accepted the frame. Applications that need confirmation from the receiver can send a reply with an ID of their choice.

On reception, tick() returns true when a packet completes, including an empty packet. Read currentPacketID(), bytesRead, and the payload before polling again. If you use available(), check status == NEW_DATA to distinguish an empty packet from an idle poll.

For example, an Arduino that stores integers in little-endian order can send an unsigned 16-bit channel number and a signed 32-bit count like this:

uint16_t channel = 3;
int32_t count = -42;
uint16_t pos = link.txObj(channel);
pos = link.txObj(count, pos);
link.sendData(pos, 7);

The receiving Arduino should check for ID 7 and exactly 6 bytes before calling rxObj(channel) and rxObj(count, sizeof(channel)). Python can decode the same payload with struct.unpack("<Hi", payload). Both helpers on Arduino copy the object's memory representation. Agree on widths and byte order. For portable layouts, send fields individually and encode byte order explicitly where needed. Pointers and the bytes of an Arduino String object are not a text encoding.

Advanced: how framing and recovery work

Field Bytes Meaning
Start 1 Always 0x7E.
ID 1 Application-defined message type, 0 to 255.
Length 1 Number of payload bytes, 0 to 255.
Payload Length Any bytes, including 0x00 and 0x7E.
CRC 1 CRC-8 over ID, length, and payload, in that order.

CRC calculation starts at zero, uses polynomial 0x9B, processes the most significant bit first, and applies no final XOR. For example, ID 0 with payload 01 02 03 04 produces the eight wire bytes 7E 00 04 01 02 03 04 6A. Once the parser knows the length, it can consume a literal 0x7E inside the payload. There is no escaping or trailing delimiter.

An empty packet occupies four bytes, and a full packet occupies 259. A CRC failure discards the frame. A truncated frame can hold the parser until more bytes arrive or its inter-byte timeout expires. Call available() or tick() frequently. The simple UART initializer uses a 50 ms timeout. With configST, set timeout in milliseconds. Use 0 or UINT32_MAX to disable it. UART timing is measured as the sketch reads bytes. The stream does not supply arrival timestamps for bytes already in its buffer. CRC_ERROR has value zero, and STALE_PACKET_ERROR indicates that an incomplete frame timed out.

Callbacks

Configure a configST with a function-pointer array and its entry count. Index 0 handles packet ID 0, index 1 handles ID 1, and so on. Keep the table alive for as long as the transfer uses it. Poll in loop() and read the finished payload inside the callback. The Serial callback example shows the complete sketch.

I²C between two boards

Use I2CTransfer.h and call Wire.begin() on the controller or Wire.begin(address) on the target before link.begin(Wire). Connect SDA to SDA, SCL to SCL, and ground to ground. Use compatible bus voltages and pull-ups. The controller sends with sendData(length, id, address). The frame uses the same CRC and length as UART but can span several Wire transactions (32 bytes per transaction by default).

The target queues up to 259 wire bytes. Poll available() or tick() in the main loop to parse them and dispatch callbacks. Read the payload before the next poll. If a whole incoming Wire transaction cannot fit, it is dropped and the receiver can report PAYLOAD_ERROR. Pace packets or acknowledge each one before sending the next. The controller initiates reads for target replies.

Keep the TwoWire object alive while the transfer uses it. Stop incoming traffic before calling end(), changing buses, or destroying the transfer, because some Wire cores dispatch receive callbacks from a separate task.

Use one active I2CTransfer instance per board. If your Wire implementation has a smaller transmit buffer, set the last argument of begin to its capacity, for example link.begin(Wire, false, Serial, 16). The transaction size controls how the sender divides a frame on the bus. The packet length still describes the whole payload. See I²C quick start and acknowledged I²C file transfer.

Files and older sketches

The example guide distinguishes the simple one-way file protocol from the UART and I²C examples with acknowledgements and retries. Sender and receiver must use the same example protocol. The legacy archive includes historical sketches, including SPI, which is unavailable in the current library.

About

Arduino library to transfer dynamic, packetized data fast and reliably via Serial, I2C, etc.

Topics

Resources

Code of conduct

Stars

487 stars

Watchers

21 watching

Forks

Releases

Packages

Used by

Contributors

Languages