PIC8-Bit Trainer - EUSART.

0.Contents

PIC18F Trainer : PIC18F2xJ13 @8MHz Internal oscillator.

1.MCP2221A - UART Tx/Rx, No Interrupt.

// Configuration registers.
#pragma config WDTEN=OFF, PLLDIV=1, CFGPLLEN=OFF, STVREN=ON, XINST=OFF
#pragma config CP0=OFF, OSC=INTOSCO, SOSCSEL=HIGH, CLKOEC=OFF, FCMEN=OFF
#pragma config IESO=OFF, WDTPS=32768, DSWDTOSC=INTOSCREF, RTCOSC=T1OSCREF
#pragma config DSBOREN=ON, DSWDTEN=ON, DSWDTPS=G2
#pragma config IOL1WAY=ON, ADCSEL=BIT10, PLLSEL=PLL4X, MSSP7B_EN=MSK7
#pragma config WPFP=PAGE_63, WPCFG=OFF, WPDIS=OFF, WPEND=PAGE_WPFP

#include <xc.h>
#include <stdint.h>
//#include <stdlib.h>
#define _XTAL_FREQ 8000000
// PIC18F26J13 - Compile with XC8(v2.00).
// PIC18F26J13 - @8MHz Internal oscillator.

// MCP2221A - UART Tx/Rx, No Interrupt.

// Definitions.
#define LED		LATAbits.LATA0

// Function prototypes.
void mcu_initialize(void);
void uart_initialize(void);
uint8_t uart_readCharacter(void);
void uart_writeCharacter(char cData);
void uart_writeString(const char * cData);

// String.
const char string[] = "Tronix I/O\r\nwww.tronix.io\r\n> ";

// Main.
int main(void)
{
	mcu_initialize();
	uart_initialize();

	// Display String.
	uart_writeString(string);

	uint8_t u8Data;
	while(1){
		u8Data = uart_readCharacter();
		uart_writeCharacter(u8Data);
		if(u8Data == 'l' | u8Data == 'L'){
			LED = 0;
		}
		if(u8Data == 'h' | u8Data == 'H'){
			LED = 1;
		}
		if(u8Data == 0xd){
			uart_writeString("\n\r> ");
		}
		__delay_ms(200);
	}
	return(0);
}

// Functions.
void mcu_initialize(void)
{
	// Internal Oscillator 8MHz.
	OSCCONbits.IRCF = 0x7;
	OSCTUNEbits.PLLEN = 0;
	// Ports.
	PORTA = 0x00;
	TRISA = 0x00;
	PORTB = 0x00;
	TRISB = 0x00;
	PORTC = 0x00;
	TRISC = 0x80;
}

void uart_initialize(void)
{
	// UART1 - Asynchronous transmitter.
	// TXEN = 1 - Transmit enable.
	// TXEN = 0 - Transmit disable.
	TXSTA1bits.TXEN = 1;
	// CREN = 1 - Receiver enable.
	// CREN = 0 - Receiver disable.
	RCSTA1bits.CREN = 1 ;
	// Baud Rate Generator.
	// SPBRGH7.0 = High byte.
	SPBRGH1 = 0;
	// SPBRG7.0 = Low byte.
	SPBRG1 = 12;

	// UART1 Enable.
	RCSTA1bits.SPEN = 1;
}

uint8_t uart_readCharacter(void)
{
	while(!PIR1bits.RCIF){};
	return(RCREG1);
}

void uart_writeCharacter(char cData)
{
	while(!PIR1bits.TXIF){};
	TXREG1 = cData;
}

void uart_writeString(const char * cData)
{
	while(*cData != '\0')
		uart_writeCharacter(*cData++);
}

12.2018