#define __16F876
#include "pic16f876.h"

// How do I set the __CONFIG word?  Bingo, libero.it gives it in one of his questions:
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;
//Should look like this: 0x3f72;

#define SAMPLE_PERIOD 1000  //ms
unsigned int count;
unsigned int ms_count1;
unsigned char sample_fl;

void timer_intr() interrupt 0 {
  /*if(TXIF) { // serial interrupt
    // TXIF = 0; // not doable :)
    TXREG = 'n';
    TXIE = 0;
    //char r = ring[ring_pointer];
    //if(r) {
    //  TXREG = r;
    // ring_pointer++;
    //} else {
      //TXIE = 0;
    //}
    } */
  if(TMR2IF) { // No real advantage to not doing these at the same time.
    if (++ms_count1 == SAMPLE_PERIOD) {
      ms_count1 = 0;
      sample_fl = 1;
    }
    TMR2IF = 0;
    PIR1 = 0;
    PEIE = 1;
  }
}

#define T2_DIV_BY_16 3

void putc(char c) {
  TXEN = 1;
  while(!TRMT);
  // enable transmission
  TXREG = c;
}

void print(char* p) {
  while(*p) {
    putc(*p);
    p++;
  }
}

void main() {
  char a[4];
  NOT_RBPU=0;
  
  // Configure UART serial transmit
  
  SPBRG = 25; // 16MHz => 9600 baud
  BRGH = 0;
  SYNC = 0;
  SPEN = 1;
  //TXIE = 1;  // polling only
  
  //Configure timer 2
  
  T2CON=0x03;
  TMR2ON = 1;
  GIE = 1;
  PEIE = 1;
  //INTCON=0xc0;
  PIR1 = 0;
  PIE1 = 2;
  PR2 = 249;
  sample_fl = 0;

  a[0] = 'h';
  a[1] = 'j';
  a[2] = 'n';
  a[3] = 0;
  
  TRISB = 0;
  count = 0;
  while(1) {
    while (!sample_fl);
    sample_fl = 0;
    PORTB = count++;
    putc('n');
    putc('j');
    putc('h');
    putc('-');
    print(a);
    print("njh ");
  }
}
