diff --git a/src/omv/ringbuf.c b/src/omv/ringbuf.c new file mode 100644 index 000000000..329f46de5 --- /dev/null +++ b/src/omv/ringbuf.c @@ -0,0 +1,45 @@ +/* + * This file is part of the OpenMV project. + * Copyright (c) 2013/2014 Ibrahim Abdelkader + * This work is licensed under the MIT license, see the file LICENSE for details. + * + * Simple Ring Buffer implementation. + * + */ +#include +#include +#include "ringbuf.h" + +void ring_buf_init(ring_buf_t *buf) +{ + memset(buf, 0, sizeof(*buf)); +} + +int ring_buf_empty(ring_buf_t *buf) +{ + return (buf->head == buf->tail); +} + +void ring_buf_put(ring_buf_t *buf, uint8_t c) +{ + if ((buf->tail + 1) % BUFFER_SIZE == buf->head) { + /*buffer is full*/ + return; + } + + buf->data[buf->tail] = c; + buf->tail = (buf->tail + 1) % BUFFER_SIZE; +} + +uint8_t ring_buf_get(ring_buf_t *buf) +{ + uint8_t c; + if (buf->head == buf->tail) { + /*buffer is empty*/ + return 0; + } + + c = buf->data[buf->head]; + buf->head = (buf->head + 1) % BUFFER_SIZE; + return c; +} diff --git a/src/omv/ringbuf.h b/src/omv/ringbuf.h new file mode 100644 index 000000000..3b0a7920c --- /dev/null +++ b/src/omv/ringbuf.h @@ -0,0 +1,24 @@ +/* + * This file is part of the OpenMV project. + * Copyright (c) 2013/2014 Ibrahim Abdelkader + * This work is licensed under the MIT license, see the file LICENSE for details. + * + * Simple Ring Buffer implementation. + * + */ +#ifndef __RING_BUFFER_H__ +#define __RING_BUFFER_H__ +#include +#define BUFFER_SIZE (1024) + +typedef struct ring_buffer { + volatile uint32_t head; + volatile uint32_t tail; + uint8_t data[BUFFER_SIZE]; +} ring_buf_t; + +void ring_buf_init(ring_buf_t *buf); +int ring_buf_empty(ring_buf_t *buf); +void ring_buf_put(ring_buf_t *buf, uint8_t c); +uint8_t ring_buf_get(ring_buf_t *buf); +#endif /* __RING_BUFFER_H__ */