#include <stdint.h>
#include <stdbool.h>
#include <msp430.h>

#define interrupt(x) void __attribute__((interrupt (x)))

uint8_t debug[8];

void send(char data) {
    UCA0TXBUF = data;
    while (!(IFG2 & UCA0TXIFG)) ;
}

int main() {
    WDTCTL = WDTPW | WDTHOLD;

    BCSCTL1 = CALBC1_1MHZ;
    DCOCTL = CALDCO_1MHZ;

    P1OUT = 0x00;

    // Button
    P1REN |= 0x08;
    P1OUT |= 0x08;

    // Led
    P1DIR |= 0x01;

    // Phototransistor
    P2SEL = 0;
    P2SEL2 = 0;
    P2IFG = 0;
    P2IE = 0x01;
    P2IES = 0x00;

    UCA0CTL1 |= UCSSEL_2; // SMCLK clock

    // http://mspgcc.sourceforge.net/cgi-bin/msp-uart.pl?clock=1000000&baud=9600&submit=calculate
    UCA0BR0 = 0x68;
    UCA0BR1 = 0x00;
    UCA0MCTL = 0x04;

    // UART
    P1SEL |= 0x02 | 0x04;
    P1SEL2 |= 0x02 | 0x04; // RXD on P1.1, TXD on P1.2

    UCA0CTL1 &= ~UCSWRST; // Start UART

    //IE2 |= UCA0RXIE;
    
    __delay_cycles(1000);
    P2IFG = 0;

    __bis_status_register(LPM1_bits | GIE);

    return 0;
}

volatile bool debounce = false;

interrupt(PORT2_VECTOR) port2_isr() {
    if ((P2IFG & 0x01) && !debounce) {
        P2IES ^= 0x01;

        if (P2IES & 0x01)
            send('.');

        debounce = true;
        
        P1OUT |= 0x01;

        TACTL |= TACLR;
        TACCR0 = 10000;
        TACCTL0 |= CCIE;
        TACTL = TASSEL_2 | MC_1;
    }

    P2IFG = 0;
}

interrupt(TIMER0_A0_VECTOR) timera_isr() {
    debounce = false;

    P1OUT &= ~0x01;

    TACTL |= TACLR;
}
