從模擬引腳獲取電壓

模擬引腳可用於讀取電壓,這對電池監控或與模擬裝置介面非常有用。預設情況下,AREF 引腳與 arduino 的工作電壓相同,但可以在外部設定為其他值。如果要讀取的電壓大於輸入電壓,則需要潛在的分壓器來降低模擬電壓。

#define analogPin 14    //A0 (uno)
#define AREFValue 5        //Standard for 5V Arduinos
#define ADCResolution 1023    //Standard for a 10bit ADC

int ADCValue = 0;
float voltage = 0;

void setup()
{
    Serial.begin(9600);
}

void loop() 
{
    readADC();
    Serial.print(voltage); Serial.println("V");
}

void readADC()
{
    ADCValue = analogRead(analogPin);
    float = ( ( (float)ADCValue/ADCRange ) * AREFValue );    //Convert the ADC value to a float, devide by the ADC resolution and multiply by the AREF voltage
}