EmbeddedRelated.com

Circular FIFO Buffer

Dr. Maykel Alonso January 15, 20137 comments Coded in C

This code is a complete example of the implementation of a circular First In First Out (FIFO) buffer (also called ring buffer), it is very useful for communications of serial drivers storing the bytes before the analysis of them as a frame or something similar.

 

/***** circularBuffer.h *****/

#ifndef CIRCULAR_BUFFER_H_
#define CIRCULAR_BUFFER_H_

#define BUFFER_SIZE 128
#define TYPE char

// Check if the buffer it is full
bool isFull();

// Check if the buffer it is empty	
bool isEmpty();

// Get the first element from the FIFO queue
TYPE getElement();

// Add an element to the FIFO queue
bool addElement(TYPE data);

// Return the number of Elements that are in the FIFO queue
unsigned char getNumberOfElements();

#endif /*CIRCULAR_BUFFER_H_*/

/***** circularBuffer.cpp *****/

#include "circularBuffer.h"

TYPE Buffer[BUFFER_SIZE + 1]; // It needs 1 extra byte to difference full and empty
unsigned char next = 0;
unsigned char first = 0;

bool isFull(){
	if (getNumberOfElements() == BUFFER_SIZE){
		return true;
	}else{
		return false;
	}
}
	
bool isEmpty(){
	if ( next == first ){
		return true;
	}else{
		return false;
	}	
}
	
TYPE getElement(){
	TYPE theElement = 0;
	if (! isEmpty()){	 
		theElement =  Buffer[first];	
		if ( first != BUFFER_SIZE ){
			first++;
		}else{
			first = 0;
		}		
	}

	return theElement;// Return 0 always if it is empty, must be checked before
}

bool addElement(TYPE data){	
	if (!isFull()){
		 Buffer[next] = data;
		 if ( next != BUFFER_SIZE ){
			next++;
		 }else{
			 next = 0;
		 }
		return true;
	}else{
		return false;
	}	
}

unsigned char getNumberOfElements(){	
	if (next >= first){
		return (next - first);
	}else{
		return (BUFFER_SIZE - next + first);
	}	
}