You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

116 lines
1.9 KiB

  1. #include "config.h"
  2. #include "uart.h"
  3. void uart_init(int uart)
  4. {
  5. if (uart == 1) {
  6. U1MODE = 0;
  7. U1MODEbits.BRGH = 0;
  8. U1STA = 0;
  9. U1MODEbits.UARTEN = 1;
  10. U1STAbits.UTXEN = 1;
  11. } else if (uart == 2) {
  12. U2MODE = 0;
  13. U2MODEbits.BRGH = 0;
  14. U2STA = 0;
  15. U2MODEbits.UARTEN = 1;
  16. U2STAbits.UTXEN = 1;
  17. }
  18. uart_set_rate(uart, 115200);
  19. }
  20. void uart_set_rate(int uart, int32_t rate)
  21. {
  22. int32_t brg;
  23. brg = ((FCY + (8 * rate - 1)) / (16 * rate)) - 1;
  24. if (brg < 1) brg = 1;
  25. if (brg > 65535) brg = 65535;
  26. if (uart == 1)
  27. U1BRG = brg;
  28. else if (uart == 2)
  29. U2BRG = brg;
  30. }
  31. void uart_put(int uart, uint8_t x)
  32. {
  33. if (uart == 1) {
  34. while (U1STAbits.UTXBF) continue;
  35. U1TXREG = x;
  36. } else if (uart == 2) {
  37. while (U2STAbits.UTXBF) continue;
  38. U2TXREG = x;
  39. }
  40. }
  41. uint8_t uart_get(int uart)
  42. {
  43. uint8_t data = 0;
  44. if (uart == 1) {
  45. while (!U1STAbits.URXDA) continue;
  46. data = U1RXREG;
  47. if (U1STAbits.OERR)
  48. U1STAbits.OERR = 0;
  49. } else if (uart == 2) {
  50. while (!U2STAbits.URXDA) continue;
  51. data = U2RXREG;
  52. if (U2STAbits.OERR)
  53. U2STAbits.OERR = 0;
  54. }
  55. return data;
  56. }
  57. void uart_put_string(int uart, const char *s)
  58. {
  59. while(s && *s)
  60. uart_put(uart, *s++);
  61. }
  62. void uart_put_bin(int uart, uint8_t x)
  63. {
  64. int i;
  65. for(i=0;i<8;i++) {
  66. uart_put(uart, (x & 0x80) ? '1' : '0');
  67. x <<= 1;
  68. }
  69. }
  70. void uart1_put_hex(int uart, uint8_t x)
  71. {
  72. uart_put(uart, hex[x >> 4]);
  73. uart_put(uart, hex[x & 15]);
  74. }
  75. void uart_put_hex16(int uart, uint16_t x)
  76. {
  77. uart_put_hex(uart, (x >> 8) & 0xFF);
  78. uart_put_hex(uart, (x) & 0xFF);
  79. }
  80. void uart_put_hex32(int uart, uint32_t x)
  81. {
  82. uart_put_hex(uart, (x >> 24) & 0xFF);
  83. uart_put_hex(uart, (x >> 16) & 0xFF);
  84. uart_put_hex(uart, (x >> 8) & 0xFF);
  85. uart_put_hex(uart, (x) & 0xFF);
  86. }
  87. void uart_put_dec(int uart, uint32_t x)
  88. {
  89. uint32_t place = 1;
  90. while (x / place > 9)
  91. place *= 10;
  92. while (place > 0) {
  93. uart_put(uart, x / place + '0');
  94. x %= place;
  95. place /= 10;
  96. }
  97. }
  98. void uart_crlf(int uart)
  99. {
  100. uart_put(uart, '\r');
  101. uart_put(uart, '\n');
  102. }