Last active
August 29, 2015 14:09
-
-
Save sapher/fa4f3d0a133fa96e9216 to your computer and use it in GitHub Desktop.
PIC16F1704 USART TX example (RX is not implemented)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "xc.h" | |
#include "config.h" | |
#define BUFSIZE 12 //Maximum size of received string | |
volatile unsigned char rx_data; | |
volatile unsigned char rx_index; | |
volatile unsigned char rx_buffer[BUFSIZE]; | |
/** | |
* Send a caracter with USART | |
* @param c character to send | |
*/ | |
void USART_putc(unsigned char c) { | |
while(!TXSTAbits.TRMT); | |
TXREG = c; | |
} | |
/** | |
* Send a string with USART | |
* @param s string to send | |
*/ | |
void USART_puts(unsigned char* s) { | |
while(*s) { | |
USART_putc(*s); | |
s++; | |
} | |
} | |
/** | |
* Interrupt serbice routine | |
*/ | |
void interrupt isr() { | |
// USART receive interrupt | |
if(PIR1bits.RCIF) { | |
rx_data = RC1REG; | |
// handle received character here | |
PIR1bits.RCIF = 0; // clear RCIF | |
} | |
} | |
/** | |
* Initialize USART peripheral : async @ 9600 | |
*/ | |
void USART_Init() { | |
// IO Configuration | |
// TX | |
TRISAbits.TRISA2 = 1; | |
RA2PPSbits.RA2PPS = 0b10100; // Set RA2 as TX pin with PPS peripheral | |
// RX | |
TRISCbits.TRISC5 = 1; | |
PORTCbits.RC5 = 0; | |
ANSELCbits.ANSC5 = 0; | |
// Configure USART | |
TXSTAbits.BRGH = 1; // high baud rate mode | |
TXSTAbits.TX9 = 0; // 8 or 9 bits | |
TX1STAbits.SYNC = 0; // asynchronous mode | |
TX1STAbits.TXEN = 1; // enable transmitter | |
// Enable USART | |
RCSTAbits.SPEN = 1; // enable peripheral | |
RCSTAbits.RX9 = 0; // 8 or 9 bits | |
RCSTAbits.CREN = 1; // enable continious receiving | |
SPBRGL = 25; // set baud rate to 9600 | |
// USART Interrupts | |
PIR1bits.RCIF = 0; // clear receive interrupt | |
PIE1bits.RCIE = 1; // enable USART receive interrupt | |
} | |
void main(void) { | |
//4Mhz internal oscillator | |
OSCCONbits.IRCF = 0b1101; | |
/** | |
* Interrupts | |
*/ | |
INTCONbits.GIE = 1; | |
INTCONbits.PEIE = 1; | |
USART_Init(); | |
while(1) { | |
USART_puts("hello world!\n"); | |
__delay_ms(5000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment