Skip to content

Instantly share code, notes, and snippets.

@mbainrot
Last active April 16, 2018 08:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbainrot/10fdcab920ec883d32c52c8bcff9d91c to your computer and use it in GitHub Desktop.
Save mbainrot/10fdcab920ec883d32c52c8bcff9d91c to your computer and use it in GitHub Desktop.
How I got serial working on a PIC18F2550
/*
* File: main.c
* Author: max
*
* Created on April 14, 2018, 10:40 AM
*/
// Set the OSC to internal osc which is 8 MHz
#pragma config FOSC = INTOSC_EC
#pragma config WDT = OFF // turn off watch dog
#pragma config BOR = OFF // turn off brown out reset because my wiring SUCKS and the circuit's voltage varies with my mood...
#pragma config PBADEN = OFF // turn off ADC converter
#pragma config LVP = OFF
/// ^^^^^ Long story about this ^^^^^^
// You do this if you have a high voltage programming capable programmer, if you don't, tie PGM low with >10K ohm resistor
// Why? because if you leave PGM floating, with LVP, you'll waste many hours troubleshooting the random crashes
// floating PGM w/ LVP is akin to leaving MCLR or on AVR, RESET line floating :)
//
// Massive thank you to -> https://electronics.stackexchange.com/a/30449
// Have to set this constant so stuff like __delay_ms() knows our clock speed
#define _XTAL_FREQ 8000000
// Usual includes
#include <xc.h>
#include <string.h>
// My flail send string function
void tx_str(const char * s)
{
// This is junk, because it's blocking, kinda defeats the purpose
// of asynchronous serial...
// ... but hey it works and I am not ready to torture myself with
// interrupt vectors **yet**
for(unsigned int i = 0; i < strlen(s); i++)
{
// Fill the TXREGister with our delicious bits
TXREG = s[i];
// aaaand wait for it to drain...
while(TRMT != 1 && TXIF != 1) {}
}
}
void main(void) {
// Set up the clock... otherwise stuff doesn't work
// Internal OSC Freq Select, 111 = 8 MHz
IRCF2 = 1; IRCF1 = 1; IRCF0 = 1;
// Init the serial port IO pins
TRISC7 = 1;
TRISC6 = 0;
//*
// 8bit, async mode, tx enabled
TXSTA = 0; // first we clear the register
TXEN = 1; // then enable transmission (rest stays 0)
// 8bit, async, rx enabled
RCSTA = 0; // again nuke the register
SPEN = 1;
// Baud rate = 9600 baud (act 9616)
BRG16 = 0; // 8 bit (legacy) baudrate spec
SPBRG = 12; // 9k12 baud @ 8MHz
// */
// Init our status led
TRISB0 = 0;
while(1)
{
// Hello world, because I am too stupid/tired to come up with something more creative :)
tx_str("hello world!");
// Flash the LED to prove the uC hasn't had it's RST line dragged low by the stupid pickit3...
RB0 = ! RB0;
// Sleep for a bit, so I can admire my handy work (:
__delay_ms(1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment