1

I am trying to simply read a voltage from a battery. I am able to work out how to do this using arduino code on an arduino board. (UNO)

When I try to do the same thing on a board using python the output seems erroneous.

Using arduino I will say for example get a voltage output to serial monitor or 1.39v which stays pretty much constant.

When doing so with the python board (Trinket M0) the output varies from 1.23342 -1.78484 and varies between these values.

My arduino code is as follows:

int offset =0;// set the correction offset value
void setup() {
  // Robojax.com voltage sensor
  Serial.begin(9600);
}

void loop() {
  // Robojax.com voltage sensor
  int volt = analogRead(A0);// read the input
  double voltage = map(volt,0,1023, 0, 2500) + offset;// map 0-1023 to 0-2500 and add correction offset
  
  voltage /=100;// divide by 100 to get the decimal values
  Serial.print("Voltage: -");
  Serial.print(voltage);//print the voltge
  Serial.println("V");

delay(500);
  
  
}

My Python code is as follows

import time
import board
from analogio import AnalogIn

analog_in = AnalogIn(board.A1)


def get_voltage(pin):
    return (pin.value * 3.3) / 65536


while True:
   print((get_voltage(analog_in),))
    time.sleep(0.1)
    

2
  • Have you checked the voltage with a multi-meter while the Trinket M0 is running, to compare against a reference? Perhaps the M0 reading is correct? Commented Nov 22, 2021 at 20:34
  • Ok, i had made a really stupid mistake and had wired the analogue pin incorrectly. However, now my reading in the serial console read 0.33456 -0.34564 the voltmeter reads voltage as 1.42v Commented Nov 22, 2021 at 20:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.