Last active
September 29, 2015 20:02
-
-
Save antonvh/c81c247fc03029a1ba6a to your computer and use it in GitHub Desktop.
Get Voltage from BrickPi+
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import smbus | |
def get_voltage(): | |
""" | |
Reads the digital output code of the MCP3021 chip on the BrickPi+ over i2c. | |
Some bit operation magic to get a voltage floating number. | |
If this doesnt work try this on the command line: i2cdetect -y 1 | |
The 1 in there is the bus number, same as in bus = smbus.SMBus(1) | |
Google the resulting error. | |
:return: voltage (float) | |
""" | |
try: | |
bus = smbus.SMBus(1) # SMBUS 1 because we're using greater than V1. | |
address = 0x48 | |
# time.sleep(0.1) #Is this necessary? | |
# read data from i2c bus. the 0 command is mandatory for the protocol but not used in this chip. | |
data = bus.read_word_data(address, 0) | |
# from this data we need the last 4 bits and the first 6. | |
last_4 = data & 0b1111 # using a bit mask | |
first_6 = data >> 10 # right shift 10 because data is 16 bits | |
# together they make the voltage conversion ratio | |
# to make it all easier the last_4 bits are most significant :S | |
vratio = (last_4 << 6) | first_6 | |
# Now we can calculate the battery voltage like so: | |
ratio = 0.0179 # This is an empyrical value based on several different batteries | |
voltage = vratio * ratio | |
return voltage | |
except: | |
return 0.0 | |
if __name__ == "__main__": | |
print get_voltage() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment