uart.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * =====================================================================================
  3. *
  4. * ________ .__ __ ________ ____ ________
  5. * \_____ \ __ __|__| ____ | | __\______ \ _______ _/_ |/ _____/
  6. * / / \ \| | \ |/ ___\| |/ / | | \_/ __ \ \/ /| / __ \
  7. * / \_/. \ | / \ \___| < | ` \ ___/\ / | \ |__\ \
  8. * \_____\ \_/____/|__|\___ >__|_ \/_______ /\___ >\_/ |___|\_____ /
  9. * \__> \/ \/ \/ \/ \/
  10. *
  11. * www.optixx.org
  12. *
  13. *
  14. * Version: 1.0
  15. * Created: 07/21/2009 03:32:16 PM
  16. * Author: david@optixx.org
  17. *
  18. * =====================================================================================
  19. */
  20. #include <avr/io.h>
  21. #include <avr/interrupt.h>
  22. #include <avr/pgmspace.h>
  23. #include <stdio.h>
  24. #include "uart.h"
  25. #include "fifo.h"
  26. volatile struct {
  27. uint8_t tmr_int:1;
  28. uint8_t adc_int:1;
  29. uint8_t rx_int:1;
  30. } intflags;
  31. volatile char rxbuff;
  32. static int uart_stream(char c, FILE * stream);
  33. FILE uart_stdout = FDEV_SETUP_STREAM(uart_stream, NULL, _FDEV_SETUP_WRITE);
  34. void uart_init(void)
  35. {
  36. UCSR0A = _BV(U2X0); /* improves baud rate error @ F_CPU = 1 MHz */
  37. UCSR0B = _BV(TXEN0) | _BV(RXEN0) | _BV(RXCIE0); /* tx/rx enable, rx complete * intr */
  38. UBRR0L = (F_CPU / (8 * 115200UL)) - 1;
  39. }
  40. /*
  41. * ISR(USART0_RX_vect) { uint8_t c; c = UDR0; if (bit_is_clear(UCSR0A, FE0)) { rxbuff = c; intflags.rx_int = 1; } }
  42. */
  43. void uart_putc(uint8_t c)
  44. {
  45. loop_until_bit_is_set(UCSR0A, UDRE0);
  46. UDR0 = c;
  47. }
  48. void uart_puts(const char *s)
  49. {
  50. do {
  51. uart_putc(*s);
  52. }
  53. while (*s++);
  54. }
  55. void uart_puts_P(PGM_P s)
  56. {
  57. while (1) {
  58. unsigned char c = pgm_read_byte(s);
  59. s++;
  60. if ('\0' == c)
  61. break;
  62. uart_putc(c);
  63. }
  64. }
  65. static int uart_stream(char c, FILE * stream)
  66. {
  67. if (c == '\n')
  68. uart_putc('\r');
  69. loop_until_bit_is_set(UCSR0A, UDRE0);
  70. UDR0 = c;
  71. return 0;
  72. }