Circular buffer for structs?

I've seen various circular buffer libraries for primitive data types, however I have an interrupt that receives a struct from a MCP2515 CAN bus controller.

There are 2 fields of importance, uint16_t for the Id and 8 bytes for the payload which doesn't have a specific type. There's also a byte for the payload length, but that is always 8, so can be ignored.

The data arrives in bursts so I need a way of buffering it so I can later deal with it in the main loop.
Do I just create an array of structs with volatile variables then store the head and tail and use nointerrupts() to protect the access in the main loop?

struct Packet{
  volatile uint16_t Id;
  volatile uint8_t buffer[8];
};

Packet can_data[32]; // Big enough to hold a burst of messages

volatile uint8_t head = 0;
volatile uint8_t tail = 0;

and 8 bytes for the payload which doesn't have a specific type.

Of course it does. The type is byte array.

Do I just create an array of structs with volatile variables then store the head and tail and use nointerrupts() to protect the access in the main loop?

Yep.

Seems right to me :slight_smile:

mikb55:
Do I just create an array of structs with volatile variables then store the head and tail and use nointerrupts() to protect the access in the main loop?

That sounds right.

Do you really need to read the incoming data within your ISR - as opposed to a simple ISR that raises a flag to tell your main code that data is available?

...R

Robin2:
That sounds right.

Do you really need to read the incoming data within your ISR - as opposed to a simple ISR that raises a flag to tell your main code that data is available?

...R

I cannot guarantee that the main loop is fast enough to deal with bursts of incoming data.

mikb55:
I cannot guarantee that the main loop is fast enough to deal with bursts of incoming data.

I could :slight_smile:

...R

Robin2:
I could :slight_smile:

...R

Show your calculations.

mikb55:
Show your calculations.

No calculations needed. The key is to NOT write blocking code and to not call blocking code that others have written.

If there is time to do it in the ISR, there is time to do it in some other function, as long as there is no time wasted twiddling thumbs. For whatever "it" is.

mikb55:
Show your calculations.

You first. I'm shy.

And I agree with @PaulS. The reality is that calling an ISR uses extra CPU cycles that would not be needed if polling could do the job.

...R