USART revised

This commit is contained in:
Tristan Krause 2019-04-03 14:51:33 +02:00
parent 2d26632f41
commit 787fc6f784
7 changed files with 108 additions and 191 deletions

View file

@ -12,8 +12,6 @@ void USART::init() volatile
// setze Baudrate
UBRR0H = (((F_CPU / (8UL * BAUDRATE))-1) >> 8) & 0xFF;
UBRR0L = ((F_CPU / (8UL * BAUDRATE))-1) & 0xFF;
send_active = false;
}
void USART::clearInputBuffer() volatile
@ -38,7 +36,7 @@ void USART::initRX(void) volatile
void USART::initTX(void) volatile
{
while(send_active);
while(active);
send_pos = 0;
send_crc = 0;
}
@ -71,7 +69,7 @@ void USART::handleTX(void) volatile
}
else
{
send_active = false;
active = false;
}
}
@ -82,7 +80,7 @@ void USART::flush(void) volatile
send_len = send_pos;
send_pos = 0;
send_active = true;
active = true;
handleTX();
}
@ -122,28 +120,6 @@ void USART::writeCRC(void) volatile
writeByte(send_crc);
}
uint8_t USART::writeBlock(uint8_t* ptr, uint8_t len) volatile
{
writeByte(len);
uint8_t crc = 0;
while(len--)
{
writeByte(*ptr);
crc ^= *ptr++;
for (uint8_t i = 0; i < 8; i++)
{
if (crc & 1)
crc ^= CRC7_POLY;
crc >>= 1;
}
}
writeByte(crc);
return readByte();
}
uint8_t USART::readByte() volatile
{
return receive_buffer[receive_pos++];
@ -155,120 +131,3 @@ uint16_t USART::readInt() volatile
v |= readByte() << 8;
return v;
}
void USART::nextByte(uint8_t byte) volatile
{
switch(seq)
{
case IDLE:
{
if(byte > MAX_BLOCK_SIZE)
{
clearInputBuffer();
writeByte(MSG_FAIL);
seq = BlockSequence::IDLE;
}
else
{
block_buffer[0] = byte;
crc = 0;
block_pos = 0;
seq = BlockSequence::LEN;
}
break;
}
case LEN:
{
block_buffer[block_pos] = byte;
seq = BlockSequence::DATA;
break;
}
case DATA:
{
block_buffer[block_pos] = byte;
crc ^= byte;
for (uint8_t i = 0; i < 8; i++)
{
if (crc & 1)
crc ^= CRC7_POLY;
crc >>= 1;
}
if(block_pos == block_buffer[0])
seq = BlockSequence::CRC;
else if(block_pos >= block_buffer[0])
{
clearInputBuffer();
writeByte(MSG_FAIL);
seq = BlockSequence::IDLE;
}
break;
}
case CRC:
{
block_buffer[block_pos] = byte;
crc ^= byte;
for (uint8_t i = 0; i < 8; i++)
{
if (crc & 1)
crc ^= CRC7_POLY;
crc >>= 1;
}
seq = BlockSequence::END;
break;
}
case END:
{
clearInputBuffer();
writeByte(crc == 0 ? MSG_OK : MSG_FAIL);
seq = BlockSequence::IDLE;
break;
}
}
block_pos++;
}
void USART::readBlock(uint8_t* ptr, uint8_t offset) volatile
{
ptr += offset;
uint8_t crc = 0x7F;
do
{
uint8_t len = readByte();
if(len == 0x80) // out of sync, war bereits stoppbyte
{
writeByte(MSG_FAIL);
continue;
}
else if(len > MAX_BLOCK_SIZE)
len = 0;
crc = 0;
for(uint8_t k = 0; k <= len; k++) // len + 1 Durchgänge (+ crc)
{
uint8_t next = readByte();
crc ^= next;
for (uint8_t i = 0; i < 8; i++)
{
if (crc & 1)
crc ^= CRC7_POLY;
crc >>= 1;
}
if(k < len)
ptr[k] = next;
}
clearInputBuffer(); // leere Eingangspuffer
writeByte(crc == 0 ? MSG_OK : MSG_FAIL);
}
while(crc != 0);
}