def humidity_temp_set(self): """Sends command to read humidity. Then reads humidity with a pause between the two bytes. Temperature then reads as a temp reading is taken by the sensor for compensation for humidity reading """ # Reading values for humidity with SMBusWrapper(1) as bus: # Write command to start reading humidity self.humidity_write = i2c_msg.write(self.address, [self.humidityCommand]) # Read command to actually read humidity self.humidity_read = i2c_msg.read(self.address, 2) # Execute with a pause bus.i2c_rdwr(self.humidity_write) time.sleep(0.25) bus.i2c_rdwr(self.humidity_read) #Reading values for temperature with SMBusWrapper(1) as bus: # Write command to start reading temperature self.temp_write = i2c_msg.write(self.address, [self.tempCommand]) # Read command to actually read temperature self.temp_read = i2c_msg.read(self.address, 2) # Execute bus.i2c_rdwr(self.temp_write) bus.i2c_rdwr(self.temp_read)
def test_read(self): res = [] res2 = [] res3 = [] # Read bytes with SMBusWrapper(1) as bus: for k in range(2): x = bus.read_byte_data(80, k) res.append(x) self.assertEqual(len(res), 2, msg="Result array of incorrect length.") # Read word with SMBusWrapper(1) as bus: x = bus.read_word_data(80, 0) res2.append(x & 255) res2.append(x / 256) self.assertEqual(len(res2), 2, msg="Result array of incorrect length.") self.assertListEqual(res, res2, msg="Byte and word reads differ") # Read block of N bytes n = 2 with SMBusWrapper(1) as bus: x = bus.read_i2c_block_data(80, 0, n) res3.extend(x) self.assertEqual(len(res3), n, msg="Result array of incorrect length.") self.assertListEqual(res, res3, msg="Byte and block reads differ")
def initI2C(): while (1): """ Read 7 bytes from ATMega (2 bytes Fu elCellCurrent, 2 bytes FuelCellVoltage, 2 bytes BatteryVoltage, 1 byte ATMega status) Offset: 0 # of Bytes: 7 """ with SMBusWrapper(1) as bus: ATMegaData = bus.read_i2c_block_data(ATMEGA_ADDRESS, 0, 7) time.sleep(0.5) print("ATMega Data: ") for i in ATMegaData: print(i) """ Write 3 bytes to ATMega (1 byte FanSpeed, 1 byte Target Current, 1 byte Pi Status) Offset: 0 # of bytes: 3 """ with SMBusWrapper(1) as bus: bus.write_i2c_block_data(ATMEGA_ADDRESS, 0, PiData) time.sleep(0.5) print("\nPi Data: ") for i in PiData: print(i)
def updateValues(self): with SMBusWrapper(1) as bus: #put sensor into signle shot mode with no clock stretching try: bus.write_word_data(self.address, 0x24, 0x00) except Exception as e: print("Error writting to SHT31 sensor: ", e) time.sleep(.012) #experimentally found rest time before reading values with SMBusWrapper(1) as bus: #read 16 bit temp and humidity with 2 CRC bytes (6 bytes) numOfTries = 0 while (numOfTries < 4): try: dataBlock = bus.read_i2c_block_data(self.address, 0, 6) self.readError = False break except Exception as e: print("SHT31-D read error: ", e) self.readError = True numOfTries += 1 time.sleep(.001) #print "Retrying..." if (not self.readError): self.decodeMessage(dataBlock) else: self.decodeMessage([0, 0, 0, 0, 0, 0])
def update_pixel_temperature_matrix(self): ''' Updates the 8*8 pixel temperature matrix containig the the pixels temperature in Celsius\n Structure:\n [ [00, 01, 02, 03, 04, 05, 06, 07],\n [08, 09, 10, 11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20, 21, 22, 23],\n [24, 25, 26, 27, 28, 29, 30, 31],\n [32, 33, 34, 35, 36, 37, 38, 39],\n [40, 41, 42, 43, 44, 45, 46, 47],\n [48, 49, 50, 51, 52, 53, 54, 55],\n [56, 57, 58, 59, 60, 61, 62, 63]\n ] ''' def to_celsius_temperature(lsb_byte, msb_byte): unified_no_sign = ((msb_byte & 7) << 8) | lsb_byte value = 0 if (msb_byte & 8) == 0 else -(1 << 11) value += unified_no_sign return value / 4 with SMBusWrapper(self._i2c_bus) as bus: for i, reg_addr in enumerate( range(_FIRST_PIXEL_REG_ADDR, _LAST_PIXEL_REG_ADDR, 2)): lsb = bus.read_byte_data(self._i2c_address, reg_addr) msb = bus.read_byte_data(self._i2c_address, reg_addr + 1) self._last_pixel_data[i // 8][i % 8] = to_celsius_temperature( lsb, msb)
def readData(): with SMBusWrapper(1) as bus: try: block = bus.read_i2c_block_data(address, 0, 8) except: print("I2C ERROR") return for b in block: if b & 0xFF == 0xFF: return data = [] data.append(block[0] << 8 | block[1]) data.append(block[2] << 8 | block[3]) data.append(block[4] << 8 | block[5]) data.append(block[6] << 8 | block[7]) print(data) # if data[0] < 600: # send_motor_command(2) # elif data[1] < 600: # send_motor_command(1) # else: # send_motor_command(0) for i in range(4): motor_triggers[i] = data[i] < 600 send_motor_command()
def __init__(self): # reset device with SMBusWrapper(1) as bus: bus.write_byte(MS8607.TEMP_ADDR, 0x1e) bus.write_byte(MS8607.RH_ADDR, 0xfe) # set factory calibration data cal_dat self.read_factory_calibration_data()
def read_response(self): response = -1 self.dprint('LOCKED... for read_request') with SMBusWrapper(1) as bus: response = bus.read_i2c_block_data(self.i2c_addr, 0, 4) bus.close() return response
def read_gauge(self): try: with SMBusWrapper(1) as bus: voltage_readings = bus.read_i2c_block_data(self.address, self.voltage_reg, 2) accum_charge_readings = bus.read_i2c_block_data(self.address, self.accum_charge_reg, 2) current_readings = bus.read_i2c_block_data(self.address, self.current_reg, 2) temperature_readings = bus.read_i2c_block_data(self.address, self.temperature_reg, 2) except Exception as e: print('Error: {}'.format(e)) sys.exit() voltage = voltage_readings[0] << 8 | voltage_readings[1] accum_charge = accum_charge_readings[0] << 8 | accum_charge_readings[1] current = current_readings[0] << 8 | current_readings[1] temperature = temperature_readings[0] << 8 | temperature_readings[1] voltage = self.code_to_voltage(voltage) accum_charge = self.code_to_mAh(accum_charge) current = self.code_to_current(current) temperature = self.code_to_celcius(temperature) battery = Battery() battery.voltage.data = voltage battery.charge.data = accum_charge battery.current.data = current battery.temperature.data = temperature battery.percent_full.data = min(100, accum_charge/self.max_cap) # Turn off the motors if current too high if current < self.current_th_hi: d_msg = Drive() d_msg.direction.data = 0 d_msg.speed.data = 0 self.motor_pub.publish(d_msg) self.battery_pub.publish(battery)
def write(dev_add, start_add, my_list): data = [] with SMBusWrapper(1) as bus: bus.write_byte_data(address, 0, 0) for start_addr in range(len(my_list)): if start_addr % 32 == 0 and start_addr > 0: lsbyte = start_addr & 0x00FF msbyte = start_addr >> 8 #print(data) #import pdb; pdb.set_trace() writestring = [lsbyte] + data[0:len(data) - 1] #print(writestring, len(writestring)) bus.write_i2c_block_data(address, msbyte, writestring) time.sleep(0.1) current = (start_addr - 1) + 32 clsbyte = current & 0x00FF cmsbyte = current >> 8 #print(current, clsbyte, cmsbyte, chr(data[len(data)-1]) ) writestring = [clsbyte] + [data[len(data) - 1]] #print(writestring, len(writestring)) #import pdb; pdb.set_trace() bus.write_i2c_block_data(address, cmsbyte, writestring) time.sleep(0.1) data = [] data.append(my_list[start_addr])
def change_led_state(self, led): pwm = self.read(led) with SMBusWrapper(1) as bus: if pwm == constant.PWM_LOW: bus.write_byte_data(constant.DEVICE_ADDR, led, constant.PWM_HIGH) else: bus.write_byte_data(constant.DEVICE_ADDR, led, constant.PWM_LOW)
def i2crw(addr, cmd, dataNum): with SMBusWrapper(1) as bus: msg = i2c_msg.write(addr, cmd) data = i2c_msg.read(addr, dataNum) bus.i2c_rdwr(msg, data) data = list(data) return data
def main(): host = 'localhost' port = 8086 dbname = 'sensor' client = InfluxDBClient(host=host, port=port, database=dbname) with SMBusWrapper(1) as bus: sgp = Sgp30( bus, baseline_filename="/tmp/mySGP30_baseline" ) #things thing with the baselinefile is dumb and will be changed in the future sgp.i2c_geral_call( ) #WARNING: Will reset any device on teh i2cbus that listens for general call sgp.init_sgp() while True: time.sleep(20) bundle = sgp.read_measurements() #print("CO2: {} TVOC: {}".format(bundle.data[0], bundle.data[1])) current_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') json_body = [{ "measurement": "svm30", "tags": { "location": "office" }, "time": current_time, "fields": { "hum": get_hum(), "temp": get_temp(), "co2": bundle.data[0], "tvoc": bundle.data[1] } }] print("Write points: {0}".format(json_body)) client.write_points(json_body)
def readCapacity(self): with SMBusWrapper(self.i2c_bus) as bus: read = bus.read_byte_data(self.address, 4) swapped = struct.unpack("<H", struct.pack(">H", read))[0] capacity = swapped / 256 return capacity
def readVoltage(self): with SMBusWrapper(self.i2c_bus) as bus: read = bus.read_byte_data(self.address, 2) swapped = struct.unpack("<H", struct.pack(">H", read))[0] voltage = swapped * 78.125 / 1000000 return voltage
def setI2CDisplay(): #bus = SMBus(1) #open i2c bus 1 #create buffer used in setting up i2c display data = [0] * 16; #buffer of 17 with SMBusWrapper(1) as bus: # turn on oscillator on_osci = (0x2 << 4) | 0x01; #set upper 4 bit 0x02 and lower 4 bits 0x01 #data[0] = on_osci bus.write_byte_data(SLAVE_ADDRESS,on_osci,0) #turn on Display, No Blink cmd = (0x08 << 4) | 0x01; #data[0] = cmd; bus.write_byte_data(SLAVE_ADDRESS,cmd,0); #set brightness cmd = (0x0E << 4) | 0x0E # set brightness by adjusting the duty cycle (15/16) #data[0] = cmd; bus.write_byte_data(SLAVE_ADDRESS,cmd,0); #data[0] = 0x79; #data[2] = 0x39; #data[3] = 0x00; #data[6] = 0x79; #data[8] = 0x79 bus.write_i2c_block_data(SLAVE_ADDRESS,0,data);
def loadCalibration(self): with SMBusWrapper(1) as bus: self.cal_REGISTER_DIG_T1 = bus.read_word_data( self.address, BMP280_REGISTER_DIG_T1) # UINT16 self.cal_REGISTER_DIG_T2 = bus.read_word_data( self.address, BMP280_REGISTER_DIG_T2) # INT16 self.cal_REGISTER_DIG_T3 = bus.read_word_data( self.address, BMP280_REGISTER_DIG_T3) # INT16 self.cal_REGISTER_DIG_P1 = bus.read_word_data( self.address, BMP280_REGISTER_DIG_P1) # UINT16 self.cal_REGISTER_DIG_P2 = bus.read_word_data( self.address, BMP280_REGISTER_DIG_P2) # INT16 self.cal_REGISTER_DIG_P3 = bus.read_word_data( self.address, BMP280_REGISTER_DIG_P3) # INT16 self.cal_REGISTER_DIG_P4 = bus.read_word_data( self.address, BMP280_REGISTER_DIG_P4) # INT16 self.cal_REGISTER_DIG_P5 = bus.read_word_data( self.address, BMP280_REGISTER_DIG_P5) # INT16 self.cal_REGISTER_DIG_P6 = bus.read_word_data( self.address, BMP280_REGISTER_DIG_P6) # INT16 self.cal_REGISTER_DIG_P7 = bus.read_word_data( self.address, BMP280_REGISTER_DIG_P7) # INT16 self.cal_REGISTER_DIG_P8 = bus.read_word_data( self.address, BMP280_REGISTER_DIG_P8) # INT16 self.cal_REGISTER_DIG_P9 = bus.read_word_data( self.address, BMP280_REGISTER_DIG_P9) # INT16
def factory_reset(active=False): '''Resets ALL memory, use with caution ''' if active == True: #Safety, user must trigger #print("Reseting EEPROM: ETA 40.95 seconds") with SMBusWrapper(1) as bus: bus.write_byte_data(address, 0, 0) for start_addr in range(n_bytes): if start_addr % 32 == 0: current = 31 + start_addr clsbyte = current & 0x00FF cmsbyte = current >> 8 lsbyte = start_addr & 0x00FF msbyte = start_addr >> 8 writestring = [lsbyte] + [255] * 31 bus.write_i2c_block_data(address, msbyte, writestring) time.sleep(0.1) bus.write_i2c_block_data(address, cmsbyte, [clsbyte, 255]) time.sleep(0.1) #print('---0x{:4x} {}'.format(start_addr, start_addr)) #print('lo 0x{:4x} {}'.format(lsbyte, lsbyte)) #print('hi 0x{:4x} {}'.format(msbyte, msbyte)) else: print("factory activity status set to false, no changes!")
def processQueue(arg1, arg2): global message_queue while True: if len(message_queue) > 0: print(len(message_queue)) try: with SMBusWrapper(1) as bus: arr = message_queue[0][0] addr = message_queue[0][1] bus.write_i2c_block_data(addr, 0, arr) del message_queue[0] do_log(str(addr) + ":" + str(arr)) #time.sleep(.001) except IOError as err: del message_queue[0] do_log(str(err), syslog.LOG_ERR) except Error as err: del message_queue[0] do_log(str(err), syslog.LOG_ERR) except Exception as e: del message_queue[0] do_log(str(e), syslog.LOG_ERR) except: del message_queue[0] do_log("Error en el processQueue", syslog.LOG_ERR) time.sleep(.02) '''
def _get_command(self, cmd): self.busy = True bytes_to_read = 4 command = pack('>B', cmd) #if True: try: with SMBusWrapper(1) as bus: write = i2c_msg.write(self.address, command) # Have to get rid of the last on...smbus2 messes with the last word, not am sure why. read = i2c_msg.read(self.address, bytes_to_read + 1) bus.i2c_rdwr(write, read) data = list(read) data.pop() data = bytes(data) result = unpack('>I', data)[0] except: self.read_scale_timer.error() print('Command Read: Scale ' + str(self.scale_number) + ' command ' + str(cmd) + ' timed out.') result = False self.busy = False return result
def write(self, data): """ Raw write data without register """ with SMBusWrapper(self.BUS, ) as bus: msg = i2c_msg.write(self.ADDRESS, data) bus.i2c_rdwr(msg)
def _send_command(self, cmd, value): self.busy = True bytes_to_read = 1 command = [pack('>B', cmd), pack('>I', value)] try: with SMBusWrapper(1) as bus: write = i2c_msg.write(self.address, command) # Have to get rid of the last byte on...smbus2 messes with the last word, not am sure why. read = i2c_msg.read(self.address, bytes_to_read + 1) bus.i2c_rdwr(write, read) data = list(read) data.pop() data = bytes(data) result = unpack('>I', data)[0] if (result == 10): print('Command Read: ' + str(cmd) + ' successful.') else: print('Command Read: ' + str(cmd) + ' failed.') except: self.read_scale_timer.error() print('Command Read: Scale ' + str(self.scale_number) + ' command ' + str(cmd) + ' timed out.') self.busy = False
def read_factory_calibration_data(self): # read factory calibration data from PROM with SMBusWrapper(1) as bus: for name, addr in zip(MS8607.CAL_NAME, MS8607.CAL_ADDR): dats = bus.read_i2c_block_data(MS8607.TEMP_ADDR, addr, 2) MS8607.cal_dat[name] = (dats[0] << 8) + dats[1] return MS8607.cal_dat
def getvalue(): with SMBusWrapper(1) as bus: sgp = Sgp30(bus, baseline_filename="/tmp/mySGP30_baseline") # sgp.i2c_geral_call() #WARNING: Will reset any device on teh i2cbus that listens for general call sgp.init_sgp() value = sgp.read_measurements() return value
def factory_reset(active=False): '''Resets ALL memory, use with caution ''' if active == True: #Safety, user must trigger #print("Reseting EEPROM: ETA 40.95 seconds") with SMBusWrapper(i2c_bus_id) as bus: bus.write_byte_data(spd_page_selector_addr, 0, 0) for byte in range(n_bytes): if byte % 32 == 0: current = 31 + byte clsbyte = current & 0x00FF cmsbyte = current >> 8 lsbyte = byte & 0x00FF msbyte = byte >> 8 writestring = [lsbyte] + [255] * 31 bus.write_i2c_block_data(spd_base_addr, msbyte, writestring) time.sleep(0.1) bus.write_i2c_block_data(spd_base_addr, cmsbyte, [clsbyte, 255]) time.sleep(0.1) #print('---0x{:4x} {}'.format(byte, byte)) #print('lo 0x{:4x} {}'.format(lsbyte, lsbyte)) #print('hi 0x{:4x} {}'.format(msbyte, msbyte)) else: print("factory activity status set to false, no changes!")
def i2c_read_string(busnum, address, nbytes): """ Return character data read from I2C. """ buff = [] try: with SMBusWrapper(busnum) as bus: for i in range(nbytes + 2): time.sleep(I2C_READ_DELAY) c = bus.read_byte(address) buff.append(c) except IOError: log.debug('Error reading string. device: {:d}'.format(address)) raise I2CError() except: raise log.debug(buff) buff_checksum = buff[-2] << 8 | buff[-1] local_checksum = sum(buff[:-2]) if buff_checksum != local_checksum: log.error('Checksums do not match, buff: {}, local: {}'.format( buff_checksum, local_checksum)) raise ChecksumError() s = ''.join([chr(v) for v in buff[:-2]]) return s
def updateValues(self): with SMBusWrapper(1) as bus: # read 16 bit temp and humidity with 2 CRC bytes (6 bytes) numOfTries = 0 while (numOfTries < 4): try: # Read raw tempurature data msb = bus.read_byte_data(self.address, BMP280_REGISTER_TEMPDATA_MSB) lsb = bus.read_byte_data(self.address, BMP280_REGISTER_TEMPDATA_LSB) xlsb = bus.read_byte_data(self.address, BMP280_REGISTER_TEMPDATA_XLSB) self.rawTemp = ((msb << 8 | lsb) << 8 | xlsb) >> 4 # Read raw pressure data msb = bus.read_byte_data(self.address, BMP280_REGISTER_PRESSUREDATA_MSB) lsb = bus.read_byte_data(self.address, BMP280_REGISTER_PRESSUREDATA_LSB) xlsb = bus.read_byte_data(self.address, BMP280_REGISTER_PRESSUREDATA_XLSB) self.rawPressure = ((msb << 8 | lsb) << 8 | xlsb) >> 4 self.readError = False break except Exception as e: rospy.logerr("BMP280 read error: %s", e) self.readError = True numOfTries += 1 rospy.sleep(.001) # print "Retrying..." if (self.readError): self.rawTemp = 0 self.rawPressure = 0
def __init__(self, addr=0x77): self.address = addr # calibration values calibrationSuccess = False attempts = 0 self.tfine = 0 while (calibrationSuccess == False and attempts < 10): try: self.loadCalibration() with SMBusWrapper(1) as bus: try: # put sensor into normal mode - ultra high resolution bus.write_byte_data(self.address, BMP280_REGISTER_CONTROL, 0xFF) bus.write_byte_data(self.address, BMP280_REGISTER_CONFIG, 0x1C) except Exception as e: rospy.logerr("Error writting mode and settings to BMP280 sensor: %s", e) calibrationSuccess = True except Exception as e: attempts += 1 rospy.logerr("Error reading BMP280 calibration data: %s", e) rospy.sleep(0.25) if (attempts == 10): rospy.logerr("BMP280 failed program closing!") exit()
def factory_reset(self, active=False): '''Resets ALL memory, use with caution ''' if active == True: #Safety, user must trigger #print("Reseting EEPROM: ETA 40.95 seconds") with SMBusWrapper(1) as bus: bus.write_byte_data(address, 0, 0) #Starting Location for start_addr in range(n_bytes): #Erasing all bytes if start_addr % 32 == 0: #32 Bytes a block current = 31 + start_addr #Position of 32nd byte clsbyte = current & 0x00FF cmsbyte = current >> 8 lsbyte = start_addr & 0x00FF #position of 1st 31 bytes msbyte = start_addr >> 8 writestring = [ lsbyte ] + [255] * 31 #Start byte and erase bytes bus.write_i2c_block_data(address, msbyte, writestring) time.sleep(0.1) bus.write_i2c_block_data(address, cmsbyte, [clsbyte, 255]) time.sleep(0.1) else: print("factory activity status set to false, no changes!")
def sgp30_mainloop(sensor_id, mqttc, mqtt_topic): """ Main loop to run SGP30 sensor """ # pylint: disable=W0612,W0613 with SMBusWrapper(1) as bus: sgp = Sgp30( bus, baseline_filename="/tmp/mySGP30_baseline" ) #things thing with the baselinefile is dumb and will be changed in the future print("resetting all i2c devices") sgp.i2c_geral_call( ) #WARNING: Will reset any device on teh i2cbus that listens for general call print(sgp.read_features()) print(sgp.read_serial()) sgp.init_sgp() while True: sgp_measurements = sgp.read_measurements() co2 = measure_hash(sensor_id, int(sgp_measurements.data[0]), "co2") tvoc = measure_hash(sensor_id, int(sgp_measurements.data[1]), "voc") (rtn_value, mid) = mqttc.publish(mqtt_topic + "co2", co2, qos=0) (rtn_value, mid) = mqttc.publish(mqtt_topic + "tvoc", tvoc, qos=0) print("eCO2: " + str(sgp_measurements.data[0]) + " tVOC: " + str(sgp_measurements.data[1])) time.sleep(10 * 60)
def __init__(self, address, bus_number=1, auto_cleanup=True, force=False): SMBusWrapper.__init__(self, bus_number, auto_cleanup, force) self.bus = None self.address = address self.ddelay = 0.05 log.debug("delay after r/w : {}".format(self.ddelay))