#include <htc.h>
#include <string.h>
/* Start of configuration fuses*/
#pragma config IESO=OFF, FOSC=INTIO67,PRICLKEN=OFF,FCMEN =OFF,PLLCFG=ON,BOREN=ON,BORV=250
#pragma config WDTEN=OFF
#pragma config P2BMX=PORTC0,CCP2MX=PORTC1,PBADEN=OFF,CCP3MX=PORTE0,MCLRE=INTMCLR,HFOFST=OFF,T3CMX=PORTC0
#pragma config DEBUG=OFF,STVREN=ON,XINST=OFF,LVP=OFF
#pragma config CP0=OFF,CP1=OFF,CP2=OFF,CP3=OFF
#pragma config CPB=OFF,CPD=OFF
#pragma config WRT0=ON,WRT1=ON,WRT2=ON,WRT3=ON
#pragma config WRTB=ON,WRTC=ON,WRTD=ON
/* end of configuration fuses */
char sendBuffer[11];
char sendPosition = 0;
void sendUartString(const char string[10]);
void init() {
OSCCON = 0b11110011; //16MHz internal oscillator
OSCCON2 = 0b00000000;
// Asynchronous Transmission Setup
// 1. Initialize the SPBRGHx:SPBRGx register pair and the BRGH and BRG16 bits to achieve the desired baud rate
SPBRGH2 = 0X01;
SPBRG2 = 0XA0;
TXSTA2bits.BRGH = 1;
BAUDCON2bits.BRG16 = 1;
// 2. Set the RXx/DTx and TXx/CKx TRIS controls to ?1?.
TRISB = 0b11000000; //set TX2 and RX2 as input
// 3. Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN bit.
ANSELB = 0; //disable ANSEL
SYNC2 = 0; //asynchronous mode
SPEN2 = 1; //enable EUSART
// 4. If 9-bit transmission is desired, set the TX9 control bit. A set ninth data bit will indicate that the eight Least Significant data bits are an address when the receiver is set for address detection.
// 5. Set the CKTXP control bit if inverted transmit data polarity is desired.
// 6. Enable the transmission by setting the TXEN control bit. This will cause the TXxIF interrupt bit to be set.
TXEN2 = 1;
// 7. If interrupts are desired, set the TXxIE interrupt enable bit. An interrupt will occur immediately provided that the GIE/GIEH and PEIE/GIEL bits of the INTCON register are also set.
//TX2IE = 1;
//GIE = 1;
//PEIE = 1;
// 8. If 9-bit transmission is selected, the ninth bit should be loaded into the TX9D data bit.
// 9. Load 8-bit data into the TXREGx register. This will start the transmission.
}
void main() {
init();
//now you want to send something, so first load a string into the sendBuffer
while (1) TXREG2 = 'H';
//while(1)
//sendUartString("helloworld");
}
void sendUartString(const char string[10]) {
strcpy(sendBuffer, string); //please check the correct command,copy string[] to sendBuffer[]
sendPosition = 0; //start sending first char
// while ((sendPosition != strlen(sendBuffer)) && sendPosition < 10) {
// if (TX2IF == 1)//if Transmit register is empty
// {
// TX2REG = sendBuffer[sendPosition]; //send one more char
// sendPosition++;
// }
// }
while ((sendPosition != strlen(sendBuffer)) && sendPosition < 10) {
TX2REG = sendBuffer[sendPosition++]; //send one more char
while (TX2IF);
}
}