def __get_eeprom(self, eeprom_address=0x50): # Two separate I2C transfers in case the buffer size is small q1 = [I2C.Message([0x00, 0x00]), I2C.Message([0x00]*4000, read=True)] q2 = [I2C.Message([0x0f, 0xa0]), I2C.Message([0x00]*4000, read=True)] self.i2c.transfer(eeprom_address, q1) self.i2c.transfer(eeprom_address, q2) return np.array(q1[1].data + q2[1].data)
def get_eeprom(self, eeprom_address=0x50): # Dua transfer I2C terpisah jika ukuran buffer kecil q1 = [I2C.Message([0x00, 0x00]), I2C.Message([0x00] * 4000, read=True)] q2 = [I2C.Message([0x0f, 0xa0]), I2C.Message([0x00] * 4000, read=True)] self.i2c.transfer(eeprom_address, q1) self.i2c.transfer(eeprom_address, q2) return np.array(q1[1].data + q2[1].data)
def read(self, first_address, count): dat_buffer = [] bytes_already_read = 0 while bytes_already_read != count: read_len = min(MAX_WPILIB_I2C_READ_BYTES, count - bytes_already_read) with self.mutex: try: # first transfer address and length we want to read register_address = first_address + bytes_already_read self.i2c.transfer( 0x32, [I2C.Message([register_address, read_len])]) # now read the data # NOTE: these two statements should theoretically be able to be combined into a single transaction, # but when I tried, it didn't work read_msg = I2C.Message(bytearray(read_len), read=True) self.i2c.transfer(0x32, [read_msg]) #print("Read %d bytes at register %d: %s" % (read_len, register_address, binascii.hexlify(read_msg.data))) if not read_msg.data: break dat_buffer.extend(read_msg.data) bytes_already_read = len(dat_buffer) except Exception: traceback.print_exc() break if bytes_already_read != count: raise IOError("Read error") return dat_buffer
def pmbus_read(dev_addr, reg_addr, n_bytes): i2c = I2C("/dev/i2c-0") write = I2C.Message([reg_addr]) read = I2C.Message([0x0] * n_bytes, read=True) i2c.transfer(dev_addr, [write, read]) i2c.close() return bytes(bytearray(read.data)).encode('hex')
def bootloader_enter(ser, address, rst_gpio, inverted): # send payload req = bytearray(REQ_ENTER) chunks = os.path.getsize(FILE) chunks = int(math.ceil(float(chunks) / BLOCK_SIZE)) print('Need to send %s chunks' % chunks) crc = get_crc() req.extend([chunks, crc, crc]) # I2c transaction with bootloader request and ACK nand respond # toggle reset via sysFS GPIO rst_gpio.write(inverted) sleep(0.5) rst_gpio.write(not inverted) sleep(0.01) snd = [I2C.Message(req)] rcv = [I2C.Message([0x00, 0x00], read=True)] ser.transfer(address, snd) sleep(0.01) # give some time to process the block ser.transfer(address, rcv) if bytearray(rcv[0].data) != bytearray(ACK): print("Bootloader NACK") sys.exit(1) return ser
def bmr458_mon(dev_addr, reg_addr): i2c = I2C("/dev/i2c-1") write = I2C.Message([reg_addr]) read = I2C.Message([0x0] * 2, read=True) i2c.transfer(dev_addr, [write, read]) i2c.close() return bytes(bytearray(read.data)).encode('hex')
def Reset(self): """Reset the Notecard.""" chunk_len = 0 while not self.lock(): pass try: while True: time.sleep(.001) reg = bytearray(2) reg[0] = 0 reg[1] = chunk_len readlen = chunk_len + 2 buf = bytearray(readlen) if use_periphery: msgs = [I2C.Message(reg), I2C.Message(buf, read=True)] self.i2c.transfer(self.addr, msgs) buf = msgs[1].data elif use_micropython: self.i2c.writeto(self.addr, reg, False) self.i2c.readfrom_into(self.addr, buf) else: self.i2c.writeto_then_readfrom(self.addr, reg, buf) available = buf[0] if available == 0: break chunk_len = min(available, self.max) finally: self.unlock() pass
def get_eeprom(self, eeprom_address=0x50): query = [ I2C.Message([0x00, 0x00]), I2C.Message([0x00] * 8000, read=True) ] self.i2c.transfer(eeprom_address, query) return np.array(query[1].data)
def run(i2c, time, steps, Filename): f = open(Filename + "_input.txt", "w+") time = float(time) volt = 0x0000 while (int(volt) < 26214): i2c.transfer( 0x11, [I2C.Message([0x3F, volt >> 8, volt & 0xFF00 >> 8], read=False)]) volt = volt + steps os.system( "cat /sys/bus/iio/devices/iio:device0/in_voltage8_vpvn_raw >>" + Filename + "_output.txt") f.write('%0.2f\n' % (float(volt))) f.flush() os.fsync(f.fileno()) sleep(time) if (int(volt) > 26214 - steps - 1): while (int(volt) > 0): volt = volt - steps i2c.transfer(0x11, [ I2C.Message([0x3F, volt >> 8, volt & 0xFF00 >> 8], read=False) ]) print('%.2f' % (float(volt))) os.system( "cat /sys/bus/iio/devices/iio:device0/in_voltage8_vpvn_raw >>" + Filename + "_output.txt") f.write('%0.2f\n' % (float(volt))) f.flush() os.fsync(f.fileno()) sleep(time)
def read_byte(self, address): msgs = [I2C.Message([address], read=False)] self.transfer(msgs) msgs = [I2C.Message([address], read=True)] ret_msg = self.transfer(msgs) return (ret_msg[0].data[0])
def get_eeprom(self, eeprom_address=0x50): # My Raspberry pi keeps timing-out here, so we split it into # two different transfers:... q1 = [I2C.Message([0x00, 0x00]), I2C.Message([0x00]*4000, read=True)] q2 = [I2C.Message([0x0f, 0xa0]), I2C.Message([0x00]*4000, read=True)] self.i2c.transfer(eeprom_address, q1) self.i2c.transfer(eeprom_address, q2) return np.array(q1[1].data + q2[1].data)
def firefly_reg_wr(i2c_bus_addr,firefly_refdes,dev_addr,reg_page,reg_addr,reg_value): firefly_select(firefly_refdes) i2c = I2C("/dev/i2c-0") i2c.transfer(TCA9548_U165_ADDR, [I2C.Message([i2c_bus_addr])]) # select i2c bus i2c.transfer(dev_addr, [I2C.Message([127,reg_page])]) # select the register page i2c.transfer(dev_addr, [I2C.Message([reg_addr,reg_value])]) # write the value to registers i2c.close()
def minipod_reg_wr(i2c_bus_addr, dev_addr, page_addr, reg_addr, reg_value): i2c = I2C("/dev/i2c-1") i2c.transfer(TCA9548_U93_ADDR, [I2C.Message([i2c_bus_addr])]) # select I2C Bus i2c.transfer(dev_addr, [I2C.Message([127, page_addr])]) # set the page i2c.transfer(dev_addr, [I2C.Message([reg_addr, reg_value])]) # write to reg_addr i2c.close()
def __wait_for_data(self): query = [I2C.Message([0x02]), I2C.Message([0x00], read=True)] done = False while not done: self.i2c.transfer(self.address, query) if not (query[1].data[0]%2 == 1): time.sleep(0.005) else: done = True
def Transaction(self, req): """Perform a Notecard transaction and return the result.""" req_json = prepareRequest(req, self._debug) rsp_json = "" while not self.lock(): pass try: self._sendPayload(req_json) chunk_len = 0 received_newline = False start = time.time() transaction_timeout_secs = 10 while True: time.sleep(.001) reg = bytearray(2) reg[0] = 0 reg[1] = chunk_len readlen = chunk_len + 2 buf = bytearray(readlen) if use_periphery: msgs = [I2C.Message(reg), I2C.Message(buf, read=True)] self.i2c.transfer(self.addr, msgs) buf = msgs[1].data elif use_micropython: self.i2c.writeto(self.addr, reg, False) self.i2c.readfrom_into(self.addr, buf) else: self.i2c.writeto_then_readfrom(self.addr, reg, buf) available = buf[0] good = buf[1] data = buf[2:2 + good] if good > 0 and buf[-1] == 0x0a: received_newline = True try: rsp_json += "".join(map(chr, data)) except: pass chunk_len = min(available, self.max) if chunk_len > 0: continue if received_newline: break if (time.time() >= start + transaction_timeout_secs): raise Exception("notecard request or response was lost") time.sleep(0.05) finally: self.unlock() if self._debug: print(rsp_json.rstrip()) rsp = json.loads(rsp_json) return rsp
def test_repstart(): i2c = I2C("/dev/i2c-1") write = I2C.Message([0x88]) read = I2C.Message([0x0]*2, read=True) # read 2 bytes msgs = [write, read] i2c.transfer(0x7F, msgs) value = msgs[1].data[1]*256 + msgs[1].data[0] return hex(value)
def __read_top_and_bottom_blocks(self): read_block = [I2C.Message([0x0A]), I2C.Message([0x00]*258, read=True)] self.i2c.transfer(self.address, read_block) top_data = np.array(copy.copy(read_block[1].data)) read_block = [I2C.Message([0x0B]), I2C.Message([0x00]*258, read=True)] self.i2c.transfer(self.address, read_block) bottom_data = np.array(copy.copy(read_block[1].data)) return top_data, bottom_data
def get_temp_humid(self): """ get_temp_humid() Get the temperature and humidity from the sensor. Returns an array with two integers - temp. [0] and humidity [1] """ # Loop sentinel values failCount = 0 # Commands to get data temp and humidity data from AM2315 cmd_data = bytearray((self.cmdReadReg, 0x00, 0x04)) # If we have failed more than twice to read the data, or have finished getting data break the loop. while (failCount < 2): try: cmd_msgs = [I2C.Message(cmd_data)] self.__i2c_master.transfer(self.i2c_addr, cmd_msgs) # Wait for the sensor to supply data to read. time.sleep(0.01) # Now read 8 bytes from the AM2315. read_data = bytearray( (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)) read_msgs = [I2C.Message(read_data, read=True)] self.__i2c_master.transfer(self.i2c_addr, read_msgs) # Break the string we want out of the array the transaction returns. rawTH = bytearray(read_msgs[0].data) # Confirm the command worked by checking the response for the command we executed # and the number of bytes we asked for. if ((rawTH[0] == self.cmdReadReg) or (rawTH[0] == self.cmdReadReg + 0x80)) and (rawTH[1] == 0x04): # And the MSB and LSB for each value together to yield our raw values. humidRaw = (rawTH[2] << 8) | rawTH[3] # Get signed int from AND'd temperature bytes. tempRaw = self.get_signed((rawTH[4] << 8) | rawTH[5]) # The return data is scaled up by 10x, so compensate. return (tempRaw / 10.0, humidRaw / 10.0) # No connection yet except AttributeError: pass # We usually fail to read data 50% of the time because the sensor goes to sleep, so try twice. except IOError: if failCount > 1: raise IOError( "am2315 IO Error: failed to read from sensor.") else: failCount = failCount + 1 return None, None
def tca6424_reg_rd(i2c_bus_addr,dev_addr,reg_addr): i2c = I2C("/dev/i2c-0") i2c.transfer(TCA9548_U165_ADDR, [I2C.Message([i2c_bus_addr])]) # select i2c bus read = I2C.Message([0x0]*1, read=True) i2c.transfer(dev_addr, [I2C.Message([reg_addr])]) # set reg_addr i2c.transfer(dev_addr, [read]) i2c.close() print('read back is 0x{0:x}' .format(read.data[0])) return read.data[0]
def i2c_read_reg(devregaddr): """ 使用periphery i2c库读取功能测试 """ # 构造数据结构 # 第一个Message为要读取的设备地址 # 第二个Message用于存放读取回来的消息,注意其中添加的read=True msgs = [I2C.Message([devregaddr]), I2C.Message([0x00], read=True)] # 发送消息,发送到i2cSlaveAddr i2c.transfer(I2CSLAVEADDR, msgs) print("从寄存器 0x{:02x} 读取出: 0x{:02x}".format(devregaddr, msgs[1].data[0]))
def minipod_reg_rd(i2c_bus_addr, dev_addr, page_addr, reg_addr): i2c = I2C("/dev/i2c-1") i2c.transfer(TCA9548_U93_ADDR, [I2C.Message([i2c_bus_addr])]) # select i2c bus read = I2C.Message([0x0], read=True) i2c.transfer(dev_addr, [I2C.Message([127, page_addr])]) # set the page i2c.transfer(dev_addr, [I2C.Message([reg_addr])]) # set reg_addr i2c.transfer(dev_addr, [read]) i2c.close() return read.data[0]
def firefly_reg_rd(i2c_bus_addr,firefly_refdes,dev_addr,reg_page,reg_addr): firefly_select(firefly_refdes) i2c = I2C("/dev/i2c-0") i2c.transfer(TCA9548_U165_ADDR, [I2C.Message([i2c_bus_addr])]) # select i2c bus read = I2C.Message([0x0]*1, read=True) i2c.transfer(dev_addr, [I2C.Message([127,reg_page])]) # select the register page i2c.transfer(dev_addr, [I2C.Message([reg_addr])]) # set reg_addr i2c.transfer(dev_addr, [read]) i2c.close() print('read back is 0x{0:x}' .format(read.data[0])) return read.data[0]
def read_sensor(): address = 0x06 register = 0x01 command = 0x03 unused = 0x00 sensor_id = detect_line_follower() if sensor_id == 2: raise NotImplementedError( 'line follower (black board) is not supported with the line_follower.line_sensor module\n\ please use the di_sensors.easy_line_follower.EasyLineFollower class to interface with both line followers (black + red boards)\n\ check https://di-sensors.readthedocs.io documentation to find out more') try: i2c = I2C('/dev/i2c-' + str(bus_number)) read_bytes = 10 * [0] msg1 = [I2C.Message([register, command] + 3 * [unused])] msg2 = [I2C.Message(read_bytes, read=True)] # we meed to do 2 transfers so we can avoid using repeated starts # repeated starts don't go hand in hand with the line follower i2c.transfer(address, msg1) i2c.transfer(address, msg2) except I2CError as error: return 5 * [-1] # unpack bytes received and process them # bytes_list = struct.unpack('10B',read_results[0]) output_values = [] input_values = msg2[0].data for step in range(5): # calculate the 16-bit number we got sensor_buffer[step].append(input_values[2 * step] * 256 + input_values[2 * step + 1]) # if there're too many elements in the list # then remove one if len(sensor_buffer[step]) > max_buffer_length: sensor_buffer[step].pop(0) # eliminate outlier values and select the most recent one filtered_value = statisticalNoiseReduction(sensor_buffer[step], 2)[-1] # append the value to the corresponding IR sensor output_values.append(filtered_value) return output_values
def ltc2499_current_mon(dev_addr, reg_addr0, reg_addr1): i2c = I2C("/dev/i2c-1") i2c.transfer(dev_addr, [I2C.Message([reg_addr1, reg_addr0])]) sleep(0.5) read = I2C.Message([0x0] * 4, read=True) i2c.transfer(dev_addr, [read]) adc_code = bytes(bytearray(read.data)).encode('hex') i2c.close() resolution = 2500. / 0x80000000 if (int(adc_code, 16) < 0x40000000): amplitude = 0 else: amplitude = (int(adc_code, 16) - 0x40000000) * resolution return amplitude / 40
def get_co2(self): try: # Set the FCR register self.write_register(self.FCR, 0x07) # cmd_data = bytearray((self.FCR, 0x07)) # cmd_msgs = [I2C.Message(cmd_data)] # self.__i2c_master.transfer(self.i2c_addr, cmd_msgs) # Read TXLVL register msgs = [I2C.Message([self.TXLVL]), I2C.Message([0x00], read=True)] self.__i2c_master.transfer(self.i2c_addr, msgs) txlvl = msgs[1].data[0] # Verify TXLVL if txlvl >= len(self.cmd_measure): # Send Command Bytes to THR Register cmd_data = bytearray([self.THR] + self.cmd_measure) cmd_msgs = [I2C.Message(cmd_data)] self.__i2c_master.transfer(self.i2c_addr, cmd_msgs) # Wait for the sensor to supply data to read. time.sleep(0.1) # Now read 9 bytes from the MHZ16. read_data = bytearray( (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)) read_msgs = [I2C.Message(read_data, read=True)] self.__i2c_master.transfer(self.i2c_addr, read_msgs) # Break the string we want out of the array the transaction returns. response = bytearray(read_msgs[0].data) ## Compute checksum checksum = 0 for i in range(0, 9): checksum += response[i] # Confirm the command worked by checking the response for the command we executed # and validating checksum if (response[0] == 0xFF) and (response[1] == 0x9C) and (checksum % 256 == 0xFF): return (response[2] << 24) + (response[3] << 16) + ( response[4] << 8) + response[5] except IOError: raise IOError("mhz16 IO Error: failed to read from sensor.") return None
def get_eeprom(self, eeprom_address=0x50): """Get dump of EEPROM configuration data from the HTPA device. Keyword Arguments: eeprom_address {hexadecimal} -- Communication address (default: {0x50}) Returns: np.array(bytes) -- EEPROM bytes """ # Two separate I2C transfers in case the buffer size is small q1 = [I2C.Message([0x00, 0x00]), I2C.Message([0x00]*4000, read=True)] q2 = [I2C.Message([0x0f, 0xa0]), I2C.Message([0x00]*4000, read=True)] self.i2c.transfer(eeprom_address, q1) self.i2c.transfer(eeprom_address, q2) return np.array(q1[1].data + q2[1].data)
def __init__(self, address=0x1A, i2c_bus="/dev/i2c-1"): self.address = address self.i2c = I2C(i2c_bus) self.blockshift = 4 # data read periodically while imaging self.data_ptats = None self.data_vdd = None self.elec_offset = None # buffer to gather pixel data self.ts = None self.pixel_values = np.zeros(1024) self.header_values = np.zeros(8) self.frame_cnt = 0 print ("Grabbing EEPROM data") eeprom = self.__get_eeprom() self.calib_params = self.__extract_eeprom_parameters(eeprom) self.eeprom = eeprom print("Initializing capture settings with stored calibration data") wakeup_and_blind = self.__generate_command(0x01, 0x01) # wake up the device adc_res = self.__generate_command(0x03, self.calib_params['MBIT_calib']) # set ADC resolution to 16 bits pull_ups = self.__generate_command(0x09, self.calib_params['PU_calib']) self.__send_command(wakeup_and_blind) self.__send_command(adc_res) self.__set_bias_current(self.calib_params['BIAS_calib']) self.__set_clock_speed(self.calib_params['CLK_calib']) self.__set_cm_current(self.calib_params['BPA_calib']) self.__send_command(pull_ups)
def __init__(self, bus, address, big_endian=True): """Initialize I2C Keyword arguments: bus -- The I2C bus: "RPI_1" - RPi hardware I2C "RPI_1SW" - RPi software I2C "GPG3_AD1" - GPG3 AD1 software I2C "GPG3_AD2" - GPG3 AD2 software I2C address -- the slave I2C address. Formatted as bits 0-6, not 1-7. big_endian (default True) -- Big endian? """ if bus == "RPI_1": self.bus_name = bus if RPI_1_Module == "pigpio": self.i2c_bus = pigpio.pi() self.i2c_bus_handle = None elif RPI_1_Module == "smbus": self.i2c_bus = smbus.SMBus(1) elif RPI_1_Module == "periphery": self.bus_name = bus self.i2c_bus = I2C("/dev/i2c-1") elif bus == "RPI_1SW": self.bus_name = bus self.i2c_bus = DI_I2C_RPI_SW() elif bus == "GPG3_AD1" or bus == "GPG3_AD2": self.bus_name = bus self.gopigo3_module = __import__("gopigo3") self.gpg3 = self.gopigo3_module.GoPiGo3() if bus == "GPG3_AD1": self.port = self.gpg3.GROVE_1 elif bus == "GPG3_AD2": self.port = self.gpg3.GROVE_2 self.gpg3.set_grove_type(self.port, self.gpg3.GROVE_TYPE.I2C) time.sleep(0.01) elif bus == "BP3_1" or bus == "BP3_2" or bus == "BP3_3" or bus == "BP3_4": self.bus_name = bus self.brickpi3_module = __import__("brickpi3") self.bp3 = self.brickpi3_module.BrickPi3() if bus == "BP3_1": self.port = self.bp3.PORT_1 elif bus == "BP3_2": self.port = self.bp3.PORT_2 elif bus == "BP3_3": self.port = self.bp3.PORT_3 elif bus == "BP3_4": self.port = self.bp3.PORT_4 self.bp3.set_sensor_type(self.port, self.bp3.SENSOR_TYPE.I2C, [0, 0]) time.sleep(0.01) else: raise IOError("I2C bus not supported") self.mutex = di_mutex.DI_Mutex(name=("I2C_Bus_" + bus)) self.set_address(address) self.big_endian = big_endian
def __init__(self, address): self.address = address self.i2c = I2C("/dev/i2c-1") wakeup_and_blind = self.generate_command(0x01, 0x01) # wake up the device adc_res = self.generate_command(0x03, 0x0C) # set ADC resolution to 16 bits pull_ups = self.generate_command(0x09, 0x88) print("Initializing capture settings") self.send_command(wakeup_and_blind) self.send_command(adc_res) self.send_command(pull_ups) self.set_bias_current(0x05) self.set_clock_speed(0x15) self.set_cm_current(0x0C) print("Grabbing EEPROM data") eeprom = self.get_eeprom() self.extract_eeprom_parameters(eeprom) self.eeprom = eeprom # initialize offset to zero self.offset = np.zeros((32, 32))
def set_frequency(frequency): if frequency not in frequencies: print('Invalid frequency, pick one of: {}'.format(frequencies.keys())) return False # select i2c device #i2c = I2C("/dev/i2c-0") # select i2c channel set_i2c_mux(TCA9548_U165_ADDR, Z_IIC_BUS2) i2c = I2C("/dev/i2c-0") # preamble, postamble, and soft-reset defined in configurations on a per-clock-chip basis # send the manufacturer preamble for initializing the clock chip for being able to accept register modifications print('Handling preamble') do_i2c_write(i2c, Si5345['preamble']) sleep(0.3) # 300 ms delay required by manufacturer # write the frequency configuration defined by manufacturer print('Handling modifications for {0:s}'.format(frequency)) do_i2c_write(i2c, frequencies[frequency]) # required by manufacturer for finishing register modifications print('Handling soft reset') do_i2c_write(i2c, Si5345['soft reset']) # required by manufacturer to lock the clock print('Handling postamble') do_i2c_write(i2c, Si5345['postamble']) print('{0:s} frequency was configured.'.format(frequency)) i2c.close() return True