uart.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. This program is free software; you can redistribute it and/or
  3. modify it under the terms of the GNU General Public License
  4. as published by the Free Software Foundation; either version 2
  5. of the License, or (at your option) any later version.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU General Public License for more details.
  10. Author: hakanai
  11. Email: hakanai at dnmx.0rg
  12. */
  13. #include <avr/io.h>
  14. #include <stdio.h>
  15. #include "uart.h"
  16. #define UART_BAUD_SELECT(baudRate,xtalCpu) (((xtalCpu)+8UL*(baudRate))/(16UL*(baudRate))-1UL)
  17. /*
  18. * It is xxxx 8 N 1 initialization
  19. * xxxx - means boudrate which is the only option
  20. * 9600 8N1 works just fine
  21. */
  22. void uart_init(int baud) {
  23. UBRR = (uint8_t)UART_BAUD_SELECT(baud, F_CPU);
  24. /*
  25. * The RXB8 could be skiped because it's RO nature,
  26. * so lets keep it simple.
  27. */
  28. UCR = _BV(TXB8)|_BV(RXEN)|_BV(TXEN);
  29. /*
  30. * TODO:
  31. * Check if this is a neceserry bit set
  32. * when uart_getchar() goes first on a first run.
  33. */
  34. USR = _BV(TXC);
  35. }
  36. /*
  37. * There is a problem with the TXC bit
  38. * which is a R/W bit of the USR. A problem is
  39. * status of the bit which does not reset properly.
  40. * Therefore I've decided to set it manually and wait for
  41. * its reset for an every transission.
  42. */
  43. void uart_putchar(char c) {
  44. USR = _BV(TXC);
  45. UDR = c;
  46. loop_until_bit_is_set(USR, TXC);
  47. }
  48. int uart_getchar() {
  49. loop_until_bit_is_set(USR, RXC);
  50. return UDR;
  51. }