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.
 
 
 
 

69 lines
1.2 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. }