Created
December 24, 2021 02:55
-
-
Save twopoint718/1aab77210682a914dd2c3adf9ace0197 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <stdio.h> | |
#define BUFFER_SIZE 16 | |
struct Buffer { | |
uint8_t data[BUFFER_SIZE]; | |
uint8_t newest_index; | |
uint8_t oldest_index; | |
}; | |
/* static struct Buffer buffer; */ | |
enum BufferStatus {BUFFER_OK, BUFFER_EMPTY, BUFFER_FULL}; | |
enum BufferStatus bufferWrite(volatile struct Buffer *buffer, uint8_t byte) { | |
uint8_t next_index = ((buffer->newest_index)+1) % BUFFER_SIZE; | |
if (next_index == buffer->oldest_index) { | |
return BUFFER_FULL; | |
} | |
buffer->data[buffer->newest_index] = byte; | |
buffer->newest_index = next_index; | |
return BUFFER_OK; | |
} | |
enum BufferStatus bufferRead(volatile struct Buffer *buffer, uint8_t *byte) { | |
if (buffer->newest_index == buffer->oldest_index) { | |
return BUFFER_EMPTY; | |
} | |
*byte = buffer->data[buffer->oldest_index]; | |
buffer->oldest_index = ((buffer->oldest_index)+1) % BUFFER_SIZE; | |
return BUFFER_OK; | |
} | |
volatile struct Buffer rx_buffer = {{}, 0, 0}; | |
ISR(USART_RX_vect) { | |
bufferWrite(&rx_buffer, UDR0); | |
} | |
int main(int argc, char **argv) { | |
uint8_t received_byte; | |
enum BufferStatus status; | |
while(1) { | |
status = bufferRead(&rx_buffer, &received_byte); | |
if (status == BUFFER_OK) { | |
printf("%c", received_byte); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment