I coded a ring buffer for my Arduino to buffer data from either the SPI or TWI ports. In the .h file I used a pointer for the buffer:
typedef uint8_t *ring_buffer_t;
typedef uint8_t ring_count_t;
typedef uint8_t ring_index_t;
typedef uint8_t ring_size_t;
typedef struct ring_t
{
ring_buffer_t buffer;
ring_count_t count;
ring_index_t head;
ring_index_t tail;
ring_size_t size;
}rint_t;
int ring_init(ring_t *r, ring_buffer_t buffer, ring_size_t size);
// other function prototypes to add and remove from the ring buffer
There is more code to handle adding and removing from the buffer, but I am simplifying here. Then in my .c file I have:
#include<string.h>
void ring_init(ring_t *r, ring_buffer_t buffer, ring_size_t size)
{
r->buffer = buffer;
r->size = size;
r->head = 0;
r->tail = 0;
r->count = 0;
// clear out the buffer memset cheaper by 12 bytes rather than for loop
memset((void *)r->buffer, 0, r->size);
}
Then somewhere in code where the ring buffer is going to be used:
In SPI.h ...
#define MAX_BUFFER_SIZE 32
ring_t rx_ring;
uint8_t spi_rx_buffer[MAX_BUFFER_SIZE];
#define MAX_BUFFER_SIZE 32
ring_t tx_ring;
uint8_t spi_tx_buffer[MAX_BUFFER_SIZE];
In SPI.c ...
void spi_init( ... )
{
ring_init(&rx_ring, spi_rx_buffer, MAX_BUFFER_SIZE);
ring_init(&tx_ring, spi_tx_buffer, MAX_BUFFER_SIZE);
// initialize other spi parameters
}
Are there any issues with my code that are obvious that I am not seeing? I ask because I ran the code and it works, but I feel I am doing something wrong. I can code in C and remember something about malloc() for dynamic memory allocation, just not sure if what I am doing qualifies. Or should this work creating a buffer of some defined size?
Thanks for any help or ideas.
EDIT: 07/27/2014 Added code to try and make what I am trying to do clear. Let me know, thanks.