uart.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include <xc.h>
  2. #include "uart.h"
  3. void init_uart(void)
  4. {
  5. #ifdef AD1PCFG
  6. AD1PCFG = 0xFFFF;
  7. #endif
  8. TRISBbits.TRISB5 = 1; //RX pin is PB.5
  9. TRISBbits.TRISB7 = 0; //TX pin is PB.7
  10. __builtin_write_OSCCONL(OSCCON & 0xbf);
  11. RPINR18bits.U1RXR = 5; /*U1RX = RP5 */
  12. RPOR3bits.RP7R = 3; /* U1TX */
  13. __builtin_write_OSCCONL(OSCCON | 0x40);
  14. // configure U1MODE
  15. U1MODEbits.UARTEN = 0; // Bit15 TX, RX DISABLED, ENABLE at end of func
  16. U1MODEbits.USIDL = 0; // Bit13 Continue in Idle
  17. U1MODEbits.IREN = 0; // Bit12 No IR translation
  18. U1MODEbits.RTSMD = 0; // Bit11 Simplex Mode
  19. U1MODEbits.UEN = 0; // Bits8,9 TX,RX enabled, CTS,RTS not
  20. U1MODEbits.WAKE = 0; // Bit7 No Wake up (since we don't sleep here)
  21. U1MODEbits.LPBACK = 0; // Bit6 No Loop Back
  22. U1MODEbits.ABAUD = 0; // Bit5 No Autobaud (would require sending '55')
  23. U1MODEbits.RXINV = 0; // Bit4 IdleState = 1
  24. U1MODEbits.BRGH = 0; // Bit3 16 clocks per bit period
  25. U1MODEbits.PDSEL = 0; // Bits1,2 8bit, No Parity
  26. U1MODEbits.STSEL = 0; // Bit0 One Stop Bit
  27. U1BRG = 5; /* 38400 baud @ 7.3728 MHz oscillator */
  28. // Load all values in for U1STA SFR
  29. U1STAbits.UTXISEL1 = 0; //Bit15 Int when Char is transferred (1/2 config!)
  30. U1STAbits.UTXINV = 0; //Bit14 N/A, IRDA config
  31. U1STAbits.UTXISEL0 = 0; //Bit13 Other half of Bit15
  32. U1STAbits.UTXBRK = 0; //Bit11 Disabled
  33. U1STAbits.UTXEN = 0; //Bit10 TX pins controlled by periph
  34. U1STAbits.UTXBF = 0; //Bit9 *Read Only Bit*
  35. U1STAbits.TRMT = 0; //Bit8 *Read Only bit*
  36. U1STAbits.URXISEL = 0; //Bits6,7 Int. on character recieved
  37. U1STAbits.ADDEN = 0; //Bit5 Address Detect Disabled
  38. U1STAbits.RIDLE = 0; //Bit4 *Read Only Bit*
  39. U1STAbits.PERR = 0; //Bit3 *Read Only Bit*
  40. U1STAbits.FERR = 0; //Bit2 *Read Only Bit*
  41. U1STAbits.OERR = 0; //Bit1 *Read Only Bit*
  42. U1STAbits.URXDA = 0; //Bit0 *Read Only Bit*
  43. IFS0bits.U1TXIF = 0; // Clear the Transmit Interrupt Flag
  44. IEC0bits.U1TXIE = 0; // Disable Transmit Interrupts
  45. IFS0bits.U1RXIF = 0; // Clear the Recieve Interrupt Flag
  46. IEC0bits.U1RXIE = 0; // Disable Recieve Interrupts
  47. U1MODEbits.UARTEN = 1; // And turn the peripheral on
  48. U1STAbits.UTXEN = 1;
  49. U1STAbits.URXEN = 1;
  50. }
  51. void putch(char c)
  52. {
  53. while(U1STAbits.UTXBF == 1);
  54. U1TXREG = c;
  55. }
  56. char getch(void)
  57. {
  58. if (U1STA & (1<<1)){
  59. U1STA |= 1<<1;
  60. }
  61. char c;
  62. while(U1STAbits.URXDA == 0);
  63. c = U1RXREG;
  64. IFS0bits.U1RXIF = 0;
  65. return c;
  66. }