Bug in robot_hat get_battery_voltage() — NameError: '_adc_obj' is not defined

Hi,

I think I found a small bug in the robot-hat library (PiDog V2, Robot HAT V5, Raspberry Pi 5, Python 3.13). Calling get_battery_voltage() raises on every call:

NameError: name '_adc_obj' is not defined
  File ".../robot_hat/device.py", line 187, in get_battery_voltage
    if not isinstance(_adc_obj, ADC):

Looking at the source: in device.py, get_battery_voltage() does global _adc_obj and then if not isinstance(_adc_obj, ADC): _adc_obj = ADC("A4") — but _adc_obj is never initialized in device.py. The _adc_obj = None declaration only exists in utils.py (in the deprecated versions of these functions). So the first access in device.py fails with NameError. It looks like the functions were moved from utils.py to device.py during a refactor, but the _adc_obj = None module-level init was not carried over.

Reading the ADC directly works fine, so it really is just the missing global init:

from robot_hat import ADC
adc = ADC("A4")
voltage = round(adc.read_voltage() * 3, 2)   # ~7.79 V on my charged battery

A simple fix would be to add _adc_obj = None at module level in device.py (as it already is in utils.py).

Could you confirm this is a known issue, and whether it’s fixed in a newer robot-hat version? In the meantime I’m reading ADC("A4") directly as a workaround.

Thanks for the great hardware, and for your earlier reply about the servos.

Thank you for your feedback. We have already forwarded this issue to our technical team.

Since you have found a working workaround by directly reading ADC(“A4”), please continue using that method for now. We plan to fix this issue in the next update of the robot-hat library.

Thank you again for your detailed report and for helping us improve.

1 Like