def _write_register(self, register_id, value): write = smbus2.i2c_msg.write(self._i2c_addr, [register_id, value]) i2c_lock_obj = i2c_lock.i2c_get_lock() with i2c_lock_obj: with smbus2.SMBusWrapper(self._i2c_instance_num) as bus: bus.i2c_rdwr(write)
def __init__(self, address, args): self.log = Log() assert address in self.valid_addresses self.address = address self.last_update = datetime.datetime.min with smbus2.SMBusWrapper(1) as bus: self.basic_setup(bus, power_on=False, conv_rate=4)
def readNumber(): #this is another way to read from I2C using smbus2 with smbus2.SMBusWrapper(1) as bus: #reads a byte from given address, offset 0 #not sure what offset means, but will look into it number = bus.read_byte_data(address, 0) return int(number)
def set_mode(mode: str, bus_number=None): """Set the mode of the graphics card to the given mode.""" # Find the bus number if it's not found. if not bus_number: bus_number = discover_nvidia_bus() raw_mode = MODE_MAP[mode] with smbus2.SMBusWrapper(bus_number) as bus: bus.write_byte_data(RGB_CHIP_ADDRESS, MODE_DATA_ADDRESS, raw_mode)
def _read_register(self, register_id) -> int: write = smbus2.i2c_msg.write(self._i2c_addr, [register_id]) read = smbus2.i2c_msg.read(self._i2c_addr, 1) i2c_lock_obj = i2c_lock.i2c_get_lock() with i2c_lock_obj: with smbus2.SMBusWrapper(self._i2c_instance_num) as bus: bus.i2c_rdwr(write, read) return list(read)[0]
def get_mode(bus_number=None): """Get the current mode of the graphics card.""" # Find the bus number if it's not found. if not bus_number: bus_number = discover_nvidia_bus() with smbus2.SMBusWrapper(bus_number) as bus: raw_mode = bus.read_byte_data(RGB_CHIP_ADDRESS, MODE_DATA_ADDRESS) for mode, mode_mapped in MODE_MAP.items(): if raw_mode == mode_mapped: return mode
def get_color(bus_number=None): """Get the current RGB value of the graphics card.""" # Find the bus number if it's not found. if not bus_number: bus_number = discover_nvidia_bus() with smbus2.SMBusWrapper(bus_number) as bus: red = bus.read_byte_data(RGB_CHIP_ADDRESS, RED_DATA_ADDRESS) green = bus.read_byte_data(RGB_CHIP_ADDRESS, GREEN_DATA_ADDRESS) blue = bus.read_byte_data(RGB_CHIP_ADDRESS, BLUE_DATA_ADDRESS) return (red << 16) + (green << 8) + blue
def set_color(rgb: int, bus_number=None): """Set the rgb of the graphics card to the given rgb value.""" # Mask and shift the rgb value to get the individual colors. red = (rgb & 0xff0000) >> 16 green = (rgb & 0x00ff00) >> 8 blue = rgb & 0x0000ff # Find the bus number if it's not found. if not bus_number: bus_number = discover_nvidia_bus() with smbus2.SMBusWrapper(bus_number) as bus: bus.write_byte_data(RGB_CHIP_ADDRESS, RED_DATA_ADDRESS, red) bus.write_byte_data(RGB_CHIP_ADDRESS, GREEN_DATA_ADDRESS, green) bus.write_byte_data(RGB_CHIP_ADDRESS, BLUE_DATA_ADDRESS, blue)
def _read_acc_data(self) -> acc.AccData: write = smbus2.i2c_msg.write(self._i2c_addr, [ACC_REG_ID.OUT_X_L]) read = smbus2.i2c_msg.read(self._i2c_addr, 6) i2c_lock_obj = i2c_lock.i2c_get_lock() with i2c_lock_obj: with smbus2.SMBusWrapper(self._i2c_instance_num) as bus: bus.i2c_rdwr(write, read) raw_data = list(read) return acc.AccData( self._raw_data_to_mg(raw_data[0] | (raw_data[1] << 8)), self._raw_data_to_mg(raw_data[2] | (raw_data[3] << 8)), self._raw_data_to_mg(raw_data[4] | (raw_data[5] << 8)))
async def update(self): t_start = time.time() import random self.log.debug(f"Updating TMP102 sensor 0x{self.address:02x}") with smbus2.SMBusWrapper(1) as bus: # This is really a config thing? Maybe? bus.write_byte_data(self.address, 0, 0) self._temperature = bus.read_i2c_block_data(self.address, 0, 2) self._temperature = ( self._temperature[0] << 8) + self._temperature[1] self._temperature >>= 4 self.last_update = datetime.datetime.now() self.log.debug( f"Updated TMP102 sensor 0x{self.address:02x}, took {(time.time()-t_start)*1e3:.3f} ms" ) self.log.debug(f"Temperature was {self.temperature:.1f} C")
async def update(self): t_start = time.time() self.log.debug(f"Updating Si7021 sensor 0x{self.address:02x}") with smbus2.SMBusWrapper(1) as bus: h_list = [] for i in range(5): h_list.append(await self._measure_humidity(bus, 50)) h_list = sorted(h_list) self._humidity = h_list[2] measured_temperature = await self._measure_temperature(bus, 50) # Handle boot loop! if not hasattr(self, "_temperature"): self._temperature = measured_temperature # Check the slope of the temperature for sudden changes delta_t_update = (datetime.datetime.now() - self.last_update).total_seconds() / 60 t_slope = self._conv_temp(measured_temperature) - self._conv_temp( self._temperature) / delta_t_update self.log.debug(f"Slope measured to be {t_slope:.3f} C/min") if abs(t_slope) > 1: # Slope exceeded 1deg/minute! self.log.warning( f"Saw excessive slope in temperature. Slope was {t_slope:.3f} C/min. Taking 5 measures and using the median." ) t_list = [] for i in range(5): t_list.append(await self._measure_temperature(bus, 50)) t_list = sorted(t_list) measured_temperature = t_list[2] self._temperature = measured_temperature self.last_update = datetime.datetime.now() self.log.debug( f"Updated Si7021 sensor 0x{self.address:02x}, took {(time.time()-t_start)*1e3:.3f} ms" ) self.log.debug( f"Temperature was {self.temperature:.1f} C (0x{self._temperature:04X}) and humidity was {self.humidity:.1f}% (0x{self._humidity:04X})" )
async def update(self): t_start = time.time() import random self.log.debug(f"Updating TMP106 sensor 0x{self.address:02x}") # Fake write to sensor await asyncio.sleep(0.8) self._uva = random.randint(0,0xffff) self._uvb = random.randint(0,0xffff) self._uvcomp1 = random.randint(0,0xffff) self._uvcomp2 = random.randint(0,0xffff) self.last_update = datetime.datetime.now() self.log.debug(f"Updated TMP106 sensor 0x{self.address:02x}, took {(time.time()-t_start)/1e3:.3f} ms") return with smbus2.SMBusWrapper(1) as bus: bus.write_byte(self.address, 0, self.POINTER_OBJECT) self._temperature = bus.read_i2c_block_data(self.address, 0, 2) bus.write_byte(self.address, 0, self.POINTER_AMBIENMT) self._temperature_a = bus.read_i2c_block_data(self.address, 0, 2)
def run(self): print("Starting " + self.name) time.sleep(2) while (1): """ Read 7 bytes from ATMega (2 bytes FuelCellCurrent, 2 bytes FuelCellVoltage, 2 bytes BatteryVoltage, 1 byte ATMega status) Address: 8 Offset: 0 of Bytes: 7 """ try: with smbus2.SMBusWrapper(1) as bus: ATMegaData = bus.read_i2c_block_data(8, 0, 8) except: print("Read Error") # data = bus.read_byte_data(8, 0) # block = bus.read_i2c_block_data(8, 0, 4) # block2 = struct.unpack("<HHHH",block) # print(data) # print('\n') # for received in block: # ATMegaData[1] = received # ATMegaData = struct.unpack('l', ''.join([chr(i) for i in block[:4]))[0] # ATMegaData[0] = bus.read_byte(8) # ATMegaData[1] = bus.read_byte(8,1) time.sleep(0.5) """ Write 3 bytes to ATMega (1 byte FanSpeed, 1 byte Target Current, 1 byte Pi Status) Address: 8 Offset: 0 # of bytes: 3 """ try: with smbus2.SMBusWrapper(1) as bus: bus.write_i2c_block_data(8, 42, [PiData[0], PiData[1], PiData[2]]) PiData[0] += 1 PiData[1] += 2 PiData[2] -= 1 except: print("Write Error") # value = 3 # bus.write_word_data(8, 0, value) time.sleep(0.5) print("ATMega Data: ") for i in ATMegaData: print(i) print(ATMegaData) print("\nPi Data: ") for i in PiData: print(i)
def writeRequest(request): #this is another way to write to bus using smbus2 with smbus2.SMBusWrapper(1) as bus: # Write a byte to address, offset 0 #not sure what offset means, but will look into it bus.write_byte_data(address, 0, request)
ATMegaData = [0, 1, 3, 50] #, 80, 0, 0, 0]) PiData = [3, 10, 120] time.sleep(2) while (1): """ Read 7 bytes from ATMega (2 bytes FuelCellCurrent, 2 bytes FuelCellVoltage, 2 bytes BatteryVoltage, 1 byte ATMega status) Address: 8 Offset: 0 of Bytes: 7 """ with smbus2.SMBusWrapper(1) as bus: ATMegaData = bus.read_i2c_block_data(8, 0, 4) # data = bus.read_byte_data(8, 0) # block = bus.read_i2c_block_data(8, 0, 4) # block2 = struct.unpack("<HHHH",block) # print(data) # print('\n') # for received in block: # ATMegaData[1] = received # ATMegaData = struct.unpack('l', ''.join([chr(i) for i in block[:4]))[0] # ATMegaData[0] = bus.read_byte(8) # ATMegaData[1] = bus.read_byte(8,1)
def run(self): print("Starting " + self.name) # Give thread time to initialize time.sleep(2) PiStatusOptions = { 0: "Boot up", 3: "Normal Operation", 4: "Load Overtemp", 5: "Controller Overtemp", 6: "Load Overcurrent", 7: "Fuel Cell Voltage too High", 8: "Fuel Cell Voltage too Low", 9: "Battery Low", 10: "Air Starve Relay Active", 15: "Lost Communication" } while (1): """ Read 7 bytes from ATMega (2 bytes FuelCellCurrent, 2 bytes FuelCellVoltage, 2 bytes BatteryVoltage, 1 byte ATMega status) Address: 8 Offset: 0 of Bytes: 7 """ try: with smbus2.SMBusWrapper(1) as bus: ATMegaData = bus.read_i2c_block_data(8, 0, 8) readErrCounter = 0 except: #print("Read Error") readErrCounter += 1 time.sleep(0.5) """ Write 3 bytes to ATMega (1 byte FanSpeed, 1 byte Target Current, 1 byte Pi Status) Address: 8 Offset: 0 # of bytes: 3 """ try: with smbus2.SMBusWrapper(1) as bus: bus.write_i2c_block_data(8, 42, [PiData[0], PiData[1], PiData[2]]) PiData[0] += 1 PiData[1] += 2 PiData[2] += 1 if PiData[2] > 15: PiData[2] = 0 writeErrCounter = 0 except: #print("Write Error") writeErrCounter += 1 time.sleep(0.5) print("\n\nATMega Data: ") print(ATMegaData) print("Pi Data: ") print(PiData) print("Read Error Counter: % 2d Write Error Counter: % 2d" % (readErrCounter, writeErrCounter)) print("Status: % s" % (PiStatusOptions.get(PiData[2], 'INVALID STATE')))
async def update(self): a1 = 1.75e-3 a2 = -1.678e-5 tRef = 298.15 #K b0 = -2.94e-5 b1 = -5.7e-7 b2 = 4.63e-9 c2 = 13.4 t_start = time.time() self.log.debug(f"Updating TMP106 sensor 0x{self.address:02x}") with smbus2.SMBusWrapper(1) as bus: await self.power_crtl(bus, True) while 1: config = await self.get_config_reg(bus) if config & 0x0080: break self.log.debug("Waiting on converstion...") await asyncio.sleep(1) self.log.debug(f"Config: {config:X}") data = [] for i in [self.POINTER_OBJECT, self.POINTER_AMBIENMT]: write = smbus2.i2c_msg.write(self.address, [i]) read = smbus2.i2c_msg.read(self.address, 2) bus.i2c_rdwr(write, read) read = list(read) data.append((read[0] << 8) + read[1]) vObj = data[0] if vObj & 0x8000: vObj = (vObj - (1 << 16)) vObj = vObj / 2**15 * 5.12e-3 tDie = data[1] if tDie & 0x8000: tDie = (tDie - (1 << 16)) tDie >>= 2 tDie = tDie * .03125 tDie += 273.15 # config = data[2] self.log.debug(f"Config: {config:X}") self.log.debug(f" vObj: {vObj:8.3e} (0x{data[0]:04X})") self.log.debug( f" tDie: {tDie-273.15:8.3f}/{tDie:8.3f} (0x{data[1]:04X})") S0 = 1.5e-14 S = S0 * (1 + a1 * (tDie - tRef) + a2 * (tDie - tRef)**2) self.log.debug(f" d-r: {(tDie - tRef):8.3f}") self.log.debug(f" S: {S:8.3f}") Vos = b0 + b1 * (tDie - tRef) + b2 * (tDie - tRef)**2 self.log.debug(f" Vos: {Vos:8.3f}") fVojb = (vObj - Vos) + c2 * (vObj - Vos)**2 self.log.debug(f" fVojb: {fVojb:8.3f}") Tobj = numpy.sqrt(numpy.sqrt(tDie**4 + (fVojb / S))) adjust = 78 self.log.debug(f" Tobj: {Tobj-adjust:8.3f}") self.log.debug(f" Tobj: {Tobj-273.15-adjust:8.3f}") self.log.debug(f" error: {37-(Tobj-273.15-adjust):8.3f}") cali = fVojb / (1 + a1 * (tDie - tRef) + a2 * (tDie - tRef)**2) self.log.debug(f" cali: {cali}") self.log.debug(f"tDie^4: {tDie**4}") await self.power_crtl(bus, False) self.log.debug( f"Updated TMP106 sensor 0x{self.address:02x}, took {(time.time()-t_start)*1e3:.3f} ms" )
""" Returns a tuple with 2 integers (upper,lower) matching the according bytes The AMG88 usually uses 2 byte to store 12bit values. """ upper = value >> 9 lower = 0b011111111 & value return (upper, lower) def maprange(a, b, s): """remap values linear to a new range""" (a1, a2), (b1, b2) = a, b return b1 + ((s - a1) * (b2 - b1) / (a2 - a1)) if __name__ == '__main__': from time import sleep from pprint import pprint with smbus.SMBusWrapper(1) as bus: print("Init GridEye88xx") ge = GridEye(i2c_bus=bus) print("Save Sensor Data As heatmap.png") image = ge.get_sensor_data("GRAYIMAGE")[0] image.save("heatmap.png", "PNG") while True: print("Thermistor Temperature is: %fC" % ge.get_thermistor_temp()) print("Current Sensor Data:") pprint(ge.get_sensor_data()[0]) sleep(0.5)