Advertisement
Guest User

Untitled

a guest
May 28th, 2015
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.83 KB | None | 0 0
  1. #include <xc.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. #include <htc.h>
  5.  
  6. #define _XTAL_FREQ   20000000  
  7.  
  8. void InitUART(void);
  9. void SendByteSerially(unsigned char Byte);
  10. unsigned char ReceiveByteSerially(void);
  11. void SendStringSerially(const unsigned char* st);
  12.  
  13.  
  14. void main()
  15. {
  16.    
  17.     GIE  = 1;                           // Enable global interrupts
  18.     PEIE = 1;                           // Enable Peripheral Interrupts
  19.  
  20.    
  21.     InitUART();
  22.     TRISA = 0x00;
  23.     PORTA = 0x00;
  24.    
  25.     while(1)
  26.     {
  27.        
  28.        
  29.        
  30.        
  31.     }
  32. }
  33.  
  34.  
  35. void interrupt ISR(void)
  36. {
  37.     if(RCIF)  // If UART Rx Interrupt
  38.     {
  39.         if(OERR) // If over run error, then reset the receiver
  40.         {
  41.             CREN = 0;
  42.             CREN = 1;
  43.         }
  44.  
  45.         SendByteSerially(RCREG);    // Echo back received char
  46.     }
  47. }
  48.  
  49. void InitUART(void)
  50. {
  51.     TRISC6 = 1;                     // TX Pin
  52.     TRISC7 = 1;                     // RX Pin
  53.    
  54.     SPBRG = ((_XTAL_FREQ/16)/9600) - 1;
  55.     BRGH  = 1;                      // Fast baudrate
  56.     SYNC  = 0;                      // Asynchronous
  57.     SPEN  = 1;                      // Enable serial port pins
  58.     CREN  = 1;                      // Enable reception
  59.     SREN  = 0;                      // No effect
  60.     TXIE  = 0;                      // Disable tx interrupts
  61.     RCIE  = 1;                      // Enable rx interrupts
  62.     TX9   = 0;                      // 8-bit transmission
  63.     RX9   = 0;                      // 8-bit reception
  64.     TXEN  = 0;                      // Reset transmitter
  65.     TXEN  = 1;                      // Enable the transmitter
  66. }
  67.  
  68.  
  69. void SendByteSerially(unsigned char Byte)  // Writes a character to the serial port
  70. {
  71.     while(!TXIF);  // wait for previous transmission to finish
  72.     TXREG = Byte;
  73. }
  74.  
  75. unsigned char ReceiveByteSerially(void)   // Reads a character from the serial port
  76. {
  77.     if(OERR) // If over run error, then reset the receiver
  78.     {
  79.         CREN = 0;
  80.         CREN = 1;
  81.     }
  82.    
  83.     while(!RCIF);  // Wait for transmission to receive
  84.    
  85.     return RCREG;
  86. }
  87.  
  88. void SendStringSerially(const unsigned char* st)
  89. {
  90.     while(*st)
  91.         SendByteSerially(*st++);
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement