Skip to content
Snippets Groups Projects
user avatar
Charles JAVERLIAT authored
Closes #1
69ef3560

Serial framing protocol for Mbed

This library provides the SFPSerial module, a serial transmitter/receiver which embeds the serial framing protocol.

How-to-use

Simply includes SFPSerial.hpp and instantiate with its constructor SFPSerial(PinName tx, PinName rx, unsigned int baudrate).

Then, all you have to do is send a message in form of an array of bytes via serial.sendData(const uint8_t *data, const uint16_t dataSize). This will frame the data using the serial framing protocol and send it through the serial port.

If you want to receive a message, you will have to check if one or more frames are availables to be read via serial.readable() and then call serial.readData(uint8_t* dataDst, uint16_t* dataDstSize).

Examples

Sending data

#include "mbed.h"
#include "SFPSerial.hpp"

SFPSerial serial(USBTX, USBRX, 115200);

int main() {

    wait_us(2 * 1000 * 1000);

    uint8_t dataBuf[3] = {0x12, 0x34, 0x56};

    while(1) {

        if(serial.writeable()) {
            serial.sendData(dataBuf, 3);
        }

        wait_us(1000 * 1000);
    }

    return 0;
}

The actual byte sent are 0x7e 0x0 0x3 0x12 0x34 0x56 0xbf 0x12 0x7f. In those bytes:

  • 0x7e is the start of frame flag
  • 0x0 0x3 is the data size encoded on 2 bytes
  • 0x12 0x34 is the data we are sending
  • 0xbf 0x12 is the cyclic redundancy check (CRC) encoded on 2 bytes, it helps checking for any corruption of the data
  • 0x7f is the end of frame flag

The receiver on the other side will have to implement to SFP in order to decode the message and check for any corruption errors.

Reading data frame

#include "mbed.h"

#include "SFP.hpp"
#include "SFPSerial.hpp"

SFPSerial serial(USBTX, USBRX, 115200);

int main() {

    // Wait for the serial to be set up.
    wait_us(2 * 1000 * 1000);

    uint8_t dataBuf[256];
    uint16_t dataBufSize;

    while(1) {

        if(serial.readable()) {
            
            uint8_t resultCode = serial.readData(dataBuf, &dataBufSize);

            if(resultCode == 0) {
                // Do something with data...
            } else {
                // Error while reading the data, either SFP::ERR_MISSING_SOF_DELIMITER, SFP::ERR_MISSING_EOF_DELIMITER or SFP::ERR_CORRUPTED_DATA.
            }
        }
    }

    return 0;
}