I was trying to convert this code I grabbed from the Discord from Arduino C/C++ to MicroPython:
JasonTC — 03/22/2022
It is possible to check the battery voltage. The battery is connected on ADC0/GPIO26 to a voltage divider.
I don't have anything in MicroPython, but here's some Arduino C/C++ code someone else wrote:
float total = 0.0f;
const int numberSamples = 25;
for(int i=0; i<numberSamples; i++){
float battVoltage = analogRead(A0);
battVoltage = 2.0 * 3.3 * battVoltage / (4095.0);
battVoltage = (int) (battVoltage * 100.0 + 0.5) / 100.0;
total += battVoltage;
}
Serial.print("Battery: ");
Serial.println(total/numberSamples);
I'm trying to switch it over to MicroPython:
adc = ADC(26)
battVoltage = 1.0
numberSamples = 25
while(1):
total = 0
for int in range (0, numberSamples):
thumby.display.fill(0)
battVoltage = adc.read_u16()
battVoltage = 2.0 * 3.3 * battVoltage / (4095.0)
battVoltage = (battVoltage * 100.0 + 0.5) / 100.0
total = battVoltage + total
thumby.display.update()
thumby.display.fill(0)
thumby.display.drawText("Battery:", 1, 1, 1)
thumby.display.drawText(str(total/numberSamples), 1, 11, 1)
battVoltage = adc.read_u16()
thumby.display.drawText(str(battVoltage), 1, 21, 1)
thumby.display.update()
time.sleep(2)
I'm not exactly sure that the math translates from Arduino C/C++ code to MicroPython. I think the value from "battVoltage = adc.read_u16()" might be throwing me off? I'm not sure exactly what is going on with the math. This is the first time I'm trying to interact with a pin too. So I'm not sure if I'm 100% sure doing that right either
I've exhausted my google-fu.
If anyone has any info/advise on battery math or things I might be able to google to set me on the right path, that would be cool.
![Cheesy :D](https://forum.tinycircuits.com/Smileys/default/cheesy.gif)