//
// ADC example with pull and sw trigger
// By PEK '2007
//
// MCU: AT91SAM7S256
// Experiment board: AT91SAM7S-EK
//

#include "Board.h"

// Macros
#define SET_LED(x)  AT91C_BASE_PIOA->PIO_ODSR = (x)

int main()
{
    unsigned int nAD;

    // Setup PIO
    AT91C_BASE_PMC->PMC_PCER = 1 << AT91C_ID_PIOA;  // Enable clock to PIO
    AT91C_BASE_PIOA->PIO_OER = LED_MASK;    // Output on PA0-PA3
    AT91C_BASE_PIOA->PIO_OWER = LED_MASK;   // Enable to set/clear PA0-PA3 with status register
    SET_LED(0xF); // Clear leds

    // Setup ADC
    AT91C_BASE_ADC->ADC_MR = AT91C_ADC_TRGEN_DIS | AT91C_ADC_LOWRES_10_BIT | AT91C_ADC_SLEEP_NORMAL_MODE | AT91C_ADC_PRESCAL | AT91C_ADC_STARTUP | AT91C_ADC_SHTIM; // software trigger, 10 bits, normal mode, max time
    AT91C_BASE_ADC->ADC_CHER = AT91C_ADC_CH0;   // Enable channel 0

    while(1)
    {
        AT91F_ADC_StartConversion(AT91C_BASE_ADC);  // Start conversion
        while(!(AT91C_BASE_ADC->ADC_SR & AT91C_ADC_EOC0)); // Wait for conversion to finish
        nAD = AT91F_ADC_GetConvertedDataCH0(AT91C_BASE_ADC);    // Get converted data from channel 0

        SET_LED(~(nAD >> 6));   // Show the four most significant bits
    }
}

