/* Make avr-libc's printf etc. write to the serial port. (Originally written for the Arduino Transterpreter.) Adam Sampson */ #include #include #include #ifdef __AVR_ATmega8__ #define TXEN0 TXEN #define UBRR0H UBRRH #define UBRR0L UBRRL #define UCSR0A UCSRA #define UCSR0B UCSRB #define UDR0 UDR #define UDRE0 UDRE #endif static int serial_write(char c, FILE *f) { /* Wait for transmit buffer to be empty */ while ((UCSR0A & _BV(UDRE0)) == 0) ; /* Put byte into transmit buffer */ UDR0 = c; return 0; } void serial_stdout_init(long speed) { /* Set baud rate */ uint16_t factor = (F_CPU / 16 + speed / 2) / speed - 1; UBRR0H = factor >> 8; UBRR0L = factor; /* Set format (8N1). */ #ifdef __AVR_ATmega8__ /* The ATmega8 differs from the 328 in that you have to set URSEL to get the right register here, since UCSRC and UBRRH are actually the same register... */ UCSRC = _BV(URSEL) | (3 << UCSZ0); #else UCSR0C = 3 << UCSZ00; #endif /* Enable transmitter */ UCSR0B = _BV(TXEN0); /* Set up stdout to write to the serial port */ stdout = fdevopen(serial_write, NULL); }