//
// Demo code for the PIC16F876
//
// Example of how to use the RTCC Interrupt to do timing
//
// For SP.710, Spring 2001
//
// maxdavis(at)mit.edu
//

#include <16f876.h>
#fuses nowdt, hs, noprotect, put, brownout, nolvp 
#use delay(clock=20000000)
#use rs232 (baud=2400, xmit=PIN_C6, rcv=PIN_C7)

#define LED PIN_C5

// global variables that subroutines can read and modify
unsigned long time = 0;
unsigned long timeB = 0;

#int_rtcc
void rtcc_interrupt_subroutine() {
  // it doesn't matter what this subroutine is named, but it will
  //  be run every time the "RTCC interrupt" goes off, which is 
  //  every time the RTCC counter runs over, roughly every 13 ms
  timeB += 13;
  // so add 13 to a variable holding "# of milliseconds elapsed"
}

void main() {

  char c;

  // these lines are just a check that the PIC and the serial port are working

  output_high(LED);
  delay_ms(500);
  output_low(LED);
  printf("the serial port works.\r\n");

  // set up the Real Time Clock Counter (RTCC):
  //  with these settings, it will roll over at a rate of:
  //  20 MHz / 4 (clocks-per-instr) / 256 (DIV_BY_256) / 256
  //   (clock ticks until the 8-bit counter rolls over) =
  //   76 Hz = once every 13 ms

  setup_COUNTERS(RTCC_INTERNAL,RTCC_DIV_256);

  disable_interrupts(GLOBAL);   // make sure all interrupts are disabled
  enable_interrupts(INT_RTCC);   
  // select the RTCC timer interrupt (but don't start it running yet,
  //  not until you run enable_interrupts(GLOBAL) )
  
  printf("Timing, two different ways:\r\n");

  while(1) {

    time = 0;
    timeB = 0;
    
    printf("\r\n<Hit any key to start>\r\n");
    
    c=getc();     // waits at this line until you press a key
    
    enable_interrupts(GLOBAL);   // start checking for interrupts.
    // specifically, start checking for the RTCC interrupt.
    
    printf("\r\nThe time it takes to print out this text is not\r\n");
    printf("accounted for if you measure time using delay_ms()\r\n");
    printf("statements, but is accounted for if you use interrupts.\r\n");
    printf("\r\n<Hit any key to stop timing>\r\n");



    // loop endlessly until a key is hit
    while (!kbhit()) {
      delay_ms(1);
      time++;
      // every millisecond, increment another counter that keeps track
      //  of elapsed time
    }
    

    disable_interrupts(GLOBAL); // stop checking the RTCC interrupt
    
    c=getc();
    
    printf("delay_ms  method says %lu milliseconds elapsed\r\n",time);
    printf("interrupt method says %lu milliseconds elapsed\r\n",timeB);
    
  }
  
}










