uart.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * CNC-remote-control
  3. * UART driver
  4. *
  5. * Copyright (C) 2011 Michael Buesch <m@bues.ch>
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License
  9. * version 2 as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. */
  16. #include "uart.h"
  17. #include "main.h"
  18. #include "util.h"
  19. #include <avr/io.h>
  20. static bool uart_enabled;
  21. void uart_putchar(char c)
  22. {
  23. if (!uart_enabled)
  24. return;
  25. mb();
  26. if (c == '\n')
  27. uart_putchar('\r');
  28. while (!(UCSRA & (1 << UDRE)));
  29. UDR = (uint8_t)c;
  30. }
  31. void uart_puthex(uint8_t val)
  32. {
  33. uart_putchar(hexdigit_to_ascii((val >> 4) & 0xF));
  34. uart_putchar(hexdigit_to_ascii(val & 0xF));
  35. }
  36. void _uart_putstr(const char PROGPTR *pstr)
  37. {
  38. char c;
  39. while (1) {
  40. c = (char)pgm_read_byte(pstr);
  41. if (c == '\0')
  42. break;
  43. uart_putchar(c);
  44. pstr++;
  45. }
  46. }
  47. #if UART_USE_2X
  48. # define UBRR_FACTOR 2
  49. #else
  50. # define UBRR_FACTOR 1
  51. #endif
  52. void uart_init(void)
  53. {
  54. /* Set baud rate */
  55. UBRRL = lo8((F_CPU / 16 / UART_BAUD) * UBRR_FACTOR);
  56. UBRRH = hi8((F_CPU / 16 / UART_BAUD) * UBRR_FACTOR) & ~(1 << URSEL);
  57. #if UART_USE_2X
  58. UCSRA = (1 << U2X);
  59. #endif
  60. /* 8 Data bits, 1 Stop bit, No parity */
  61. UCSRC = (1 << UCSZ0) | (1 << UCSZ1) | (1 << URSEL);
  62. /* Enable transmitter */
  63. UCSRB = (0 << RXEN) | (1 << TXEN) | (0 << RXCIE);
  64. mb();
  65. uart_enabled = 1;
  66. }
  67. void uart_exit(void)
  68. {
  69. uart_enabled = 0;
  70. mb();
  71. while (!(UCSRA & (1 << UDRE)));
  72. _delay_ms(10);
  73. UCSRB = 0;
  74. UCSRC = 0;
  75. UCSRA = 0;
  76. UBRRL = 0;
  77. UBRRH = 0;
  78. }