adc.ino 1.92 KB
Newer Older
Erik Strand's avatar
Erik Strand committed
1 2
#include "wiring_private.h"

3 4 5 6 7
#define LED_GREEN 23
#define SENSE_LINE_0 2

int value;

Erik Strand's avatar
Erik Strand committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
// Note that these values need to be kept in sync with the originals in analog_wiring.c.
static int _readResolution = 10;
static int _ADCResolution = 10;

// Wait for synchronization of registers between the clock domains
static __inline__ void syncADC() __attribute__((always_inline, unused));
static void syncADC() { while ( ADC->STATUS.bit.SYNCBUSY == 1 ); }

static inline uint32_t mapResolution(uint32_t value, uint32_t from, uint32_t to)
{
    if (from == to) {
        return value;
    }
    if (from > to) {
        return value >> (from-to);
    }
    return value << (to-from);
}


uint32_t bm_analogRead( uint32_t pin )
{
    uint32_t valueRead = 0;

    // Uses a variable outside this translation unit
    //if (!ADCinitialized) {
    //    initADC();
    //}

    // pinPeripheral now handles disabling the DAC (if active)
    if ( pinPeripheral(pin, PIO_ANALOG_ADC) == RET_STATUS_OK )
    {
        ADC->INPUTCTRL.bit.MUXPOS = GetADC(pin); // Selection for the positive ADC input

        syncADC();

        ADC->CTRLA.bit.ENABLE = 0x01;             // Enable ADC
        syncADC();

        // Start conversion
        ADC->SWTRIG.bit.START = 1;
        syncADC();

        // Store the value
        while (ADC->INTFLAG.bit.RESRDY == 0);   // Waiting for conversion to complete
        valueRead = ADC->RESULT.reg;

        ADC->CTRLA.bit.ENABLE = 0x00;             // Disable ADC
        syncADC();
    }

    return mapResolution(valueRead, _ADCResolution, _readResolution);
}


63 64 65 66
void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(LED_GREEN, OUTPUT);
Erik Strand's avatar
Erik Strand committed
67 68
    // Calling the regular method once ensures that the ADC does get initialized.
    analogRead(SENSE_LINE_0);
69 70 71 72
}

void loop() {
    // put your main code here, to run repeatedly:
Erik Strand's avatar
Erik Strand committed
73
    value = bm_analogRead(SENSE_LINE_0);
74 75 76
    Serial.println(value);
    delay(1000);
}