Skip to content

Instantly share code, notes, and snippets.

@tmeissner tmeissner/avr_fifo.c
Last active Dec 19, 2015

Embed
What would you like to do?
Fifo implementation for AVR 8-bit controller
struct fifo {
uint8_t size; /* size of buffer in bytes */
uint8_t read; /* read pointer */
uint8_t write; /* write pointer */
unsigned char buffer[]; /* fifo ring buffer */
};
/* define a FIFO type for 'size' bytes */
#define MK_FIFO(size) \
struct fifo_ ## size { \
struct fifo f; \
unsigned char buffer_bytes[size]; \
}
/* define a fifo (type: struct fifo *) with name 'name' for 's' bytes */
#define DEFINE_FIFO(name, s) \
struct fifo_##s _raw_##name = { .f = { .size = s } }; \
struct fifo *name = &_raw_##name.f;
uint8_t FifoDataLength (struct fifo *fifo)
{
// return length of valid data in fifo
return (fifo->write - fifo->read) & (fifo->size - 1);
};
uint8_t FifoWrite (struct fifo *fifo, unsigned char data)
{
// fifo full : error
if (FifoDataLength(fifo) == (fifo->size - 1))
{
return 1;
}
// write data & increment write pointer
fifo->buffer[fifo->write] = data;
fifo->write = (fifo->write + 1) & (fifo->size - 1);
return 0;
};
uint8_t FifoRead (struct fifo *fifo, unsigned char *data)
{
// fifo empty : error
if (FifoDataLength(fifo) == 0)
{
return 1;
}
// read data & increment read pointer
*data = fifo->buffer[fifo->read];
fifo->read = (fifo->read + 1) & (fifo->size - 1);
return 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.