PIC18F26K22 – Serial Hello World example

After having compiler issues using the new PIC18F25K50 chip, I switched to the K22 series.  Specifically the 28 pin PIC18F26K22.  The dual USART, dual SPI/I2C interfaces will be handy and allow for more flexible board layouts.

But, I had some difficulty getting the serial output to work.  I read through a variety of examples, and questions/problems posted by others, most without responses.  I did find several examples, but none of these worked.  With some additional messing about, I managed to come up with this minimal Hello World example.

Hopefully the following will save someone else some time.

/* Serial Hello World
* This works!
* Clock set to 4Mhz, no PLL, transmits at 2400 Baud
* PIC18F26K22
* Complier: C18 v 3.45
*/

#include
#include
#include
#include
#include
#include

#pragma config FOSC = INTIO7 // internal clock, clock output on RA6

/*
IRCF: Internal RC Oscillator Frequency Select bits(2)
111 = HFINTOSC (16 MHz)
110 = HFINTOSC/2 (8 MHz)
101 = HFINTOSC/4 (4 MHz)
100 = HFINTOSC/8 (2 MHz)
011 = HFINTOSC/16 (1 MHz)
*/

void main (void)
{
OSCCONbits.IRCF = 0b101; //change Fosc to 4Mhz
// wait until IOFS = 1 (osc. stable)
while (!OSCCONbits.IOFS)
/*
* Open the USART configured as
* 8N1, 2400 baud, in polled mode
*/
Open1USART (USART_TX_INT_OFF &
USART_RX_INT_OFF &
USART_ASYNCH_MODE &
USART_EIGHT_BIT &
USART_CONT_RX &
USART_BRGH_HIGH, 103);

while (1)
{
putrs1USART(“Hello World!\n\r”);
Delay1KTCYx(1);
}
}

Leave a comment