Skip to content

Instantly share code, notes, and snippets.

@dagon666
Created October 4, 2013 18:32
Show Gist options
  • Save dagon666/6830489 to your computer and use it in GitHub Desktop.
Save dagon666/6830489 to your computer and use it in GitHub Desktop.
interrupt driven data reception
// the RX ring buffer
static volatile t_buffer g_rx_buff;
ISR(USART_RX_vect, ISR_BLOCK) {
// no frame error
// UCSR0A must be read before UDR0 !!!
if (bit_is_clear(UCSR0A, FE0)) {
/// must read the data in order to clear the interrupt flag
volatile unsigned char data = UDR0;
/// calculate the next available ring buffer data bucket index
volatile unsigned char next =
((g_rx_buff.head + 1) % SERIAL_RX_RING_SIZE);
/// do not overflow the buffer
if (next != g_rx_buff.tail) {
g_rx_buff.ring[g_rx_buff.head] = data;
g_rx_buff.head = next;
}
}
else {
/// must read the data in order to clear the interrupt flag
volatile unsigned char data __attribute__((unused)) = UDR0;
}
}
unsigned char serial_getc(unsigned char *a_data) {
if (g_rx_buff.head == g_rx_buff.tail)
return 0;
*a_data = g_rx_buff.ring[g_rx_buff.tail];
g_rx_buff.tail = (g_rx_buff.tail + 1) % SERIAL_RX_RING_SIZE;
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment