Skip to content

Instantly share code, notes, and snippets.

@CreateRemoteThread
Created March 25, 2018 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CreateRemoteThread/c1d8925f4b1720f816dcc0f829366b9a to your computer and use it in GitHub Desktop.
Save CreateRemoteThread/c1d8925f4b1720f816dcc0f829366b9a to your computer and use it in GitHub Desktop.
#define F_CPU 16000000UL
#define BAUD 9600
#include <util/setbaud.h>
#include <avr/io.h>
#include <stdio.h>
void uart_init(void) {
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
#if USE_2X
UCSR0A |= _BV(U2X0);
#else
UCSR0A &= ~(_BV(U2X0));
#endif
UCSR0C = _BV(UCSZ01) | _BV(UCSZ00); /* 8-bit data */
UCSR0B = _BV(RXEN0) | _BV(TXEN0); /* Enable RX and TX */
}
void uart_putchar(char c, FILE *stream) {
if (c == '\n') {
uart_putchar('\r', stream);
}
loop_until_bit_is_set(UCSR0A, UDRE0);
UDR0 = c;
}
char uart_getchar(FILE *stream) {
loop_until_bit_is_set(UCSR0A, RXC0); /* Wait until data exists. */
return UDR0;
}
FILE uart_output = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE);
FILE uart_input = FDEV_SETUP_STREAM(NULL, uart_getchar, _FDEV_SETUP_READ);
FILE uart_io = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW);
int main(void)
{
char buffer[128] = "HELLO WORLD\n";
char secret[128] = "SECRET DATA DO NOT PRINT\n";
uart_init();
stdout = &uart_output;
stdin = &uart_input;
printf(buffer);
while (1)
{
printf(buffer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment