Circular Buffer

Moderator: Benj

Post Reply
mnf
Valued Contributor
Valued Contributor
Posts: 1189
Joined: Wed May 31, 2017 11:57 am
Has thanked: 70 times
Been thanked: 439 times
Contact:

Circular Buffer

Post by mnf »

Mentioned this briefly in passing in the forum.

Circular buffer GetNumberOfBytes - doesn't return correct value.
circular_buffer_bug.fcfx
(9.04 KiB) Downloaded 146 times
Demonstrates (in simulation or on hardware) - the circular buffer size (in my demo) is 128 bytes - but the maximum size returned by GetNumberOfBytes is 127.

I think the error is in GetNumberofBytes:

Code: Select all

    if (FCV_01211_CircularBuffer1__DATAEND > FCV_01211_CircularBuffer1__DATASTART)
    {

        // .Return = DataEnd - DataStart
        FCR_RETVAL = FCV_01211_CircularBuffer1__DATAEND - FCV_01211_CircularBuffer1__DATASTART;

Following PutByte - DATAEND has a maximum value (the index into the buffer) or 127 - and if DATASTART = 0 (buffer full for the first time) - then the maximum value returned will be 127. This, however, is the index of the final byte rather than the number of bytes. I didn't attempt the math for other possibilities but the value should be +1 here.

PutBytes - looks correct (FCL_TEMP >=128) so reading data from the buffer will possibly lose a byte????

Martin

mnf
Valued Contributor
Valued Contributor
Posts: 1189
Joined: Wed May 31, 2017 11:57 am
Has thanked: 70 times
Been thanked: 439 times
Contact:

Re: Circular Buffer

Post by mnf »

I found an excellent article on this at https://embedjournal.com/implementing-c ... mbedded-c/
Having the maximum length of data as one byte less than the buffer size is a reasonable trade off against code complexity - and possibly the easiest way to maintain sanity is to allocate a buffer of required size+1 bytes..

Martin

User avatar
Benj
Matrix Staff
Posts: 15312
Joined: Mon Oct 16, 2006 10:48 am
Location: Matrix TS Ltd
Has thanked: 4803 times
Been thanked: 4314 times
Contact:

Re: Circular Buffer

Post by Benj »

Hi Martin,

Maintaining sanity is a good thing :D

At the moment totally filling the buffer would be the same as having an empty buffer in terms of the pointers we use to track things. We could have an additional count variable to track the number of entries in the buffer. I could potentially make this an optional property so you can switch between -1 and totally full.

I don't think we're currently loosing any data but if you find any problems regarding this then please let us know.

Post Reply