- 아두이노 우노의 3.3V 핀을 A0에 연결해서 전압측정함.

>측정시 5V의 실제 전압은 4.65V가 나와서 (PC USB PORT <-> UNO) 이 값으로 Aref 핀에 연결하고 측정함. 

(이렇게 해야 정확한 값이 측정됨)

16:18:42.132 -> digital value = 742, Aref:4.64, ADC voltage = 3.36
16:18:43.188 -> digital value = 743, Aref:4.64, ADC voltage = 3.36
16:18:44.242 -> digital value = 740, Aref:4.65, ADC voltage = 3.36
16:18:45.312 -> digital value = 742, Aref:4.64, ADC voltage = 3.36
16:18:46.352 -> digital value = 743, Aref:4.64, ADC voltage = 3.36
16:18:47.423 -> digital value = 742, Aref:4.62, ADC voltage = 3.35
16:18:48.480 -> digital value = 742, Aref:4.64, ADC voltage = 3.36

 

- Aref 전압을 입력받아서 정확한 값 측정,

int sensorPin = A0;  // input pin for the potentiometer
int digitalValue = 0;// variable to store the value coming from the sensor

void setup() {
  Serial.begin(9600);
  // 아날로그 입력 핀을 읽기 전에 아날로그 기준 값을 외부 전원을
  // 사용하는 것으로 설정합니다:
}

void loop() {
//  analogReference(EXTERNAL);  
  delay(10);
  digitalValue = analogRead(sensorPin);// read the value from the analog channel
  Serial.print("digital value = ");
  Serial.print(digitalValue);        //print digital value on serial monitor

  float voltage = readAref();
  Serial.print(", Aref:");
  Serial.print(voltage);  
 
  float ADC_voltage = voltage * (float)digitalValue / (float)1024;
  Serial.print(", ADC voltage = ");
  Serial.println( ADC_voltage );        //print digital value on serial monitor
  delay(1000);
}

//
// Function readAref
//
// Reads AREF (when external voltage is supplied).
// When the AREF pin is open, a value of 1.1V is returned.
// This function is only valid for a voltage at AREF of 1.1 to 5V.
//
// The calculations can be translated for integers to prevent
// use of float.
// Only for the Arduino Uno, Nano, Pro Micro at this moment.
// Experimental, no guarantees.
// public domain
//
float readAref (void) {
  float volt;

#if defined (__AVR_ATmega8__)
#elif defined (__AVR_ATmega168__)
#elif defined (__AVR_ATmega168A__)
#elif defined (__AVR_ATmega168P__)
#elif defined (__AVR_ATmega328__)
#elif defined (__AVR_ATmega328P__)

  // set reference to AREF, and mux to read the internal 1.1V
  // REFS1 = 0, REFS0 = 0, MUX3..0 = 1110
  ADMUX = _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
 
  // Enable the ADC
  ADCSRA |= _BV(ADEN);

  // Wait for voltage to become stable after changing the mux.
  delay(20);

  // Start ADC
  ADCSRA |= _BV(ADSC);

  // wait for the ADC to finish
  while (bit_is_set(ADCSRA,ADSC));

  // Read the ADC result
  // The 16-bit ADC register is 'ADC' or 'ADCW'
  unsigned int raw = ADCW;

  // Calculate the Aref.
  volt = 1.1 / (float) raw * 1024.0;

#elif defined (__AVR_ATmega32U4__)
#elif defined (__AVR_ATmega1280__) || defined (__AVR_ATmega2560__)
#endif


  // Try to return to normal.
  analogReference(EXTERNAL);
  analogRead(A0);            // the mux is set, throw away ADC value
  delay(20);                 // wait for voltages to become stable

  return volt;
}
posted by cskimair
: