Commit aadc0347 authored by Erik Strand's avatar Erik Strand

Expand analogRead

parent 641537e0
#include "wiring_private.h"
#define LED_GREEN 23
#define SENSE_LINE_0 2
int value;
// 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();
//}
#if defined(REMAP_ANALOG_PIN_ID)
REMAP_ANALOG_PIN_ID(pin);
#endif
#if (SAMC21 || SAMD51)
Adc* ADC;
if ( (g_APinDescription[pin].ulPeripheralAttribute & PER_ATTR_ADC_MASK) == PER_ATTR_ADC_ALT ) {
ADC = ADC1;
} else {
ADC = ADC0;
}
#endif
// 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);
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(LED_GREEN, OUTPUT);
// Calling the regular method once ensures that the ADC does get initialized.
analogRead(SENSE_LINE_0);
}
void loop() {
// put your main code here, to run repeatedly:
value = analogRead(SENSE_LINE_0);
value = bm_analogRead(SENSE_LINE_0);
Serial.println(value);
delay(1000);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment