if (transmitting)
return 0;
- if (buf_len == 0) // nothing received yet
- return 0;
-
if (get_clock() - last_rx < REQ_TIMEOUT) // still receiving
return 0;
- if (buf_len < 4) { // too short
- buf_len = 0;
- return 0;
- }
-
- if (buffer[0] != mb_unit_id) { // not for myself
+ if (buf_len < 4) { // too short (or not for us)
buf_len = 0;
return 0;
}
ISR(USART_RX_vect)
{
uint8_t rx_byte = UDR0;
+ clock_t now = get_clock();
+
+ if (transmitting) // how did we get here? discard it
+ goto out;
- if (transmitting) // discard it
- return;
+ if (buf_len && buffer[0] != mb_unit_id) // not for us
+ goto out;
- buffer[buf_len] = rx_byte;
+ if (buf_len == BUFSIZE) { // overrun - discard the packet
+ buffer[0] = 0xFF;
+ buf_len = 1;
+ goto out;
+ }
- if (buf_len + 1 < BUFSIZE) // ignore overruns
- buf_len++;
+ if (now - last_rx >= REQ_TIMEOUT) { // new packet; start over
+ buf_len = 0;
+ }
- last_rx = get_clock();
+ // TODO: we can probably calculate the CRC here as well
+ buffer[buf_len++] = rx_byte;
+out:
+ last_rx = now;
}
ISR(USART_TX_vect)