From daf34ae9ab7146b8cfbb2c7983b4ba87dd0ccb89 Mon Sep 17 00:00:00 2001
From: Cristian Maglie <c.maglie@arduino.cc>
Date: Fri, 21 Nov 2014 17:44:24 +0100
Subject: [PATCH]  Fixed analogReadResolution behaviour

---
 cores/arduino/wiring_analog.c | 30 +++++++++++++++++-------------
 1 file changed, 17 insertions(+), 13 deletions(-)

diff --git a/cores/arduino/wiring_analog.c b/cores/arduino/wiring_analog.c
index ff356b41..9a647de7 100644
--- a/cores/arduino/wiring_analog.c
+++ b/cores/arduino/wiring_analog.c
@@ -25,7 +25,8 @@ extern "C" {
 #endif
 
 static int _readResolution = 10;
-static int _writeResolution = 10;
+static int _ADCResolution = 10;
+static int _writeResolution = 8;
 
 // Wait for synchronization of registers between the clock domains
 static __inline__ void syncADC() __attribute__((always_inline, unused));
@@ -43,20 +44,23 @@ static void syncDAC() {
 
 void analogReadResolution( int res )
 {
+  _readResolution = res ;
   syncADC();
-  switch ( res )
+  if (res > 10)
   {
-    case 12:
-      ADC->CTRLB.bit.RESSEL = ADC_CTRLB_RESSEL_12BIT_Val;
-      break;
-    case 8:
-      ADC->CTRLB.bit.RESSEL = ADC_CTRLB_RESSEL_8BIT_Val;
-      break;
-    default:
-      ADC->CTRLB.bit.RESSEL = ADC_CTRLB_RESSEL_10BIT_Val;
-      break;
+    ADC->CTRLB.bit.RESSEL = ADC_CTRLB_RESSEL_12BIT_Val;
+    _ADCResolution = 12;
+  }
+  else if (res > 8)
+  {
+    ADC->CTRLB.bit.RESSEL = ADC_CTRLB_RESSEL_10BIT_Val;
+    _ADCResolution = 10;
+  }
+  else
+  {
+    ADC->CTRLB.bit.RESSEL = ADC_CTRLB_RESSEL_8BIT_Val;
+    _ADCResolution = 8;
   }
-  _readResolution = res ;
 }
 
 void analogWriteResolution( int res )
@@ -179,7 +183,7 @@ uint32_t analogRead( uint32_t ulPin )
   ADC->CTRLA.bit.ENABLE = 0x00;             // Disable ADC
   syncADC();
 
-  return valueRead;
+  return mapResolution(valueRead, _ADCResolution, _readResolution);
 }
 
 
-- 
GitLab