updated serial system

This commit is contained in:
IMback
2018-11-14 11:29:12 +01:00
parent 18dc36e928
commit b72ec4ba8a
3 changed files with 42 additions and 28 deletions

View File

@ -18,14 +18,15 @@
#include <stdint.h>
template < int BUFFER_SIZE >
template < int BUFFER_SIZE, typename T = uint8_t >
class RingBuffer
{
private:
uint_fast16_t _headIndex = 0;
uint_fast16_t _tailIndex = 0;
uint8_t _buffer[BUFFER_SIZE];
volatile uint_fast16_t _headIndex = 0;
volatile uint_fast16_t _tailIndex = 0;
volatile bool _overrun = false;
volatile T _buffer[BUFFER_SIZE];
public:
@ -34,22 +35,29 @@ public:
flush();
}
uint_fast16_t remaining()
uint_fast16_t remaining() const volatile
{
return (_headIndex-_tailIndex);
}
bool isOverun(uint_fast16_t margin = 0)
uint_fast16_t remainingCapacity() const volatile
{
return remaining() >= BUFFER_SIZE - margin;
return BUFFER_SIZE - (_headIndex-_tailIndex);
}
bool isEmpty()
bool isOverun() volatile
{
bool returnVal = _overrun;
_overrun = false;
return returnVal;
}
bool isEmpty() const volatile
{
return _tailIndex >= _headIndex;
}
uint8_t read()
T read() volatile
{
if(!isEmpty())
{
@ -59,7 +67,7 @@ public:
else return '\0';
}
unsigned int read( uint8_t* buffer, unsigned int length )
unsigned int read( T* buffer, unsigned int length ) volatile
{
unsigned int i = 0;
for(; i < length && !isEmpty(); i++)
@ -69,7 +77,7 @@ public:
return i;
}
void write( uint8_t in )
void write( T in ) volatile
{
if (_headIndex - BUFFER_SIZE > 0 && _tailIndex - BUFFER_SIZE > 0)
{
@ -78,21 +86,26 @@ public:
}
_buffer[_headIndex % BUFFER_SIZE] = in;
_headIndex++;
if(remaining() > BUFFER_SIZE)
{
_overrun = true;
_tailIndex = _headIndex - BUFFER_SIZE;
}
}
void write( uint8_t* buffer, unsigned int length )
void write( T* buffer, const unsigned int length ) volatile
{
for(uint8_t i = 0; i < length; i++) write(buffer[i]);
for(unsigned int i = 0; i < length; i++) write(buffer[i]);
}
void flush()
void flush(T flushCharacter = ' ') volatile
{
_headIndex = 0;
_tailIndex = 0;
for(int i = 0; i < BUFFER_SIZE; i++) _buffer[i] = ' ';
for(int i = 0; i < BUFFER_SIZE; i++) _buffer[i] = flushCharacter;
}
unsigned int getString(uint8_t terminator, char* buffer, const unsigned int bufferLength)
unsigned int getString(T terminator, T* buffer, const unsigned int bufferLength) volatile
{
unsigned int i = 0;
for(; i <= remaining() && i <= BUFFER_SIZE && _buffer[(_tailIndex+i) % BUFFER_SIZE] != terminator; i++);
@ -100,7 +113,7 @@ public:
if( i < remaining() && i > 0)
{
if(i > bufferLength-1) i = bufferLength-1;
read((uint8_t*)buffer, i);
read(buffer, i);
buffer[i]='\0';
_tailIndex++;
}