Skip to content

Instantly share code, notes, and snippets.

@ChuckM
Last active September 7, 2018 23:23
Show Gist options
  • Save ChuckM/a82fc630a8de6b5b8d6bfe9f329daebf to your computer and use it in GitHub Desktop.
Save ChuckM/a82fc630a8de6b5b8d6bfe9f329daebf to your computer and use it in GitHub Desktop.
Transmitting characters with the interrupt sub system
#define BUF_SIZE 16
char ring_buf[BUF_SIZE];
uint8_t cur_char, nxt_char = 0;
void _write_char(char *c)
{
/* ring buffer is full, wait for isr to drain a character out of it */
while (((cur_char + 1) % BUF_SIZE) == nxt_char) ;
/* Is the USART idle? Then just write the character */
if ((USART_TXE == 1) && (cur_char == nxt_char)) {
USART_DR = c;
return;
}
/* Else stick it into the ring buffer, ISR will get it */
ring_buf[nxt_char++] = c; // store char
nxt_char = nxt_char % BUF_SIZE; // update ring buffer
return;
}
usart_isr(void)
{
/* Is the transmitter buffer empty? */
if (USART_TXE) {
/* yes: Is there a character in the ring buffer that hasn't been sent? */
if (cur_char != nxt_char) {
USART_DR = ring_buf[cur_char++]; // write char
cur_char = cur_char & BUF_SIZE; // update ring buffer
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment