uart.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <avr/io.h>
  2. #include <avr/interrupt.h>
  3. #include <avr/pgmspace.h>
  4. #include <stdio.h>
  5. #include "uart.h"
  6. #include "fifo.h"
  7. volatile struct {
  8. uint8_t tmr_int:1;
  9. uint8_t adc_int:1;
  10. uint8_t rx_int:1;
  11. } intflags;
  12. /*
  13. * * Last character read from the UART.
  14. *
  15. */
  16. volatile char rxbuff;
  17. FILE uart_stdout = FDEV_SETUP_STREAM(uart_stream, NULL, _FDEV_SETUP_WRITE);
  18. void uart_init(void)
  19. {
  20. UCSRA = _BV(U2X); /* improves baud rate error @ F_CPU = 1 MHz */
  21. UCSRB = _BV(TXEN) | _BV(RXEN) | _BV(RXCIE); /* tx/rx enable, rx complete
  22. * intr */
  23. UBRRL = (F_CPU / (8 * 115200UL)) - 1; /* 9600 Bd */
  24. }
  25. ISR(USART_RXC_vect)
  26. {
  27. uint8_t c;
  28. c = UDR;
  29. if (bit_is_clear(UCSRA, FE)) {
  30. rxbuff = c;
  31. intflags.rx_int = 1;
  32. }
  33. }
  34. void uart_putc(uint8_t c)
  35. {
  36. loop_until_bit_is_set(UCSRA, UDRE);
  37. UDR = c;
  38. }
  39. void uart_puts(const char *s)
  40. {
  41. do {
  42. uart_putc(*s);
  43. }
  44. while (*s++);
  45. }
  46. void uart_puts_P(PGM_P s)
  47. {
  48. while (1) {
  49. unsigned char c = pgm_read_byte(s);
  50. s++;
  51. if ('\0' == c)
  52. break;
  53. uart_putc(c);
  54. }
  55. }
  56. static int uart_stream(char c, FILE * stream)
  57. {
  58. if (c == '\n')
  59. uart_putc('\r');
  60. loop_until_bit_is_set(UCSRA, UDRE);
  61. UDR = c;
  62. return 0;
  63. }