/*
 * File:   capture_test.c
 * Author: corrado
 *
 * Created on January 10, 2016, 6:52 PM
 */

#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

void setup_uart(void)
{
    // configure UART
    // setup UART
    TRISCbits.TRISC6 = 0;   // TX as output
    TRISCbits.TRISC7 = 1;   // RX as input

    TXSTA1bits.SYNC = 0; // Async operation
    TXSTA1bits.TX9 = 0; // No tx of 9th bit
    TXSTA1bits.TXEN = 1; // Enable transmitter
    RCSTA1bits.RC9 = 0; // No rx of 9th bit
    // Setting for 19200 BPS
    BAUDCON1bits.BRG16 = 0; // Divisor at 8 bit
    TXSTA1bits.BRGH = 0; // No high-speed baudrate
    SPBRG1 = 51; // divisor value for 19200

    RCSTA1bits.CREN = 1; // Enable receiver
    RCSTA1bits.SPEN = 1; // Enable serial port

    PIE1bits.TX1IE = 0; // disable TX hardware interrupt
    PIE1bits.RC1IE = 0; // disable RX hardware interrupt

}

void putch(char c) {
    // wait the end of transmission
    while (TXSTA1bits.TRMT == 0) {};
    TXREG1 = c; // send the new byte
}

void setup_capture(void)
{
    T1CONbits.TMR1CS = 0b00; // FOSC/4
    T1CONbits.T1CKPS = 0b11; // prescaler 1:8
    T1GCONbits.TMR1GE = 0; // not gated
    TMR1L = 0; TMR1H = 0; // clear timer

    CCPTMRS0bits.C1TSEL = 0b00; // CCP1 uses timer1

    TRISCbits.TRISC2 = 1; // RC2/CCP1 pin set as input

    T1CONbits.TMR1ON = 1; // turn on timer
}


void main(void) {
    unsigned int start, end, duration;
    float real_time_ms;
    setup_uart();
    setup_capture();

    printf("Press and release fast button 3\n\r");

    for (;;) {
        CCP1CONbits.CCP1M = 0b0100; // capture every falling
        PIR1bits.CCP1IF = 0;        // clear interrupt flag
        while (PIR1bits.CCP1IF == 0) {} // wait capture event
        start = CCPR1; // copy capture register

        CCP1CONbits.CCP1M = 0b0101; // capture every rising
        PIR1bits.CCP1IF = 0;        // clear interrupt flag
        while (PIR1bits.CCP1IF == 0) {} // wait capture event
        end = CCPR1; // copy capture register

        duration = end - start;
        real_time_ms = duration * 0.5e-3;
        printf("Elapsed time %f\n\r", real_time_ms);
    }
}

