Initial commit
This commit is contained in:
90
serial.cpp
Normal file
90
serial.cpp
Normal file
@ -0,0 +1,90 @@
|
||||
#include "serial.h"
|
||||
|
||||
char rxBuffer[BUFFER_SIZE];
|
||||
volatile uint16_t interruptIndex = 0;
|
||||
|
||||
ISR (USART_RX_vect) //I have seen worse interrupt sintax
|
||||
{
|
||||
rxBuffer[interruptIndex % BUFFER_SIZE] = UDR0;
|
||||
interruptIndex++;
|
||||
}
|
||||
|
||||
Serial::Serial()
|
||||
{
|
||||
UBRR0H = UBRRH_VALUE;
|
||||
UBRR0L = UBRRL_VALUE;
|
||||
UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);
|
||||
UCSR0B = _BV(RXEN0) | _BV(TXEN0); //Enable RX and TX
|
||||
UCSR0B |= (1 << RXCIE0); //Enable Rx interuppt
|
||||
}
|
||||
|
||||
void Serial::putChar(const char c)
|
||||
{
|
||||
loop_until_bit_is_set(UCSR0A, UDRE0);
|
||||
UDR0 = c;
|
||||
}
|
||||
|
||||
void Serial::putString(const char* in, const unsigned int length)
|
||||
{
|
||||
for(unsigned int i = 0; i < length; i++)
|
||||
{
|
||||
putChar(in[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void Serial::putString(const char in[])
|
||||
{
|
||||
for(unsigned int i = 0; i < strlen(in); i++)
|
||||
{
|
||||
putChar(in[i]);
|
||||
}
|
||||
}
|
||||
|
||||
bool Serial::dataIsWaiting()
|
||||
{
|
||||
return (interruptIndex > _rxIndex);
|
||||
}
|
||||
|
||||
char Serial::getChar()
|
||||
{
|
||||
if( _rxIndex >= (32768) - 2*BUFFER_SIZE ) flush(); //may explode only occasionaly
|
||||
if(dataIsWaiting())
|
||||
{
|
||||
_rxIndex++;
|
||||
return rxBuffer[(_rxIndex -1) % BUFFER_SIZE];
|
||||
}
|
||||
else return '\0';
|
||||
}
|
||||
|
||||
int Serial::getString(char* buffer, const int bufferLength)
|
||||
{
|
||||
int i = 0;
|
||||
for(; i <= (interruptIndex-_rxIndex) && i <= BUFFER_SIZE && rxBuffer[(_rxIndex+i) % BUFFER_SIZE] != _terminator; i++);
|
||||
|
||||
if( i < (interruptIndex-_rxIndex) && i > 0)
|
||||
{
|
||||
for(int j = 0 ; j < i && j < bufferLength ; j++)
|
||||
{
|
||||
buffer[j] = getChar();
|
||||
}
|
||||
_rxIndex++;
|
||||
}
|
||||
else
|
||||
{
|
||||
i = 0;
|
||||
if( _rxIndex >= (32768) - 2*BUFFER_SIZE ) flush();
|
||||
}
|
||||
|
||||
if (rxBuffer[(_rxIndex+i) % BUFFER_SIZE] == _terminator) _rxIndex++;
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
void Serial::flush()
|
||||
{
|
||||
_rxIndex = 0;
|
||||
interruptIndex = 0;
|
||||
for(int i = 0; i < BUFFER_SIZE; i++) rxBuffer[i] = ' ';
|
||||
}
|
||||
|
||||
void Serial::setTerminator(char terminator){_terminator = terminator;}
|
Reference in New Issue
Block a user