Measuring battery voltage with ADC gpio

ThomasThomas New Member Posts: 18
edited May 2017 in 40-PIN GP-bus
I am trying to measure battery voltage using the ADC pin which is listed as gpio2 on the data sheet. However when I try to create the gpio object

mraa:Gpio adc = new mraa::Gpio(2);

I get the error "Invalid GPIO pin specified". Is the mraa gpio numbering the same as the datasheet's?

Also from what I read about the ADC, I think the command

printf("voltage %d \n",adc->read());

should print a integer between 0-255 which corresponds to the voltage between 0-3.3v on the gpio pin. Is this correct?




  • ThomasThomas New Member Posts: 18
    I found that
    mraa:Gpio adc = new mraa::Gpio(7);

    is the right command, but when I do

    printf("voltage %d \n",adc->read());

    The program prints 1 regardless of the voltage applied to that pin.

    Do I need to do something further to get the ADC pin working?

    Thank you,

  • WereCatfWereCatf New Member Posts: 201
    You are not reading the analog value of the pin, you're reading it as a digital GPIO-pin. Use the aio-class instead: and
  • ThomasThomas New Member Posts: 18
    Thank you very much!
  • HannibalHannibal New Member Posts: 4
    Is there any Python code example for reading ADC value in UP board?
  • Dan O'DonovanDan O'Donovan Emutex Posts: 225 mod
    I don't have a prepared example to send you. But I suggest the following, which should be straightforward to implement:
    - Read the value from '/sys/bus/iio/devices/iio:device0/in_voltage_scale'. You'll only need to do this once (or you could hard-code it as well if you prefer, as it doesn't change)
    - Read the value from '/sys/bus/iio/devices/iio:device0/in_voltage_raw'. This is the "live" raw value obtained directly from the ADC. Its an 8-bit value, so it will be an integer between 0-255.

    Multiply the raw value by the scale value. Now you have a reading from the ADC in millivolts.
  • HannibalHannibal New Member Posts: 4
    Thank you
Sign In or Register to comment.