#include <t_services.h>
#include "lpc23xx.h"
#include "lpc2388def.h"

#define TMAX    30

static int tcount;
static int tvals[TMAX];
static int ctemp;

void adc_init()
{
    /* Enable power and clock */
    PCONP |= PCAD;
    PCLKSEL0 = (PCLKSEL0 & 0xfcffffff) | (1<<24);
    AD0CR = (AD0CR & 0xffff00ff) | (16 << 8);
    AD0CR = (AD0CR & 0xffdfffff) | (1 << 21);

    PINSEL0 = (PINSEL0 & 0xfcffffff) | (0x03 << 26); /* Channel 7 */
    AD0CR |= (1 << 7);
    /* start conversion */
    AD0CR |= (1 << 24);
    tcount = 0;
}

#define VOFFSET 600

void update_temp()
{
    UW  val, temp;
#ifdef DEBUG
    extern int get_blightness();
#endif

    val = AD0DR7 >> 6;
    temp = val & 0x3ff;
    temp = (3300*temp/1024);
    temp -= VOFFSET;
    tvals[tcount++] = temp;
    if (ctemp == 0)
        ctemp = temp;
    if (tcount == TMAX) {
        temp = 0;
        for (val = 0; val < TMAX; val++) {
            temp += tvals[val];
        }
        temp /= TMAX;
        ctemp = temp;
#ifdef DEBUG
        syslog(LOG_NOTICE, "temp: %d, blight: %d", temp, get_blightness());
#endif
        tcount = 0;
    }
    AD0CR |= (1 << 24);
}

int get_temp()
{
    return ctemp;
}
