Skip to content

Instantly share code, notes, and snippets.

@Wollw
Created February 18, 2013 04:03
Show Gist options
  • Save Wollw/4975052 to your computer and use it in GitHub Desktop.
Save Wollw/4975052 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include "serial.h"
#include <avr/pgmspace.h>
int main(void) {
serial_init(19200);
int i;
char buffer[8];
for(i = 0;; i ^= 1) {
if (!i) {
sprintf(buffer, "%s", "Foo");
} else {
sprintf(buffer, "%s", "Bar");
}
printf_P(PSTR("State: %s\r\n"), buffer);
}
}
#include <stdio.h>
#include <avr/io.h>
#include "serial.h"
void serial_init(uint32_t baudrate) {
// Set Baudrate
UBRR0H = (UBRR_ASYNC_NORMAL(baudrate) >> 8);
UBRR0L = UBRR_ASYNC_NORMAL(baudrate);
// Enable RX and TX
UCSR0B |= _BV(RXEN0) | _BV(TXEN0);
// Set 8N1 Framing
UCSR0C |= _BV(UCSZ00) | _BV(UCSZ01);
fdevopen(serial_write, serial_read);
}
int serial_write(char c, FILE *fp) {
(void)*fp;
while ( !(UCSR0A & (1 << UDRE0)) );
UDR0 = c;
return 0;
}
int serial_read(FILE *fp) {
(void)*fp;
while ( !(UCSR0A & (1 << RXC0)) );
return UDR0;
}
#ifndef SERIAL_H
#define SERIAL_H
#include <stdint.h>
#define UBRR_ASYNC_NORMAL(br) ((F_CPU / (br * 16UL)) - 1)
void serial_init(uint32_t baudrate); // Initializes Serial
int serial_write(char c, FILE *fp); // Send a character over serial
int serial_read(FILE *fp); // Read a character from serial buffer (blocking)
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment