uart.c 2.2 KB

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