3 * Copyright (c) 2006-2012 by Roland Riegel <feedback@roland-riegel.de>
5 * This file is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
11 #include <avr/interrupt.h>
13 #include <avr/pgmspace.h>
14 #include <avr/sfr_defs.h>
15 #include <avr/sleep.h>
19 /* some mcus have multiple uarts */
38 #define UCSRC_SELECT 0
40 #define UCSRC_SELECT (1 << URSEL)
43 #ifndef USART_RXC_vect
44 #if defined(UART0_RX_vect)
45 #define USART_RXC_vect UART0_RX_vect
46 #elif defined(UART_RX_vect)
47 #define USART_RXC_vect UART_RX_vect
48 #elif defined(USART0_RX_vect)
49 #define USART_RXC_vect USART0_RX_vect
50 #elif defined(USART_RX_vect)
51 #define USART_RXC_vect USART_RX_vect
52 #elif defined(USART0_RXC_vect)
53 #define USART_RXC_vect USART0_RXC_vect
54 #elif defined(USART_RXC_vect)
55 #define USART_RXC_vect USART_RXC_vect
57 #error "Uart receive complete interrupt not defined!"
62 #define UBRRVAL (F_CPU/(BAUD*16)-1)
69 UBRRL = UBRRVAL & 0xff;
70 /* set frame format: 8 bit, no parity, 1 bit */
71 UCSRC = UCSRC_SELECT | (1 << UCSZ1) | (1 << UCSZ0);
72 /* enable serial receiver and transmitter */
74 UCSRB = (1 << RXEN) | (1 << TXEN);
76 UCSRB = (1 << RXEN) | (1 << TXEN) | (1 << RXCIE);
80 void uart_putc(uint8_t c)
85 /* wait until transmit buffer is empty */
86 while(!(UCSRA & (1 << UDRE)));
92 void uart_putc_hex(uint8_t b)
96 uart_putc((b >> 4) + '0');
98 uart_putc((b >> 4) - 0x0a + 'a');
101 if((b & 0x0f) < 0x0a)
102 uart_putc((b & 0x0f) + '0');
104 uart_putc((b & 0x0f) - 0x0a + 'a');
107 void uart_putw_hex(uint16_t w)
109 uart_putc_hex((uint8_t) (w >> 8));
110 uart_putc_hex((uint8_t) (w & 0xff));
113 void uart_putdw_hex(uint32_t dw)
115 uart_putw_hex((uint16_t) (dw >> 16));
116 uart_putw_hex((uint16_t) (dw & 0xffff));
119 void uart_putw_dec(uint16_t w)
121 uint16_t num = 10000;
127 if(b > 0 || started || num == 1)
138 void uart_putdw_dec(uint32_t dw)
140 uint32_t num = 1000000000;
145 uint8_t b = dw / num;
146 if(b > 0 || started || num == 1)
157 void uart_puts(const char* str)
163 void uart_puts_p(PGM_P str)
167 uint8_t b = pgm_read_byte_near(str++);
177 /* wait until receive buffer is full */
182 while(!(UCSRA & (1 << RXC)))
187 while(!(UCSRA & (1 << RXC)));
197 EMPTY_INTERRUPT(USART_RXC_vect)