STM32 Buffer FIFO – FIFO Buffer (Circular/Ring Buffer) for Packet Storage

bufferfifostm32

I am developing a simple radio transmission network using B-L072Z-LRWAN1 boards. The network structure is formed by:

  1. One board acting as a gateway (where data is received).
  2. Multiple boards acting as nodes (which send data to the gateway).

The packet payload sent by nodes is N bytes long and I want to store this packet's information in case gateway stops working and nodes cannot communicate with it. I want to keep data that could not be sent by the node and send it once the gateway is active again.

Let's say I want to keep the last M messages that node could not send to the gateway. The buffer size should be M*N bytes long, but how do I implement this type of buffer in C?

Thank you in advance!

Best Answer

    //pseudo algorithm First In First Out
    int FIFO[16]; // size of 2^N
    int WR_Ptr, RD_Ptr; // Write and read pointer
    int Input, Output;

    // On write event
    FIFO[WR_Ptr] = Input;
    WR_Ptr++; //increment WR pointer
    WR_Ptr &= 15 // apply mask 2^N-1, turn over in circular manner
    if WR_Ptr==RD_Ptr //buffer overrun?
    {
       //handle error
    }

    //On read event
    if WR_Ptr<>RD_Ptr //check if FIFO is not empty
    {
      Output = FIFO[RD_Ptr];
      RD_Ptr++; //increment RD pointer
      RD_Ptr &= 15 // apply mask 2^N-1, turn over in circular manner
    }

//clear FIFO
RD_Ptr = 0;
WR_Ptr = 0;