def __init__(self, measure, unit, device, address): """Initialize the sensor.""" self._measure = measure self._unit = unit i2c_bus = I2C(device) self._device = device self._address = address self.ina219 = INA219(i2c_bus, address) value = getattr(self.ina219, self._measure) self._state = round(value, 2)
def power(): print(colored("INA219 started. . .", 'green')) ina219 = INA219(i2c, addr=0x41) powers = [] while True: for i in range(0, 300): powers.append(ina219.power) time.sleep(.1) avg_power_consumption = sum(powers)/len(powers) with lock: database.create_record(conn, "Measurements", ("power", avg_power_consumption)) powers = []
def get_voltage(battery): # Convert 1 to 0x40, 2 to 0x41, etc addr = "0x" + str(39 + int(battery)) i2c_bus = board.I2C() ina = INA219(i2c_bus, addr=int(addr, 16)) ina.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina.bus_voltage_range = BusVoltageRange.RANGE_16V voltage = ina.bus_voltage voltagerounded = round(voltage, 2) return str(voltagerounded)
def getPowerLevels(): import board from adafruit_ina219 import INA219, ADCResolution, BusVoltageRange dic = {0x40: "Pi", 0x41: "Battery", 0x42: "Solar", 0x43: "Unknown"} i2c_bus = board.I2C() for address in dic: ina = INA219(i2c_bus, addr=address) ina.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina.bus_voltage_range = BusVoltageRange.RANGE_16V yield PowerLevel(dic[address], ina.bus_voltage, ina.power, ina.current, ina.shunt_voltage) i2c_bus.deinit()
def recordEnergyConsumption(path='data'): print("ina219 start") fileName = path + '/ina219-' + str(datetime.date.today()) + '-' + str( int(time.time())) + '.csv' i2c_bus = board.I2C() ina219 = INA219(i2c_bus) # optional : change configuration to use 32 samples averaging for both bus voltage and shunt voltage ina219.bus_adc_resolution = ADCResolution.ADCRES_12BIT_128S ina219.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_128S # optional : change voltage range to 16V ina219.bus_voltage_range = BusVoltageRange.RANGE_16V ina219.mode = Mode.SVOLT_CONTINUOUS dataDF = pd.DataFrame(columns=['mA', 'V', 'time']) startTime = time.time() #run till selenium done while global_flag: if ina219.conversion_ready == 1: bus_voltage = ina219.bus_voltage # voltage on V- (load side) current = ina219.current # current in mA dataDF = dataDF.append( { 'mA': current, 'V': bus_voltage, 'time': time.time() }, ignore_index=True) elapsedTime = time.time() testTime = elapsedTime - startTime #save data to file try: with open(fileName) as csvfile: print("This file already exists!") except: dataDF.to_csv(fileName, sep=',', index=False) print("ina219 done")
if (len(sys.argv)) > 1: # print("There are arguments!") # if (('a' == sys.argv[1]) or ('afsk' in sys.argv[1])): bus = int(sys.argv[1], base=10) if (len(sys.argv)) > 2: address = int(sys.argv[2], base=16) else: address = 0x40 else: bus = 1 address = 0x40 try: # Create library object using Extended Bus I2C port i2c_bus = I2C(bus) # 1 Device is /dev/i2c-1 ina219 = INA219(i2c_bus, address) # optional : change configuration to use 32 samples averaging for both bus voltage and shunt voltage ina219.bus_adc_resolution = ADCResolution.ADCRES_12BIT_1S # 32S ina219.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_1S # 32S # optional : change voltage range to 16V ina219.bus_voltage_range = BusVoltageRange.RANGE_16V current = ina219.current # current in mA print("{:9.1f}".format(current)) except: print("0.0 Error")
# """Sample code and test for adafruit_in219""" import sys import time import board from adafruit_ina219 import ADCResolution, BusVoltageRange, INA219 addr = 0x40 if len(sys.argv) > 1: addr = int(sys.argv[1]) i2c_bus = board.I2C() ina219 = INA219(i2c_bus, addr=addr) print("ina219 test (addr:" + str(addr) + ")") # display some of the advanced field (just to test) print("Config register:") print(" bus_voltage_range: 0x%1X" % ina219.bus_voltage_range) print(" gain: 0x%1X" % ina219.gain) print(" bus_adc_resolution: 0x%1X" % ina219.bus_adc_resolution) print(" shunt_adc_resolution: 0x%1X" % ina219.shunt_adc_resolution) print(" mode: 0x%1X" % ina219.mode) print("") # optional : change configuration to use 32 samples averaging for both bus voltage and shunt voltage ina219.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina219.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S
def initialize(self): """ Initialize INA219x sensor """ from adafruit_ina219 import INA219, ADCResolution, BusVoltageRange from adafruit_extended_bus import ExtendedI2C try: self.sensor = INA219(ExtendedI2C(self.input_dev.i2c_bus), addr=int(str(self.input_dev.i2c_location), 16)) except (ValueError, OSError) as msg: self.logger.exception("INA219x Exception: %s", msg) return None if not self.sensor: self.logger.error("INA219x sensor unable to initialize.") return None self.measurements_for_average = self.measurements_for_average # calibrate voltage and current detection range if self.calibration == '1': self.sensor.set_calibration_32V_1A() self.logger.debug("INA219x: set_calibration_32V_1A()") elif self.calibration == '2': self.sensor.set_calibration_16V_400mA() self.logger.debug("INA219x: set_calibration_16V_400mA()") elif self.calibration == '3': self.sensor.set_calibration_16V_5A() self.logger.debug("INA219x: set_calibration_16V_5A()") else: # use default sensor calibration of 32V / 2A self.sensor.set_calibration_32V_2A() self.logger.debug("INA219x: set_calibration_32V_2A()") BUS_VOLTAGE_RANGE = { '0': BusVoltageRange.RANGE_16V, '1': BusVoltageRange.RANGE_32V } # calibrate sensor bus voltage range self.sensor.bus_voltage_range = BUS_VOLTAGE_RANGE.get( self.bus_voltage_range, BUS_VOLTAGE_RANGE['1']) ADC_RESOLUTION = { '00': ADCResolution.ADCRES_9BIT_1S, '01': ADCResolution.ADCRES_10BIT_1S, '02': ADCResolution.ADCRES_11BIT_1S, '03': ADCResolution.ADCRES_12BIT_1S, '09': ADCResolution.ADCRES_12BIT_2S, '0A': ADCResolution.ADCRES_12BIT_4S, '0B': ADCResolution.ADCRES_12BIT_8S, '0C': ADCResolution.ADCRES_12BIT_16S, '0D': ADCResolution.ADCRES_12BIT_32S, '0E': ADCResolution.ADCRES_12BIT_64S, '0F': ADCResolution.ADCRES_12BIT_128S } # calibrate sensor ADC resolutions self.sensor.bus_adc_resolution = ADC_RESOLUTION.get( self.bus_adc_resolution, ADC_RESOLUTION['03']) self.sensor.shunt_adc_resolution = ADC_RESOLUTION.get( self.shunt_adc_resolution, ADC_RESOLUTION['03'])
def __init__(self): i2c = busio.I2C(board.SCL, board.SDA) self.device = INA219(i2c)
from adafruit_ina219 import ADCResolution, BusVoltageRange addresses = [0x40, 0x41, 0x44, 0x45] #INA219 addresses on the bus # print("buses: ", buses, " addr: ", addresses) for x in buses: try: i2c_bus = I2C(x) # Device is /dev/i2c-x for y in addresses: # print(x,y) try: # Create library object using Extended Bus I2C port # print("bus: ", x, " addr: ", y) if x == 0 and y == 0x45: # print("Reading INA219 in MoPower Board") i2c_bus = I2C(1) ina219 = INA219(i2c_bus, 0x4a) else: ina219 = INA219(i2c_bus, y) # print("ina219 test") if config: # print("Configuring") # optional : change configuration to use 32 samples averaging for both bus voltage and shunt voltage ina219.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S # 1S ina219.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S # 1S # optional : change voltage range to 16V ina219.bus_voltage_range = BusVoltageRange.RANGE_16V bus_voltage = ina219.bus_voltage # voltage on V- (load side) # shunt_voltage = ina219.shunt_voltage # voltage between V+ and V- across the shunt current = ina219.current # current in mA
servoX_value = 2.5 servoY_value = 2.5 servoX.start(servoX_value) servoY.start(servoY_value) servoX_value_old = 2.5 servoY_value_old = 2.5 time.sleep(2) ldr = {"lb": 0, "rb": 0, "lo": 0, "ro": 0} adc = ADC(10**5) offset = 15 ldr_counter = 0 i2c_bus = board.I2C() manual_mode = 0 ip_old = "" solar = INA219(i2c_bus, 0x41) battery = INA219(i2c_bus, 0x40) def get_all_ldr(): ldr["lb"] = adc.analogRead(0) ldr["lo"] = adc.analogRead(1) ldr["rb"] = adc.analogRead(2) ldr["ro"] = adc.analogRead(3) servo_move(ldr) def get_ip_print_to_display(): global ip_old ips = str(check_output(['hostname', '-I'])) ipslist = ips.replace("b'", "").split(" ")
def main(): global DISPLAY_ENABLED global Logging_ENABLED # Create the I2C interface. i2c = busio.I2C(board.SCL, board.SDA) # Create the SSD1306 OLED class. # The first two parameters are the pixel width and pixel height. # Change these to the right size for your display! try: disp = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c) except: print("Searching SSD1306 Display ... Failed!\n") DISPLAY_ENABLED = False if (DISPLAY_ENABLED): print("Display ... Enabled\n") # Clear display. disp.fill(0) disp.show() # Create blank image for drawing. # Make sure to create image with mode '1' for 1-bit color. width = disp.width height = disp.height image = Image.new('1', (width, height)) # Get drawing object to draw on image. draw = ImageDraw.Draw(image) # Draw a black filled box to clear the image. draw.rectangle((0, 0, width, height), outline=0, fill=0) # Draw some shapes. # First define some constants to allow easy resizing of shapes. padding = -2 top = padding bottom = height - padding # Move left to right keeping track of the current x position for drawing shapes. x = 0 # Load default font. font = ImageFont.load_default() # Alternativly load TTF font. Make sure the .ttf font file is in the # same directory as the python script! # Some other nice fonts to try: http://www.dafont.com/bitmap.php # font = ImageFont.truetype('/user/share/fonts/truetype/dejavu/DejaVuSans.ttf', g) # Draw a black Filled box to clear the image. draw.rectangle((0, 0, width, height), outline=0, fill=0) # Shell scripts for system monitoring from here: # https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load cmd = "hostname -I | cut -d\' \' -f1" ## cut -d' ' -f1 IP = subprocess.check_output(cmd, shell=True).decode("utf-8") draw.text((x, top + 0), "IP: " + IP, font=font, fill=255) # Display image. disp.image(image) disp.show() ina219_1 = INA219(i2c_bus=i2c, addr=0x40) ina219_1 = config_ina219(ina219_1) ina219_2 = INA219(i2c_bus=i2c, addr=0x41) config_ina219(ina219_2) # display some of the advanced field (just to test) print("INA219 Config Register:") print(" bus_voltage_range: 0x%1X" % ina219_1.bus_voltage_range) print(" gain: 0x%1X" % ina219_1.gain) print(" bus_adc_resolution: 0x%1X" % ina219_1.bus_adc_resolution) print(" shunt_adc_resolution: 0x%1X" % ina219_1.shunt_adc_resolution) print(" mode: 0x%1X" % ina219_1.mode) print("") try: duration = 0.01 # arg[1] sample duration in hours -- (36s) dly = 1 # arg[2] sample timer interval in seconds -- (10s) if (len(sys.argv) == 3): Logging_ENABLED = True print('Logging ... Enalbed') if ((float(sys.argv[1]) < 48) and (float(sys.argv[1]) > 0)): # maximum 48 hours duration = float(sys.argv[1]) if ((int(sys.argv[2]) < 100) and (int(sys.argv[2]) > 0)): dly = int(sys.argv[2]) print('Sample duration: %.3f hours, interval: %02d seconds' % (duration, dly)) wdir = './log' if (os.path.exists(wdir)): print("Log folder exists") else: os.mkdir(wdir) else: Logging_ENABLED = False print('Logging ... Disabled!') print("") count = 0 fidx = 1 t0 = datetime.datetime.now() if (Logging_ENABLED): fn = t0.strftime("%Y-%m%d-%H%M") + '-%ds.log' % dly f = open(wdir + '/' + fn, 'w') print('--------------------------------------') print('ina1 V mA | ina2 V mA') print('--------------------------------------') while (1): # check sample time t1 = datetime.datetime.now() dt = t1 - t0 hours_passed = get_hours_passed(dt) # s = dt.total_seconds() # elapsed_time = '{:02}:{:02}:{:02}'.format(s // 3600, s % 3600 // 60, s % 60) elapsed_time = str(dt).split('.')[0] if (Logging_ENABLED and (hours_passed > duration)): break if (Logging_ENABLED and (count != 0 and count % 500 == 0)): # close current file first f.close() fidx += 1 t = datetime.datetime.now() fn = t.strftime("%Y-%m%d-%H%M") + '-%ds.log' % dly f = open(wdir + '/' + fn, 'w') count += 1 v1, i1, v2, i2 = read_ina_2(ina219_1, ina219_2) if (Logging_ENABLED): f.write('%0.3f,%0.3f,%0.3f,%0.3f\n' % (v1, i1, v2, i2)) test1 = '0x{0:x}: {1:0.3f}V {2:0.3f}mA'.format( ina219_1.i2c_addr, v1, i1) test2 = '0x{0:x}: {1:0.3f}V {2:0.3f}mA'.format( ina219_2.i2c_addr, v2, i2) print(test1 + '|' + test2) # print('0x{0:x}: {1:0.3f}V {2:0.3f}mA | 0x{3:x}: {4:0.3f}V {5:0.3f}mA'.format( # ina219_1.i2c_addr, v1, i1, ina219_2.i2c_addr, v2, i2)) if (DISPLAY_ENABLED): # Draw a black Filled box to clear the image. draw.rectangle((0, top + 9, width, height - (top + 9)), outline=0, fill=0) # draw.text((x, top+8), 'Elapsed T: %.1f (m)'%(hours_passed*60), font=font, fill=255) draw.text((x, top + 8), 'Elapsed: ' + elapsed_time, font=font, fill=255) draw.text((x, top + 16), test1, font=font, fill=255) draw.text((x, top + 25), test2, font=font, fill=255) disp.image(image) disp.show() time.sleep(dly) if (Logging_ENABLED and (not f.closed)): f.close() except KeyboardInterrupt: print("\nCtrl-C pressed. Program exiting...") finally: pass
# ina219.bus_voltage_range = BusVoltageRange.RANGE_16V # except: # print("Python Error 2", file=sys.stderr, flush=True) # except: # print("Python Error 1", file=sys.stderr, flush=True) # No try checking yet # if buses[0] == 0 and addresses[0] == 0x45: # print("Reading INA219 in MoPower Board") # ina219_one = INA219(I2C(1), 0x4a) # else: if (buses[0] != -1): try: i2c_one = I2C(buses[0]) try: ina219_one = INA219(i2c_one, addresses[0]) ina219_one.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S # 1S time.sleep(0.001) ina219_one.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S # 1S time.sleep(0.001) ina219_one.bus_voltage_range = BusVoltageRange.RANGE_16V time.sleep(0.01) one = 1 except: # print("Python Error 3", file=sys.stderr, flush=True) one = 0 try: ina219_two = INA219(i2c_one, addresses[1]) ina219_two.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S # 1S time.sleep(0.001) ina219_two.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S # 1S
def recordEnergyConsumption(path='data'): print("ina219 start") fileName = path+'/ina219-'+str(datetime.date.today())+'-'+str(int(time.time()))+'.csv' print(fileName) i2c_bus = board.I2C() ina219 = INA219(i2c_bus) # optional : change configuration to use 32 samples averaging for both bus voltage and shunt voltage ina219.bus_adc_resolution = ADCResolution.ADCRES_12BIT_128S ina219.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_128S # optional : change voltage range to 16V ina219.bus_voltage_range = BusVoltageRange.RANGE_16V ina219.mode = Mode.SVOLT_CONTINUOUS # display some of the advanced field # see https://github.com/adafruit/Adafruit_CircuitPython_INA219/blob/master/adafruit_ina219.py class ADCResolution for details """ print("Arguments: " + str(sys.argv)) print("Config register:") print(" bus_voltage_range: 0x%1X" % ina219.bus_voltage_range) print(" gain: 0x%1X" % ina219.gain) print(" bus_adc_resolution: 0x%1X" % ina219.bus_adc_resolution) print(" shunt_adc_resolution: 0x%1X" % ina219.shunt_adc_resolution) print(" mode: 0x%1X" % ina219.mode) print(" conversion ready bit: 0x%1X" % ina219.conversion_ready) print("") """ dataDF = pd.DataFrame(columns=['mA','V','time']) #testTime = float(sys.argv[1]) testTime = 600 #clear sample lists #testResults = [] elapsedTime = time.time() startTime = time.time() #run each test for X seconds while elapsedTime - startTime < testTime : if ina219.conversion_ready == 1: bus_voltage = ina219.bus_voltage # voltage on V- (load side) #shunt_voltage = ina219.shunt_voltage # voltage between V+ and V- across the shunt current = ina219.current # current in mA dataDF = dataDF.append({'mA' : current , 'V' : bus_voltage, 'time': time.time()},ignore_index=True) #else: #print(" conversion ready bit: 0x%1X" % ina219.conversion_ready) elapsedTime = time.time() print("ina219: Test time: {}".format(elapsedTime - startTime)) #divide the amount of samples by 10 seconds to get the per second amount print("ina219: Samples per second: {}".format(len(dataDF)/testTime)) #print(testResults) #print(dataDF) #save data to file # check if the file already exists try: with open(fileName) as csvfile: print("This file already exists!") except: dataDF.to_csv(fileName, sep=',',index=False) print("ina219 done")
"""Sample code and test for adafruit_in219""" import time import board from adafruit_ina219 import ADCResolution, BusVoltageRange, INA219 i2c_bus = board.I2C() ina1 = INA219(i2c_bus,addr=0x40) ina2 = INA219(i2c_bus,addr=0x41) ina3 = INA219(i2c_bus,addr=0x42) print("ina219 test") ina1.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina1.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina1.bus_voltage_range = BusVoltageRange.RANGE_16V ina2.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina2.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina2.bus_voltage_range = BusVoltageRange.RANGE_16V ina3.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina3.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina3.bus_voltage_range = BusVoltageRange.RANGE_16V # measure and display loop while True: bus_voltage1 = ina1.bus_voltage # voltage on V- (load side)
"""Sample code and test for adafruit_in219""" import time import board from adafruit_ina219 import ADCResolution, BusVoltageRange, INA219 i2c_bus = board.I2C() ina219 = INA219(i2c_bus, 0x41) ina219.set_calibration_16V_5A() print("ina219 test") # display some of the advanced field (just to test) print("Config register:") print(" bus_voltage_range: 0x%1X" % ina219.bus_voltage_range) print(" gain: 0x%1X" % ina219.gain) print(" bus_adc_resolution: 0x%1X" % ina219.bus_adc_resolution) print(" shunt_adc_resolution: 0x%1X" % ina219.shunt_adc_resolution) print(" mode: 0x%1X" % ina219.mode) print("") # optional : change configuration to use 32 samples averaging for both bus voltage and shunt voltage #ina219.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S #ina219.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S # optional : change voltage range to 16V #ina219.bus_voltage_range = BusVoltageRange.RANGE_16V # measure and display loop while True: bus_voltage = ina219.bus_voltage # voltage on V- (load side)
import busio from robohat_mpu9250.mpu9250 import MPU9250 from robohat_mpu9250.mpu6500 import MPU6500 from robohat_mpu9250.ak8963 import AK8963 from adafruit_ina219 import INA219 from time import sleep i2c = busio.I2C(board.SCL, board.SDA) mpu = MPU6500(i2c, address=0x69) ak = AK8963(i2c) sensor_mpuak = MPU9250(mpu, ak) ina219 = INA219(i2c, 0x41) serial = 1 delay = 0.1 capability = "serial,gyro,accel,magnetic,temperature,nmea,vbus,vshunt,current" print("MM1 cpy JSON Agent (PoC)") json_sot = "{" json_eot = "}" while True: # Fake data for json testing LON = random.uniform(1, 180) LAT = random.uniform(1, 180)
import board from adafruit_ina219 import ADCResolution, BusVoltageRange, INA219 # SW-420 accelerometer libraries import busio import adafruit_adxl34x # import json libraries import json # time libraries from datetime import datetime import time i2c_bus = board.I2C() ina219 = INA219(i2c_bus) print("ina219 test") # optional : change configuration to use 32 samples averaging for both bus voltage and shunt voltage ina219.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina219.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S # optional : change voltage range to 16V ina219.bus_voltage_range = BusVoltageRange.RANGE_16V # get accelerometer data i2c = busio.I2C(board.SCL, board.SDA) accelerometer = adafruit_adxl34x.ADXL345(i2c) # reads all sensors values def read_all_sensors():
sleep(1) i2c_bus.writeto(0x72, " V1.0") sleep(1) i2c_bus.writeto(0x72, bytes([0x7C])) sleep(1) i2c_bus.writeto(0x72, bytes([0x2B])) sleep(1) i2c_bus.writeto(0x72, bytes([0x00])) sleep(1) i2c_bus.writeto(0x72, bytes([0xFF])) sleep(1) i2c_bus.writeto(0x72, bytes([0x00])) sleep(1) i2c_bus.unlock() ina219 = INA219(i2c_bus, 0x40) # Accessory Supply ina219_1 = INA219(i2c_bus, 0X41) # Street Light Supply range = ina219.bus_voltage_range range = ina219_1.bus_voltage_range # optional : change configuration to use 32 samples averaging for both bus voltage and shunt voltage ina219.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina219.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina219_1.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina219_1.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S # optional : change voltage range to 16V ina219.bus_voltage_range = BusVoltageRange.RANGE_16V ina219_1.bus_voltage_range = BusVoltageRange.RANGE_16V