Hi Matticus,
Thanks for your detailed reply, that was very helpful.
My next problem is, after reading numerous examples, I do not understand how to implement a circular buffer. Most examples have a buffer, push and pop functions.
So I understand main should be something like below, but I do not really understand. I want to read in hello, put in buffer, then print out buffer contents. I have tried to assemble an example I have found on another site but it is not working.
* read char
* push char into buffer
* pop last char out of buffert
* print out buffer
Code:
#include <stdio.h>
#include <stdlib.h>
#define CIRCBUF_DEF(x,y) unsigned char x##_space[y]; circBuf_t x = { x##_space,0,0,y}
typedef struct
{
unsigned char * const buffer;
int head;
int tail;
const int maxLen;
}circBuf_t;
CIRCBUF_DEF(cb, 6);
int circBufPush(circBuf_t *c, unsigned char data)
{
int next = c->head + 1;
if (next >= c->maxLen)
next = 0;
// Cicular buffer is full
if (next == c->tail)
return -1; // quit with an error
c->buffer[c->head] = data;
c->head = next;
return 0;
}
int circBufPop(circBuf_t *c, unsigned char *data)
{
// if the head isn't ahead of the tail, we don't have any characters
if (c->head == c->tail)
return -1; // quit with an error
*data = c->buffer[c->tail];
c->buffer[c->tail] = 0; // clear the data (optional)
int next = c->tail + 1;
if(next >= c->maxLen)
next = 0;
c->tail = next;
return 0;
}
unsigned char buffer(unsigned char data)
{
if (circBufPush(&cb, data))
{
printf("Out of space in CB\n");
}
if (circBufPop(&cb, &data))
{
printf("CB is empty\n");
}
return data;
}
int main()
{
char i;
unsigned char text[6] = "hello";
unsigned char data;
for(i = 0; i < 5; i++)
{
printf("%c", text[i]);
// I cant push data into the buffer
circBufPush(1,text[i]);
}
// print buffer contents
return 0;
}