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

#define interrupt(x) void __attribute__((interrupt (x)))
#define LEDS 6
#define DECAY 6
#define MAX 100

void delay_ms(uint16_t ms) {
    while (ms--)
        __delay_cycles(1000);
}

volatile uint16_t debug[8];

void uart_putc(char c) {
    while (!(IFG2 & UCA0TXIFG)) ;
    UCA0TXBUF = c;
}

void uart_putn(uint16_t n) {
    static char buf[5];
    int8_t digit = 0;
    
    if (n == 0) {
        uart_putc('0');
    } else {
        while (n) {
            buf[digit] = '0' + (n % 10);
            n /= 10;
            digit++;
        }
        
        for (digit--; digit >= 0; digit--)
            uart_putc(buf[digit]);
    }
}

uint16_t adc_read() {
    ADC10CTL0 &= ~ENC;
    ADC10CTL0 = ADC10SHT_3 | ADC10ON;
    ADC10CTL1 |= ADC10SSEL_3 | INCH_0;
    ADC10CTL0 |= ENC | ADC10SC;
    
    while (ADC10CTL1 & ADC10BUSY);
    
    return ADC10MEM;
}

int main() {
    uint16_t value;
    
    // Disable watchdog
    WDTCTL = WDTPW | WDTHOLD;
    
    BCSCTL1 = CALBC1_1MHZ;
    DCOCTL = CALDCO_1MHZ;
    
    // UART
    P1SEL  = 0x06;
    P1SEL2 = 0x06;
    
    UCA0CTL1 |= UCSSEL_2;
    
    // 19200baud
    UCA0BR0 = 0x34;
    UCA0BR1 = 0x00;
    UCA0MCTL = 0x40;
    
    UCA0CTL1 &= ~UCSWRST;
    
    delay_ms(100);
    
    value = 0;
    
    uart_putc('>');
    
    while (1) {
        value = adc_read();
        uart_putn(value);
        uart_putc('\r');
        uart_putc('\n'); 
        
        //value++;
        
        /*debug[0] = foo;
        
        foo++;
        if (foo > 'z')
            foo = 'a';*/
    }
}
