#define __16F876
#include "pic16f876.h"

typedef unsigned int word;
word at 0x2007  __CONFIG = _CP_OFF & _WDT_OFF & _BODEN_ON & \
         _PWRTE_ON & _HS_OSC & _WRT_ENABLE_ON & \
         _LVP_OFF & _DEBUG_OFF & _CPD_OFF;

unsigned char angle;
unsigned short ms_count = 0;
unsigned char pin = 1;

void general_intr() interrupt 0 {
  if(TMR2IF) {
    PORTB = pin;
    pin = pin << 1;
    if(pin == 0) // eventually the program will pad with extra time here
      pin = 1;
    PR2 = angle;
    TMR2IF = 0;
    PIR1 = 0;
    PEIE = 1;
  }
  if(RCIF) { // serial received
    //rst = RCSTA;
    // check for errors here
    if(OERR) {
      // if we got an error we should clear CREN
      CREN = 0;
      // re-enable receiveing
      CREN = 1;
    } else {
      angle = RCREG;
    }
  } 
}

void main() {
  NOT_RBPU=0;
  
  // Configure UART serial receive
  
  SPBRG = 25; // 16MHz => 9600 baud
  BRGH = 0;
  SYNC = 0;
  SPEN = 1;
  RCIE = 1;
  CREN = 1;
  
  GIE = 1;
  PEIE = 1;
  
  //Configure timer 2
  
  T2CON=0x0a;
  TMR2ON = 1;
  GIE = 1;
  PEIE = 1;
  PIR1 = 0;
  PIE1 = 2;
  PR2 = 255; // 1ms = 0 degrees.
  
  TRISB = 0;
  while(1) {
  }
}

