Hendrik Langer
8 years ago
5 changed files with 122 additions and 18 deletions
@ -0,0 +1,49 @@ |
|||||
|
#include "Arduino.h" |
||||
|
|
||||
|
#include "ringbuf.h" |
||||
|
|
||||
|
using namespace std; |
||||
|
|
||||
|
Ringbuf::Ringbuf(size_t buf_length) { |
||||
|
this->buf = (uint16_t *)malloc(buf_length); |
||||
|
Serial.print("Allocated buffer at: "); |
||||
|
Serial.println((int)this->buf,HEX); |
||||
|
this->buf_length = buf_length; |
||||
|
this->read_pos = 0; |
||||
|
this->write_pos = 0; |
||||
|
this->full = false; |
||||
|
} |
||||
|
|
||||
|
Ringbuf::~Ringbuf() { |
||||
|
free(this->buf); |
||||
|
} |
||||
|
|
||||
|
uint16_t *Ringbuf::getWrite() { |
||||
|
return this->buf + write_pos; |
||||
|
} |
||||
|
|
||||
|
size_t Ringbuf::getWriteAvail() { |
||||
|
if (full) return 0; // full
|
||||
|
else if (read_pos<=write_pos) return buf_length - write_pos; // to the end
|
||||
|
else return read_pos - write_pos; // between
|
||||
|
} |
||||
|
|
||||
|
uint16_t *Ringbuf::getRead() { |
||||
|
return this->buf + read_pos; |
||||
|
} |
||||
|
|
||||
|
size_t Ringbuf::getReadAvail() { |
||||
|
if (read_pos==write_pos && !full) return 0; // empty
|
||||
|
else if (read_pos>=write_pos) return buf_length - read_pos; // read til end
|
||||
|
else return write_pos - read_pos; |
||||
|
} |
||||
|
|
||||
|
void Ringbuf::setWrite(size_t bytes){ |
||||
|
write_pos = (write_pos+bytes)%buf_length; |
||||
|
if(read_pos==write_pos) full = true; |
||||
|
} |
||||
|
|
||||
|
void Ringbuf::setRead(size_t bytes){ |
||||
|
read_pos = (read_pos+bytes)%buf_length; |
||||
|
if(read_pos==write_pos) full = false; |
||||
|
} |
@ -0,0 +1,23 @@ |
|||||
|
#ifndef _RINGBUF_H |
||||
|
#define _RINGBUF_H |
||||
|
|
||||
|
|
||||
|
class Ringbuf { |
||||
|
public: |
||||
|
Ringbuf(size_t buf_length); |
||||
|
~Ringbuf(); |
||||
|
uint16_t *buf; |
||||
|
unsigned int buf_length; |
||||
|
unsigned int read_pos; |
||||
|
unsigned int write_pos; |
||||
|
uint16_t *getWrite(); |
||||
|
size_t getWriteAvail(); |
||||
|
uint16_t *getRead(); |
||||
|
size_t getReadAvail(); |
||||
|
void setWrite(size_t bytes); |
||||
|
void setRead(size_t bytes); |
||||
|
bool full; |
||||
|
private: |
||||
|
}; |
||||
|
|
||||
|
#endif /* _RINGBUF_H */ |
Loading…
Reference in new issue