You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ADC电池电压测量代码故障排查:读数错误且未读取A0引脚

ADC电池电压测量代码故障排查请求

我使用以下代码进行ADC电池电压测量,但执行后未达到预期效果:代码持续输出错误电压值,且未从A0引脚读取电压,推测是引脚配置或电路连接存在问题。我已对代码部分内容进行修改,相关截图包括:

  • 修改后的完整代码截图
  • 实际电路连接截图
  • 代码修改部分的细节截图

请求协助排查问题,使代码能够正常读取电池电压。

原代码

void setup() {
  Serial.begin(9600);
  Serial.println("Setup completed.");
}

void loop() {

  // Read external battery VCC voltage
  Serial.print("Bat: ");
  uint16_t batVolts = getBatteryVolts();
  Serial.print(batVolts);
  Serial.print(" - ");
  Serial.println(getBatteryVolts2());

  delay(500);
}

// One way of getting the battery voltate without any double or float calculations
unsigned int getBatteryVolts() {
  //http://www.gammon.com.au/adc

  // Adjust this value to your boards specific internal BG voltage x1000
  const long InternalReferenceVoltage = 1100L; // <-- change this for your ATMEga328P pin 21 AREF value

  // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc external reference
  // MUX3 MUX2 MUX1 MUX0  --> 1110 1.1V (VBG)         -Selects channel 14, bandgap voltage, to measure
  ADMUX = (0 << REFS1) | (1 << REFS0) | (0 << ADLAR) | (1 << MUX3) | (1 << MUX2) | (1 << MUX1) | (0 << MUX0);

  // Let mux settle a little to get a more stable A/D conversion
  delay(50);

  // Start a conversion
  ADCSRA |= _BV( ADSC );

  // Wait for conversion to complete
  while ( ( (ADCSRA & (1 << ADSC)) != 0 ) );

  // Scale the value - calculates for straight line value
  unsigned int results = (((InternalReferenceVoltage * 1024L) / ADC) + 5L) / 10L;
  return results;
}

// A different way using float to determine the VCC voltage
float getBatteryVolts2() {
  // You MUST measure the voltage at pin 21 (AREF) using just a simple one line sketch consisting
  // of:  analogReference(INTERNAL);
  //      analogRead(A0);
  // Then use the measured value here.

  const float InternalReferenceVoltage = 1.1; // <- as measured (or 1v1 by default)

  // turn ADC on
  ADCSRA =  bit (ADEN);

  // Prescaler of 128
  ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);

  // MUX3 MUX2 MUX1 MUX0  --> 1110 1.1V (VBG) - Selects channel 14, bandgap voltage, to measure
  ADMUX = bit (REFS0) ;
  ADMUX |= B00000000;       //I made it A0   //ADMUX = bit (REFS0) | bit (MUX3) | bit (MUX2) | bit (MUX1);

  // let it stabilize
  delay (10);

  // start a conversion
  bitSet (ADCSRA, ADSC);

  // Wait for the conversion to finish
  while (bit_is_set(ADCSRA, ADSC))
  {
    ;
  }

  // Float normally reduces precion but works OK here. Add 0.5 for rounding not truncating.
  float results = InternalReferenceVoltage / float (ADC + 0.5) * 1024.0;
  return results;
}

内容的提问来源于stack exchange,提问作者electro_nooobbbb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 08:25:57