class AM2320(object): """ AM2320 temperature and humidity sensor class. :param interface: I2C interface id. :type interface: :int :param sensor_address: AM2320 sensor I2C address. Optional, default 0x5C (92). :type sensor_address: int """ def __init__(self, interface, sensor_address=0x5c): self.interface = interface self.address = sensor_address self.temperature = -1000.0 self.humidity = -1 self.bus = SMBus(interface) def _read_raw(self, command, regaddr, regcount): try: self.bus.write_i2c_block_data(self.address, 0x00, []) self.bus.write_i2c_block_data(self.address, command, [regaddr, regcount]) sleep(0.002) buf = self.bus.read_i2c_block_data(self.address, 0, 8) except IOError, exc: raise CommunicationError(str(exc)) buf_str = "".join(chr(x) for x in buf) crc = unpack('<H', buf_str[-2:])[0] if crc != self._am_crc16(buf[:-2]): raise CommunicationError("AM2320 CRC error.") return buf_str[2:-2]
class motorControlBoard: """Class to allow communication with the motor control board built by me using I2C.""" __board_I2C_address = 0 def __init__(self, board_address): if isinstance(board_address, int): if board_address > 0 and board_address < 0x78: self.__board_I2C_address = board_address else: raise Exception("Board address must be an integer between 0 and 0b1111000 (=120) exclusive.") else: raise Exception("Board address must be an integer.") self.__bus = SMBus(1) # FIXME = have an option to make this zero for the old Raspberry Pis def set_speeds(self, left_speed, right_speed): # Enforce limits due to 8-bit resolution if(left_speed < -0xff): left_speed = -0xff if(left_speed > +0xff): left_speed = +0xff # Enforce limits due to 8-bit resolution if(right_speed < -0xff): right_speed = -0xff if(right_speed > +0xff): right_speed = +0xff direction = 0x00; if(left_speed < 0): direction |= MOTOR_CONTROL_LEFT_BACK elif(left_speed > 0): direction |= MOTOR_CONTROL_LEFT_FORE if(right_speed < 0): direction |= MOTOR_CONTROL_RIGHT_BACK elif(right_speed > 0): direction |= MOTOR_CONTROL_RIGHT_FORE self.__bus.write_i2c_block_data(self.__board_I2C_address, MOTOR_CONTROL_SET_DIR_SPEED_CMD, [direction, abs(left_speed), abs(right_speed)])
class PiGlow: i2c_addr = 0x54 # fixed i2c address of SN3218 ic bus = None def __init__(self, i2c_bus=1): self.bus = SMBus(i2c_bus) # first we tell the SN3218 to enable output (turn on) self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) # then we ask it to enable each bank of LEDs (0-5, 6-11, and 12-17) self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF]) def update_leds(self, values): #print "update pwm" self.write_i2c(CMD_SET_PWM_VALUES, values) self.write_i2c(CMD_UPDATE, 0xFF) # a helper that writes the given value or list of values to the SN3218 IC # over the i2c protocol def write_i2c(self, reg_addr, value): # if a single value is provided then wrap it in a list so we can treat # all writes in teh same way if not isinstance(value, list): value = [value]; # write the data to the SN3218 self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value)
class HTU21D(): """Class for accessing HTU21D sensors via I2C. Code taken from https://github.com/jasiek/HTU21D. Args: busno (int): The I2C bus (0 or 1, default is 1). address (byte): The I2C address of the sensor. """ CMD_TRIG_TEMP_HM = 0xE3 CMD_TRIG_HUMID_HM = 0xE5 CMD_TRIG_TEMP_NHM = 0xF3 CMD_TRIG_HUMID_NHM = 0xF5 CMD_WRITE_USER_REG = 0xE6 CMD_READ_USER_REG = 0xE7 CMD_RESET = 0xFE def __init__(self, busno=1, address=config.SENSOR_ID_HUMIDITY_EXT): self.bus = SMBus(busno) self.i2c_address = address def read_temperature(self): self.reset() msb, lsb, crc = self.bus.read_i2c_block_data( self.i2c_address, self.CMD_TRIG_TEMP_HM, 3) return -46.85 + 175.72 * (msb * 256 + lsb) / 65536 def read_humidity(self): self.reset() msb, lsb, crc = self.bus.read_i2c_block_data( self.i2c_address, self.CMD_TRIG_HUMID_HM, 3) return (-6 + 125 * (msb * 256 + lsb) / 65536.0) / 100.0 def reset(self): self.bus.write_byte(self.i2c_address, self.CMD_RESET)
class LEDSign: def __init__(self): self.s = SMBus(0) self.lock = Lock() def print_message(self, line, message): if len(message) > 255: message = message[:255] if message[:-1] != "\x00": message = "".join([message, "\x00"]) self.print_message_loop(line, message) def print_message_loop(self, line, message): if message == "": return self.lock.acquire() self.s.write_i2c_block_data(signAddress, line, [ord(x) for x in message[0:payLoadLen]]) self.lock.release() self.print_message_loop(line, message[payLoadLen:]) def get_status(self): self.lock.acquire() labStatus = self.s.read_byte(signAddress) self.lock.release() return labStatus
class PCF8574(object): def __init__(self, bus_id, address): super().__init__() self.__bus = SMBus(bus_id) self.__address = address self.__value = self.__getRealValue() @property def value(self): return self.__value @value.setter def value(self, value): self.__bus.write_byte(self.__address, (~value) & 0xff ) self.__value = value def flipBits(self, changeBits): self.value ^= changeBits def __getRealValue(self): value = self.__bus.read_byte(self.__address) return (~value) & 0xff
def __init__(self, busNum): # Remove annoying init message (The Raspberry Pi Guy) if busNum == 0: self.__bus = SMBus(0) else: self.__bus = SMBus(1) self.__addr = self.__checkI2Caddress(72) self.__DACEnabled = 0
def test_open(): bus = SMBus() py.test.raises(IOError, 'bus.open(-13)') bus.open(BUS) # does not raise if hasattr(bus, '_fd'): assert bus._fd != -1
def get_temp(): # zlecenie konwersji i2c_bus = SMBus(1) i2c_bus.write_byte_data(Register.LIGHT2_ADDRESS, 10, 1) sleep(1) cel = i2c_bus.read_word_data(0x20, 5) cel = cel >> 8 return cel
def __init__(self, busNum): #print "init PCF8591" if busNum == 0: self.__bus = SMBus(0) # on a Rev 1 board #print "bus 0" else: self.__bus = SMBus(1) # on a Rev 2 board self.__addr = self.__checkI2Caddress(0x48) self.__DACEnabled = 0x00
class Bus_Hepler_i2c(): def __init__(self, bus_location=1): self.bus = SMBus(bus_location) def write_byte(self, address, register, byte): self.bus.write_i2c_block_data(address, register, [byte]) def read_block_data(self, address, cmd): return self.bus.read_i2c_block_data(address, cmd)
def DetectCap(i2c_addr, i2c_bus, product_id): bus = SMBus(i2c_bus) try: if bus.read_byte_data(i2c_addr, R_PRODUCT_ID) == product_id: return True else: return False except IOError: return False
def __init__(self, busNum): print "init PCF8591" if busNum == 0: self.__bus = SMBus(0) # on a Rev 1 board # print "bus 0" else: self.__bus = SMBus(1) # on a Rev 2 board self.__addr = self.__checkI2Caddress(0x48) self.__DACEnabled = 0x00 print self.readADC() # dummy call to raise exception if no chip presnt on the i2c bus print "PCF8591 init completed"
class i2cDevice: def __init__(self, bus_number): self.BC_addr = 0x25 self.bus = SMBus(bus_number) def read_register(self, address): self.bus.write_byte(self.BC_addr, address) time.sleep(0.02) data = struct.pack('B', self.bus.read_byte(self.BC_addr)) return data def write_register(self, address, data): self.bus.write_byte_data(self.BC_addr, address, data) time.sleep(0.02)
class Pines(object): """docstring for Pines""" def __init__(self,address): conf.estado = 0b11111111 self.address = address self.bus = SMBus(1) def cero(self,pin): conf.estado &=~(1<<pin) self.bus.write_byte(self.address , conf.estado) return conf.estado def uno(self , pin): conf.estado |=(1<<pin) self.bus.write_byte(self.address , conf.estado) return conf.estado def toggle(self,pin): numero = 2**pin conf.estado = conf.estado^numero self.bus.write_byte(self.address , conf.estado) return conf.estado def toggle2(self,pin1,pin2): self.toggle(pin1) self.toggle(pin2) def reset(self): self.estado = self.estado|255 self.bus.write_byte(address , self.estado)
class DAC12(object): def __init__(self, dac_num, maximum=100.0): bus, self.addr = get_dac_addr(dac_num) self.bus = SMBus(bus) self.coeff = 4096/float(maximum) def conv(self, valeur): return int(ceil(valeur * self.coeff)) & 0xFFFF def set_eeprom(self, valeur): self.bus.write_word_data(self.addr, WRITE_DAC_AND_EEPROM, self.conv(valeur)) def set(self, valeur): self.bus.write_word_data(self.addr, WRITE_DAC, self.conv(valeur))
def __init__(self, i2c_bus=0): """ :type i2c_bus: int specifying i2c bus number """ self._bus = SMBus(i2c_bus) whoami = self._bus.read_byte_data(MPL3115A2_ADDRESS, MPL3115A2_WHOAMI) if whoami != 0xc4: print("MPL3115A2 not active.") exit(1) # Set MPL3115A2 oversampling to 128, put in Barometer mode, enabled standby on CTRL_REG1 self._bus.write_byte_data( MPL3115A2_ADDRESS, MPL3115A2_CTRL_REG1, MPL3115A2_CTRL_REG1_SBYB | MPL3115A2_CTRL_REG1_OS128 | MPL3115A2_CTRL_REG1_BAR) # Configure MPL3115A2 self._bus.write_byte_data( MPL3115A2_ADDRESS, MPL3115A2_PT_DATA_CFG, MPL3115A2_PT_DATA_CFG_TDEFE | MPL3115A2_PT_DATA_CFG_PDEFE | MPL3115A2_PT_DATA_CFG_DREM)
def __init__(self, i2c_bus=1): self.bus = SMBus(i2c_bus) # Enable output self.write(CMD_ENABLE_OUTPUT, 0x01) # Enable LEDs ( 0-5, 6-11, 12-17 ) self.write(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0XFF])
class HTU21D: def __init__(self, busno): self.bus = SMBus(busno) def read_temperature(self): self.reset() msb, lsb, crc = self.bus.read_i2c_block_data(I2C_ADDR, CMD_TRIG_TEMP_HM, 3) return -46.85 + 175.72 * (msb * 256 + lsb) / 65536 def read_humidity(self): self.reset() msb, lsb, crc = self.bus.read_i2c_block_data(I2C_ADDR, CMD_TRIG_HUMID_HM, 3) return -6 + 125 * (msb * 256 + lsb) / 65536.0 def reset(self): self.bus.write_byte(I2C_ADDR, CMD_RESET)
def __init__(self): self.adc_address1 = 0x68 self.adc_address2 = 0x69 # create byte array and fill with initial values to define size self.adcreading = bytearray() self.adcreading.append(0x00) self.adcreading.append(0x00) self.adcreading.append(0x00) self.adcreading.append(0x00) self.setDivisor(64) #self.varDivisior = 64 # default value: from pdf sheet on adc addresses and config #self.varMultiplier = (2.4705882/self.varDivisior)/1000 # detect i2C port number and assign to i2c_bus for line in open('/proc/cpuinfo').readlines(): m = re.match('(.*?)\s*:\s*(.*)', line) if m: (name, value) = (m.group(1), m.group(2)) if name == "Revision": if value [-4:] in ('0002', '0003'): i2c_bus = 0 else: i2c_bus = 1 break self.bus = SMBus(i2c_bus)
def __init__(self,device=0,Port=None,Server=None): """ @param device The I2C bus to use e.g. /dev/i2c-0, /dev/i2c-1 etc. @param Port Default=None if set to an Integer this will be the TCP/IP port to listen on. @param Server Default=None if set to a string e.g. '192.168.200.137' the bus listening on that address/port combination will be connected to. @todo Ckeck for Raspberry Pi, and its version in /Proc/CPUInfo If you Init an I2CBus like s = I2C(1,Port=50000) it wil listen to connections from a remote bw_library on any other computer a bw_library installation can make use of tcp communications like the I2C bus is connected to the local machine. Netbus = SPI(Server= '192.168.200.1',port=50000) In this case the device parameter is ignored. """ self.Port = Port self.Server=Server if self.Server != None: # TCP Client mode self.NetInit() self.Transaction=self._NetTransaction else: try: self.I2cBus = SMBus(device) except : print 'Need python-smbus for I2C bus to work' print '' print 'To install: sudo apt-get install python-smbus' return None if self.Port != None: #TCP Server Mode self.ServerThread = threading.Thread(target=self.ListenerTread) self.ServerThread.start()
def __init__( self, brightness=None, speed=None, pulse=None, pulse_dir=None, i2c_bus=None): if i2c_bus is None: i2c_bus = self.get_i2c_bus() # Enables the LEDs self.bus = SMBus(i2c_bus) # Tell the SN3218 to enable output self.bus.write_byte_data(I2C_ADDR, EN_OUTPUT_ADDR, 0x01) # Enable each LED arm self.bus.write_byte_data(I2C_ADDR, EN_ARM1_ADDR, 0xFF) self.bus.write_byte_data(I2C_ADDR, EN_ARM2_ADDR, 0xFF) self.bus.write_byte_data(I2C_ADDR, EN_ARM3_ADDR, 0xFF) # Set default brightness and pulsing params self.brightness = brightness self.speed = speed self.pulse = pulse self.pulse_dir = pulse_dir # Define the LED state variable self.__STATE = {'leds': {}, 'params': {}}
def get(self): lStatus = 'ok' lArgs = self.__mParser.parse_args() lBusId = int(lArgs['bus_id'], 0) lAddress = int(lArgs['address'], 0) lValue = int(lArgs['value'], 0) lBus = SMBus(lBusId) try: if lArgs['cmd'] is None: lBus.write_byte(lAddress, lValue) else: lCommand = int(lArgs['cmd'], 0) lBus.write_byte_data(lAddress, lCommand, lValue) except IOError, pExc: lStatus = "Error writing data: " + str(pExc)
def __init__(self, gpio_en, gpio_stby, i2cbus = None, gpio_mode_bcm = False): if i2cbus == None: raise Exception()#TODO auto selection based on RPI board revision self._gpio_en = gpio_en self._gpio_stby = gpio_stby self._bus = SMBus(i2cbus) sleep(0.5) GPIO.setmode(GPIO.BCM if gpio_mode_bcm else GPIO.BOARD) GPIO.setup(self._gpio_en, GPIO.OUT, GPIO.LOW) GPIO.setup(self._gpio_stby, GPIO.OUT, GPIO.LOW) self._state = { "power": False, "mute": True } self.DSP = DSP(self) self.TUNER = TUNER(self) # init GPIOs self.power(False) self.mute(True)
def __init__(self,device_number,channel): """ """ try: self.bus = SMBus(device_number) except Exception: raise i2cError() try: if channel ==3: self.CH = self._CONFIG_REG_MUX_CH3 elif channel == 2: self.CH = self._CONFIG_REG_MUX_CH2 elif channel == 1: self.CH = self._CONFIG_REG_MUX_CH1 else: self.CH = self._CONFIG_REG_MUX_CH0 # MUX PGA MODE DR COMP_QUE confList = [ self.CH, \ self._CONFIG_REG_PGA_4096, \ self._CONFIG_REG_MODE_CONT, \ self._CONFIG_REG_DR_250SPS, \ self._CONFIG_REG_COMP_OFF ] self.configADS1015(confList) # set conversion factor if confList[1] == self._CONFIG_REG_PGA_6144: self.convFactor = 6.144*2.0/4096 elif confList[1] == self._CONFIG_REG_PGA_4096: self.convFactor = 4.096*2.0/4096 except Exception as e: print(e) raise ConfigError()
def __init__(self, busnum, address): self.bus = SMBus(busnum) self.address = address # Set all outputs off self.bus.write_byte(self.address, 0x00) # Store P-port state self.byte = 0x00
def __init__(self): """ Initialise la manette nunchuk. """ self.bus = SMBus(1) self.bus.write_byte_data(0x52,0x40,0x00) sleep(0.1)
def __init__( self, brightness=None, speed=None, pulse=None, pulse_dir=None): # Check what Raspberry Pi version we got if rpi.RPI_REVISION == 1: i2c_bus = 0 elif rpi.RPI_REVISION == 2 or rpi.RPI_REVISION == 3: i2c_bus = 1 else: raise PyGlowException( self, "Unknown Raspberry Pi hardware revision: %s" % (rpi.RPI_REVISION)) # Enables the LEDs self.bus = SMBus(i2c_bus) # Tell the SN3218 to enable output self.bus.write_byte_data(I2C_ADDR, EN_OUTPUT_ADDR, 0x01) # Enable each LED arm self.bus.write_byte_data(I2C_ADDR, EN_ARM1_ADDR, 0xFF) self.bus.write_byte_data(I2C_ADDR, EN_ARM2_ADDR, 0xFF) self.bus.write_byte_data(I2C_ADDR, EN_ARM3_ADDR, 0xFF) # Set default brightness and pulsing params self.brightness = brightness self.speed = speed self.pulse = pulse self.pulse_dir = pulse_dir # Define the LED state variable self.__STATE = {'leds': {}, 'params': {}}
class Scan(Base): def __init__(self): self.found = [] def setup(self): self.bus = SMBus(1) return self def run(self): for i in range(1,127): # rez = self.bus.read_byte(i) try: rez = self.bus.write_quick(i) self.found.append(i) print "%s -> %s" % (i,rez) except IOError: pass def command(self,line): if re.search('^rescan$', line): self.run() if len(self.found) > 0: self.commander.default_address = self.found[0] return True elif re.search('^list$', line): for a in self.found: print a return True def help(self): return "rescan # rescan for i2c"
def __init__(self, i2c_bus=1): self.bus = SMBus(i2c_bus) # first we tell the SN3218 to enable output (turn on) self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) # then we ask it to enable each bank of LEDs (0-5, 6-11, and 12-17) self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF])
MaxValueDac = 65535 MinValueDac = 0 WRITEDAC_ABCD = 0x3F WRITEDAC_A = 0x31 WRITEDAC_B = 0x32 WRITEDAC_C = 0x34 WRITEDAC_D = 0x38 RefSetupReg = 0x70 # Default I2C address: DEFAULT_ADDRESS = 0x0c I2C5 = 4 bus = SMBus(I2C5) print bus bus.write_i2c_block_data(DEFAULT_ADDRESS, RefSetupReg, [0, 0]) bus.write_i2c_block_data(DEFAULT_ADDRESS, WRITEDAC_ABCD, [0, 0]) def set_voltage(ValueDAC, SelectedChannel): if ValueDAC > MaxValueDac: ValueDAC = MaxValueDac if ValueDAC < MinValueDac: ValueDAC = MinValueDac Data = [(ValueDAC >> 8) & 0xFF, (ValueDAC) & 0xFF] if SelectedChannel == 1:
if type(__val) is not int: raise PCF8591PDACvalueOutOfBoundsError elif (__val < 0): raise PCF8591PDACvalueOutOfBoundsError elif (__val > 255): raise PCF8591PDACvalueOutOfBoundsError return __val # Test harnesses if __name__ == "__main__": from smbus import SMBus from time import sleep i2c = SMBus(0) try: sensor = PCF8591P() except Exception as e: print "Passed: missing parameters" + e.message try: sensor = PCF8591P(i2c) except Exception as e: print "Passed: missing address parameter" + e.message try: sensor = PCF8591P(i2c, 'cheese') except I2CaddressOutOfBoundsError as e: print "Passed: " + e.message try: sensor = PCF8591P(i2c, -1)
def __init__(self): rospy.init_node('juliette_controller') self.rate = rospy.get_param('~rate', 10) self.Kp = rospy.get_param('~Kp', 1.0) self.Ki = rospy.get_param('~Ki', 1.0) self.Kd = rospy.get_param('~Kd', 1.0) # Radian/s min and max velocities self.motor_max_angular_vel = rospy.get_param('~motor_max_angular_vel', 6.0) self.motor_min_angular_vel = rospy.get_param('~motor_min_angular_vel', 1.0) # Corresponding motor commands self.motor_cmd_max = rospy.get_param('~motor_cmd_max', 180) self.motor_cmd_min = rospy.get_param('~motor_cmd_min', 30) # Constants for SMBus self.i2c_addr = 0x7 # bus address self.i2c_bus = SMBus(1) # indicates /dev/ic2-1 self.break_cmd = 0 self.left_motor_cmd = 2 self.right_motor_cmd = 1 self.forward_msg = 1 self.backward_msg = 0 self.R = rospy.get_param('~robot_wheel_radius', 0.063) self.pid_on = rospy.get_param('~pid_on', False) self.juliette_on = rospy.get_param('~juliette_on', True) # (Optional) Publish the computed angular velocity targets self.lwheel_angular_vel_target_pub = rospy.Publisher( 'lwheel_angular_vel_target', Float32, queue_size=10) self.rwheel_angular_vel_target_pub = rospy.Publisher( 'rwheel_angular_vel_target', Float32, queue_size=10) # (Optional) Publish the computed angular velocity control command self.lwheel_angular_vel_control_pub = rospy.Publisher( 'lwheel_angular_vel_control', Float32, queue_size=10) self.rwheel_angular_vel_control_pub = rospy.Publisher( 'rwheel_angular_vel_control', Float32, queue_size=10) # (Optional) Publish the computed angular velocity motor command self.lwheel_angular_vel_motor_pub = rospy.Publisher( 'lwheel_angular_vel_motor', Float32, queue_size=10) self.rwheel_angular_vel_motor_pub = rospy.Publisher( 'rwheel_angular_vel_motor', Float32, queue_size=10) # Read in encoders for PID control self.lwheel_angular_vel_enc_sub = rospy.Subscriber( 'lwheel_angular_vel_enc', Float32, self.lwheel_angular_vel_enc_callback) self.rwheel_angular_vel_enc_sub = rospy.Subscriber( 'rwheel_angular_vel_enc', Float32, self.rwheel_angular_vel_enc_callback) # Read in tangential velocity targets self.lwheel_tangent_vel_target_sub = rospy.Subscriber( 'lwheel_tangent_vel_target', Float32, self.lwheel_tangent_vel_target_callback) self.rwheel_tangent_vel_target_sub = rospy.Subscriber( 'rwheel_tangent_vel_target', Float32, self.rwheel_tangent_vel_target_callback) # Tangential velocity target self.lwheel_tangent_vel_target = 0 self.rwheel_tangent_vel_target = 0 # Angular velocity target self.lwheel_angular_vel_target = 0 self.rwheel_angular_vel_target = 0 # Angular velocity encoder readings self.lwheel_angular_vel_enc = 0 self.rwheel_angular_vel_enc = 0 # PID control variables self.lwheel_pid = {} self.rwheel_pid = {}
from smbus import SMBus import sys,json,requests addr = 0x8 # bus address bus = SMBus(0) # indicates /dev/ic2-0 numb = 1 while True: try: while True: n=8 cache = [] scienceCache =[] for i in range(n): cache.append(bus.read_byte_data(addr,200)) print("Cache") print(cache) index = cache.index(123) scienceCache = cache[index:] + cache[:index] #scienceCache = cache[:index] + cache[index:] scienceCache.reverse() ''' To Naman, Put dictionary with name sensor_dict. Modify and give all in place of this comment ''' string_data = json.dumps(sensor_dict) r = requests.get("http://"+sys.argv[1]"+:5000/science/set_science?json="+string_data) print("Science Cache")
def busInit(): # start up the I2C bus and enable the outputs on the SN3218 global bus bus = SMBus(1) bus.write_byte_data(SN3218,CMD_ENABLE_OUTPUT, 0x01) bus.write_i2c_block_data(SN3218, CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF])
def __init__(self, busId, slaveAddr, ifLog, ifWriteBlock): self.__i2c = SMBus(busId) self.__slave = slaveAddr self.__ifWriteBlock = ifWriteBlock self.__ifLog = ifLog self.__x0 = 0
def setup(): global pwm # Raspberry Pi revision 2 bus = SMBus(1) pwm = PWM(bus, i2c_address) pwm.setFreq(fPWM)
import sys import optparse from smbus import SMBus import time ####################### # Get options ####################### parser = optparse.OptionParser("usage: %prog [options] <decimal to write>") #parser.add_option ('-a', dest='address', type='string', # default = '70', # help="Hex value of address of i2c device.") options, args = parser.parse_args() if len(args) != 1: print "Please specify decimal integer to write via i2c" sys.exit() byteToWrite = int(args[0]) ####################### bus = SMBus(1) address = 0x70 print bus.read_byte(address) bus.write_byte(address, byteToWrite) print bus.read_byte(address)
def __init__(self): self.bus = SMBus(LightSensor.I2C_BUS_ID)
from __future__ import division import time from smbus import SMBus import Adafruit_PCA9685 import subprocess import math import numpy as np from ast import literal_eval PI = 3.14 #Global Variables pwm2 = Adafruit_PCA9685.PCA9685(address=0x41, busnum=1) pwm2.set_pwm_freq(50) bus = SMBus(1) FL_sensor = 0 FR_sensor = 0 HL_sensor = 0 HR_sensor = 0 #Functions def adc(add, data): bus.write_i2c_block_data(add, 0x01, data) adc0 = bus.read_i2c_block_data(add, 0x00, 2) a = adc0[0] & 0xFFFF b = adc0[1] & 0xFF c = (a << 8) | b return c
def __init__(self, busno): self.bus = SMBus(busno) self.reset()
def __init__(self, busId=1): """ Initialize the I2C bus. """ self._i2c = SMBus(busId)
class I2C(object): """ Class to set up and access I2C devices. """ # # Class methods # # Private methods def __init__(self, busId=1): """ Initialize the I2C bus. """ self._i2c = SMBus(busId) def __del__(self): """ Clean up routines. """ try: # Remove SMBus connection del (self._i2c) except: pass def _combineLoHi(self, loByte, hiByte): """ Combine low and high bytes to an unsigned 16 bit value. """ return (loByte | hiByte << 8) def _combineSignedLoHi(self, loByte, hiByte): """ Combine low and high bytes to a signed 16 bit value. """ combined = self._combineLoHi(loByte, hiByte) return combined if combined < 32768 else (combined - 65536) def _combineXLoLoHi(self, xloByte, loByte, hiByte): """ Combine extra low, low, and high bytes to an unsigned 24 bit value. """ return (xloByte | loByte << 8 | hiByte << 16) def _combineSignedXLoLoHi(self, xloByte, loByte, hiByte): """ Combine extra low, low, and high bytes to a signed 24 bit value. """ combined = self._combineXLoLoHi(xloByte, loByte, hiByte) return combined if combined < 8388608 else (combined - 16777216) def _getSensorRawLoHi1(self, address, outRegs): """ Return a scalar representing the combined raw signed 16 bit value of the output registers of a one-dimensional sensor, e.g. temperature. 'address' is the I2C slave address. 'outRegs' is a list of the output registers to read. """ # Read register outputs and combine low and high byte values xl = self._readRegister(address, outRegs[0]) xh = self._readRegister(address, outRegs[1]) xVal = self._combineSignedLoHi(xl, xh) # Return the scalar return xVal def _getSensorRawXLoLoHi1(self, address, outRegs): """ Return a scalar representing the combined raw signed 24 bit value of the output registers of a one-dimensional sensor, e.g. temperature. 'address' is the I2C slave address. 'outRegs' is a list of the output registers to read. """ # Read register outputs and combine low and high byte values xxl = self._readRegister(address, outRegs[0]) xl = self._readRegister(address, outRegs[1]) xh = self._readRegister(address, outRegs[2]) xVal = self._combineSignedXLoLoHi(xxl, xl, xh) # Return the scalar return xVal def _getSensorRawLoHi3(self, address, outRegs): """ Return a vector (i.e. list) representing the combined raw signed 16 bit values of the output registers of a 3-dimensional (IMU) sensor. 'address' is the I2C slave address. 'outRegs' is a list of the output registers to read. """ # Read register outputs and combine low and high byte values xl = self._readRegister(address, outRegs[0]) xh = self._readRegister(address, outRegs[1]) yl = self._readRegister(address, outRegs[2]) yh = self._readRegister(address, outRegs[3]) zl = self._readRegister(address, outRegs[4]) zh = self._readRegister(address, outRegs[5]) xVal = self._combineSignedLoHi(xl, xh) yVal = self._combineSignedLoHi(yl, yh) zVal = self._combineSignedLoHi(zl, zh) # Return the vector return [xVal, yVal, zVal] def _readRegister(self, address, register): """ Read a single I2C register. """ return self._i2c.read_byte_data(address, register) def _readRegisters(self, address, register, count): """ Read (up to 32) 'count' consecutive I2C registers. """ return self._i2c.read_i2c_block_data(address, register, count) def _read(self, address): """ Read a single byte from the I2C device without specifying a register. """ return self._i2c.read_byte(address) def _writeRegister(self, address, register, value): """ Write a single byte to a I2C register. Return the value the register had before the write. """ valueOld = self._readRegister(address, register) self._i2c.write_byte_data(address, register, value) return valueOld def _write(self, address, value): """ Write a single byte to the I2C device without specifying a register. """ return self._i2c.write_byte(address, value) def _testRegister(self, address, register): """ Check, if a I2C register is readable/accessible. """ try: return self._readRegister(address, register) except: return -1
class beschleunigungssensor(): def __init__(self): self.addr = 0x50 self.i2c = SMBus(1) # close led on JY901 self.i2c.write_i2c_block_data(0x50, 0x1b, [0x01, 0x00]) # horizontally motieren self.i2c.write_i2c_block_data(0x50, 0x23, [0x00, 0x00]) sleep(.5) # auto gyro calibration. [0x01,0x00] unauto. self.i2c.write_i2c_block_data(0x50, 0x63, [0x00, 0x00]) sleep(.5) # begin calibration of acc self.i2c.write_i2c_block_data(0x50, 0x01, [0x01, 0x00]) sleep(1) # # stop calibration of acc # self.i2c.write_i2c_block_data(0x50, 0x01, [0x00,0x00]) # sleep(.5) # save change. [0x01,0x00] --> default self.i2c.write_i2c_block_data(0x50, 0x00, [0x00, 0x00]) sleep(1) self.static_acc_error = array((0, 0, 0)) getStaticError_thread = Thread(target=self.getStaticError, args=(), daemon=True) getStaticError_thread.start() def getLinearAcc(self): acc = array(self.get_acc()) quaternion = array(self.get_quat()) gravity_n = asarray([0, 0, 9.80665]) rot_mat = self.quaternion_to_rotation_matrix(quaternion) gravity_b = dot(rot_mat, gravity_n) linear_acc = acc - gravity_b return linear_acc def get_acc(self): try: self.raw_acc_x = self.i2c.read_i2c_block_data(self.addr, 0x34, 2) self.raw_acc_y = self.i2c.read_i2c_block_data(self.addr, 0x35, 2) self.raw_acc_z = self.i2c.read_i2c_block_data(self.addr, 0x36, 2) except IOError as error: raise error return self.k_acc = 16 * 9.80665 self.acc_x = (self.raw_acc_x[1] << 8 | self.raw_acc_x[0]) / 32768 * self.k_acc self.acc_y = (self.raw_acc_y[1] << 8 | self.raw_acc_y[0]) / 32768 * self.k_acc self.acc_z = (self.raw_acc_z[1] << 8 | self.raw_acc_z[0]) / 32768 * self.k_acc if self.acc_x >= self.k_acc: self.acc_x -= 2 * self.k_acc if self.acc_y >= self.k_acc: self.acc_y -= 2 * self.k_acc if self.acc_z >= self.k_acc: self.acc_z -= 2 * self.k_acc return (self.acc_x, self.acc_y, self.acc_z) def get_quat(self): try: self.raw_quat_0 = self.i2c.read_i2c_block_data(self.addr, 0x51, 2) self.raw_quat_1 = self.i2c.read_i2c_block_data(self.addr, 0x52, 2) self.raw_quat_2 = self.i2c.read_i2c_block_data(self.addr, 0x53, 2) self.raw_quat_3 = self.i2c.read_i2c_block_data(self.addr, 0x54, 2) except IOError as error: raise error return self.k_quat = 1 self.quat_0 = (self.raw_quat_0[1] << 8 | self.raw_quat_0[0]) / 32768 * self.k_quat self.quat_1 = (self.raw_quat_1[1] << 8 | self.raw_quat_1[0]) / 32768 * self.k_quat self.quat_2 = (self.raw_quat_2[1] << 8 | self.raw_quat_2[0]) / 32768 * self.k_quat self.quat_3 = (self.raw_quat_3[1] << 8 | self.raw_quat_3[0]) / 32768 * self.k_quat if self.quat_0 >= self.k_quat: self.quat_0 -= 2 * self.k_quat if self.quat_1 >= self.k_quat: self.quat_1 -= 2 * self.k_quat if self.quat_2 >= self.k_quat: self.quat_2 -= 2 * self.k_quat if self.quat_3 >= self.k_quat: self.quat_3 -= 2 * self.k_quat return (self.quat_0, self.quat_1, self.quat_2, self.quat_3) def quaternion_to_rotation_matrix(self, quat): q = quat.copy() n = dot(q, q) if n < finfo(q.dtype).eps: return identity(4) q = q * sqrt(2.0 / n) q = outer(q, q) rot_matrix = array( [[1.0 - q[2, 2] - q[3, 3], q[1, 2] + q[3, 0], q[1, 3] - q[2, 0]], [q[1, 2] - q[3, 0], 1.0 - q[1, 1] - q[3, 3], q[2, 3] + q[1, 0]], [q[1, 3] + q[2, 0], q[2, 3] - q[1, 0], 1.0 - q[1, 1] - q[2, 2]]], dtype=q.dtype) return rot_matrix def getStaticError(self): while True: try: linearAcc_group = self.getLinearAcc() time_prev = time() while time() - time_prev < .1: linearAcc_group = row_stack( (linearAcc_group, self.getLinearAcc())) sleep(.008) print linearAcc_group_var = var(linearAcc_group, axis=0, keepdims=True) #print (linearAcc_group_var) if linearAcc_group_var[0][0] < 1e-5 and linearAcc_group_var[0][ 1] < 1e-5 and linearAcc_group_var[0][2] < 1e-5: self.static_acc_error = mean(linearAcc_group, axis=0, keepdims=True)[0] except: sleep(.001) continue
# Raspberry Pi Master for Arduino Slave # i2c_master_pi.py # Connects to Arduino via I2C # DroneBot Workshop 2019 # https://dronebotworkshop.com from smbus import SMBus addr = 0x8 # bus address bus = SMBus(1) # indicates /dev/ic2-1 numb = 1 print("Enter 1 for ON or 0 for OFF, 2 to read the last value") while numb == 1: ledstate = input(">>>> ") if ledstate == "1": bus.write_byte(addr, 1) # switch it ON elif ledstate == "0": bus.write_byte(addr, 0) # switch it OFF elif ledstate == "2": b = bus.read_byte(addr) print(b) else: numb = 0
def main(): ''' Main program function ''' buf = [0, 0] if __name__ == "__main__": main() from smbus import SMBus import time i2cbus = SMBus(1) # Create a new I2C bus i2caddress = 0x18 # Address of keypad RD_KEY_CMND = 0x05 SET_KEY_VALUES_CMND = 0x10 New_Key_Values = [ '9', 'E', 'x', 'x', 'x', '0', '4', 'x', 'x', 'x', 'A', 'B', 'x', 'x', 'x', 'F', 'G', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x' ] New_Int_Values = [ord(str) for str in New_Key_Values] print(New_Key_Values) print(New_Int_Values) i2cbus.write_i2c_block_data(i2caddress, SET_KEY_VALUES_CMND, New_Int_Values) while 1:
def setup_bus(x): bus = SMBus(x) # x indicates /dev/i2c-x return bus
def __init__(self, busno): self.bus = SMBus(1)
class L3GD20(object): def __init__(self, busId, slaveAddr, ifLog, ifWriteBlock): self.__i2c = SMBus(busId) self.__slave = slaveAddr self.__ifWriteBlock = ifWriteBlock self.__ifLog = ifLog self.__x0 = 0 def __del__(self): del(self.__i2c) def __log(self, register, mask, current, new): register = '0b' + bin(register)[2:].zfill(8) mask = '0b' + bin(mask)[2:].zfill(8) current = '0b' + bin(current)[2:].zfill(8) new = '0b' + bin(new)[2:].zfill(8) print('Change in register:' + register + ' mask:' + mask + ' from:' + current + ' to:' + new) def __writeToRegister(self, register, mask, value): current = self.__i2c.read_byte_data(self.__slave, register) # Get current value new = bitOps.SetValueUnderMask(value, current, mask) if self.__ifLog: self.__log(register, mask, current, new) if not self.__ifWriteBlock: self.__i2c.write_byte_data(self.__slave, register, new) def __readFromRegister(self, register, mask): current = self.__i2c.read_byte_data(self.__slave, register) # Get current value return bitOps.GetValueUnderMask(current, mask) def __readFromRegisterWithDictionaryMatch(self, register, mask, dictionary): current = self.__readFromRegister(register, mask) for key in dictionary.keys(): if dictionary[key] == current: return key def __writeToRegisterWithDictionaryCheck(self, register, mask, value, dictionary, dictionaryName): if value not in dictionary.keys(): raise Exception('Value:' + str(value) + ' is not in range of: ' + str(dictionaryName)) self.__writeToRegister(register, mask, dictionary[value]) __REG_R_WHO_AM_I = 0x0f # Device identification register __REG_RW_CTRL_REG1 = 0x20 # Control register 1 __REG_RW_CTRL_REG2 = 0x21 # Control register 2 __REG_RW_CTRL_REG3 = 0x22 # Control register 3 __REG_RW_CTRL_REG4 = 0x23 # Control register 4 __REG_RW_CTRL_REG5 = 0x24 # Control register 5 __REG_RW_REFERENCE = 0x25 # Reference value for interrupt generation __REG_R_OUT_TEMP = 0x26 # Output temperature __REG_R_STATUS_REG = 0x27 # Status register __REG_R_OUT_X_L = 0x28 # X-axis angular data rate LSB __REG_R_OUT_X_H = 0x29 # X-axis angular data rate MSB __REG_R_OUT_Y_L = 0x2a # Y-axis angular data rate LSB __REG_R_OUT_Y_H = 0x2b # Y-axis angular data rate MSB __REG_R_OUT_Z_L = 0x2c # Z-axis angular data rate LSB __REG_R_OUT_Z_H = 0x2d # Z-axis angular data rate MSB __REG_RW_FIFO_CTRL_REG = 0x2e # Fifo control register __REG_R_FIFO_SRC_REG = 0x2f # Fifo src register __REG_RW_INT1_CFG_REG = 0x30 # Interrupt 1 configuration register __REG_R_INT1_SRC_REG = 0x31 # Interrupt source register __REG_RW_INT1_THS_XH = 0x32 # Interrupt 1 threshold level X MSB register __REG_RW_INT1_THS_XL = 0x33 # Interrupt 1 threshold level X LSB register __REG_RW_INT1_THS_YH = 0x34 # Interrupt 1 threshold level Y MSB register __REG_RW_INT1_THS_YL = 0x35 # Interrupt 1 threshold level Y LSB register __REG_RW_INT1_THS_ZH = 0x36 # Interrupt 1 threshold level Z MSB register __REG_RW_INT1_THS_ZL = 0x37 # Interrupt 1 threshold level Z LSB register __REG_RW_INT1_DURATION = 0x38 # Interrupt 1 duration register __MASK_CTRL_REG1_Xen = 0x01 # X enable __MASK_CTRL_REG1_Yen = 0x02 # Y enable __MASK_CTRL_REG1_Zen = 0x04 # Z enable __MASK_CTRL_REG1_PD = 0x08 # Power-down __MASK_CTRL_REG1_BW = 0x30 # Bandwidth __MASK_CTRL_REG1_DR = 0xc0 # Output data rate __MASK_CTRL_REG2_HPCF = 0x0f # High pass filter cutoff frequency __MASK_CTRL_REG2_HPM = 0x30 # High pass filter mode selection __MASK_CTRL_REG3_I2_EMPTY = 0x01 # FIFO empty interrupt on DRDY/INT2 __MASK_CTRL_REG3_I2_ORUN = 0x02 # FIFO overrun interrupt on DRDY/INT2 __MASK_CTRL_REG3_I2_WTM = 0x04 # FIFO watermark interrupt on DRDY/INT2 __MASK_CTRL_REG3_I2_DRDY = 0x08 # Date-ready on DRDY/INT2 __MASK_CTRL_REG3_PP_OD = 0x10 # Push-pull / Open-drain __MASK_CTRL_REG3_H_LACTIVE = 0x20 # Interrupt active configuration on INT1 __MASK_CTRL_REG3_I1_BOOT = 0x40 # Boot status available on INT1 __MASK_CTRL_REG3_I1_Int1 = 0x80 # Interrupt enabled on INT1 __MASK_CTRL_REG4_SIM = 0x01 # SPI Serial interface selection __MASK_CTRL_REG4_FS = 0x30 # Full scale selection __MASK_CTRL_REG4_BLE = 0x40 # Big/little endian selection __MASK_CTRL_REG4_BDU = 0x80 # Block data update __MASK_CTRL_REG5_OUT_SEL = 0x03 # Out selection configuration __MASK_CTRL_REG5_INT_SEL = 0xc0 # INT1 selection configuration __MASK_CTRL_REG5_HPEN = 0x10 # High-pass filter enable __MASK_CTRL_REG5_FIFO_EN = 0x40 # Fifo enable __MASK_CTRL_REG5_BOOT = 0x80 # Reboot memory content __MASK_STATUS_REG_ZYXOR = 0x80 # Z, Y, X axis overrun __MASK_STATUS_REG_ZOR = 0x40 # Z axis overrun __MASK_STATUS_REG_YOR = 0x20 # Y axis overrun __MASK_STATUS_REG_XOR = 0x10 # X axis overrun __MASK_STATUS_REG_ZYXDA = 0x08 # Z, Y, X data available __MASK_STATUS_REG_ZDA = 0x04 # Z data available __MASK_STATUS_REG_YDA = 0x02 # Y data available __MASK_STATUS_REG_XDA = 0x01 # X data available __MASK_FIFO_CTRL_REG_FM = 0xe0 # Fifo mode selection __MASK_FIFO_CTRL_REG_WTM = 0x1f # Fifo treshold - watermark level __MASK_FIFO_SRC_REG_FSS = 0x1f # Fifo stored data level __MASK_FIFO_SRC_REG_EMPTY = 0x20 # Fifo empty bit __MASK_FIFO_SRC_REG_OVRN = 0x40 # Overrun status __MASK_FIFO_SRC_REG_WTM = 0x80 # Watermark status __MASK_INT1_CFG_ANDOR = 0x80 # And/Or configuration of interrupt events __MASK_INT1_CFG_LIR = 0x40 # Latch interrupt request __MASK_INT1_CFG_ZHIE = 0x20 # Enable interrupt generation on Z high __MASK_INT1_CFG_ZLIE = 0x10 # Enable interrupt generation on Z low __MASK_INT1_CFG_YHIE = 0x08 # Enable interrupt generation on Y high __MASK_INT1_CFG_YLIE = 0x04 # Enable interrupt generation on Y low __MASK_INT1_CFG_XHIE = 0x02 # Enable interrupt generation on X high __MASK_INT1_CFG_XLIE = 0x01 # Enable interrupt generation on X low __MASK_INT1_SRC_IA = 0x40 # Int1 active __MASK_INT1_SRC_ZH = 0x20 # Int1 source Z high __MASK_INT1_SRC_ZL = 0x10 # Int1 source Z low __MASK_INT1_SRC_YH = 0x08 # Int1 source Y high __MASK_INT1_SRC_YL = 0x04 # Int1 source Y low __MASK_INT1_SRC_XH = 0x02 # Int1 source X high __MASK_INT1_SRC_XL = 0x01 # Int1 source X low __MASK_INT1_THS_H = 0x7f # MSB __MASK_INT1_THS_L = 0xff # LSB __MASK_INT1_DURATION_WAIT = 0x80 # Wait number of samples or not __MASK_INT1_DURATION_D = 0x7f # Duration of int1 to be recognized PowerModeEnum = [ 'Power-down', 'Sleep', 'Normal'] __PowerModeDict = { PowerModeEnum[0] : 0, PowerModeEnum[1] : 1, PowerModeEnum[2] : 2 } EnabledEnum = [ False, True ] __EnabledDict = { EnabledEnum[0] : 0, EnabledEnum[1] : 1} LevelEnum = [ 'High', 'Low' ] __LevelDict = { LevelEnum[0] : 0, LevelEnum[1] : 1 } OutputEnum = [ 'Push-pull', 'Open drain' ] __OutputDict = { OutputEnum[0] : 0, OutputEnum[1] : 1 } SimModeEnum = [ '4-wire', '3-wire' ] __SimModeDict = { SimModeEnum[0] : 0, SimModeEnum[1] : 1 } FullScaleEnum = [ '250dps', '500dps', '2000dps' ] __FullScaleDict = { FullScaleEnum[0] : 0x00, FullScaleEnum[1] : 0x01, FullScaleEnum[2] : 0x02} BigLittleEndianEnum = [ 'Big endian', 'Little endian' ] __BigLittleEndianDict = { BigLittleEndianEnum[0] : 0x00, BigLittleEndianEnum[1] : 0x01 } BlockDataUpdateEnum = [ 'Continous update', 'Output registers not updated until reading' ] __BlockDataUpdateDict = { BlockDataUpdateEnum[0] : 0x00, BlockDataUpdateEnum[1] : 0x01 } OutSelEnum = [ 'LPF1', 'HPF', 'LPF2' ] __OutSelDict = { OutSelEnum[0] : 0x00, OutSelEnum[1] : 0x01, OutSelEnum[2] : 0x02 } IntSelEnum = [ 'LPF1', 'HPF', 'LPF2' ] __IntSelDict = { IntSelEnum[0] : 0x00, IntSelEnum[1] : 0x01, IntSelEnum[2] : 0x02 } BootModeEnum = [ 'Normal', 'Reboot memory content' ] __BootModeDict = { BootModeEnum[0] : 0x00, BootModeEnum[1] : 0x01 } FifoModeEnum = [ 'Bypass', 'FIFO', 'Stream', 'Stream-to-Fifo', 'Bypass-to-Stream' ] __FifoModeDict = { FifoModeEnum[0] : 0x00, FifoModeEnum[1] : 0x01, FifoModeEnum[2] : 0x02, FifoModeEnum[3] : 0x03, FifoModeEnum[4] : 0x04 } AndOrEnum = [ 'And', 'Or' ] __AndOrDict = { AndOrEnum[0] : 0x00, AndOrEnum[1] : 0x01 } DataRateValues = [95, 190, 380, 760] BandWidthValues = [12.5, 20, 25, 30, 35, 50, 70, 100] __DRBW = { DataRateValues[0] : { BandWidthValues[0]:0x00, BandWidthValues[2]:0x01}, DataRateValues[1] : { BandWidthValues[0]:0x04, BandWidthValues[2]:0x05, BandWidthValues[5]:0x06, BandWidthValues[6]:0x07}, DataRateValues[2] : { BandWidthValues[1]:0x08, BandWidthValues[2]:0x09, BandWidthValues[5]:0x0a, BandWidthValues[7]:0x0b}, DataRateValues[3] : { BandWidthValues[3]:0x0c, BandWidthValues[4]:0x0d, BandWidthValues[5]:0x0e, BandWidthValues[7]:0x0f} } HighPassFilterCutOffFrequencyValues = [51.4, 27, 13.5, 7.2, 3.5, 1.8, 0.9, 0.45, 0.18, 0.09, 0.045, 0.018, 0.009] __HPCF = { HighPassFilterCutOffFrequencyValues[0] : { DataRateValues[3]:0x00 }, HighPassFilterCutOffFrequencyValues[1] : { DataRateValues[2]:0x00, DataRateValues[3]:0x01 }, HighPassFilterCutOffFrequencyValues[2] : { DataRateValues[1]:0x00, DataRateValues[2]:0x01, DataRateValues[3]:0x02 }, HighPassFilterCutOffFrequencyValues[3] : { DataRateValues[0]:0x00, DataRateValues[1]:0x01, DataRateValues[2]:0x02, DataRateValues[3]:0x03 }, HighPassFilterCutOffFrequencyValues[4] : { DataRateValues[0]:0x01, DataRateValues[1]:0x02, DataRateValues[2]:0x03, DataRateValues[3]:0x04 }, HighPassFilterCutOffFrequencyValues[5] : { DataRateValues[0]:0x02, DataRateValues[1]:0x03, DataRateValues[2]:0x04, DataRateValues[3]:0x05 }, HighPassFilterCutOffFrequencyValues[6] : { DataRateValues[0]:0x03, DataRateValues[1]:0x04, DataRateValues[2]:0x05, DataRateValues[3]:0x06 }, HighPassFilterCutOffFrequencyValues[7] : { DataRateValues[0]:0x04, DataRateValues[1]:0x05, DataRateValues[2]:0x06, DataRateValues[3]:0x07 }, HighPassFilterCutOffFrequencyValues[8] : { DataRateValues[0]:0x05, DataRateValues[1]:0x06, DataRateValues[2]:0x07, DataRateValues[3]:0x08 }, HighPassFilterCutOffFrequencyValues[9] : { DataRateValues[0]:0x06, DataRateValues[1]:0x07, DataRateValues[2]:0x08, DataRateValues[3]:0x09 }, HighPassFilterCutOffFrequencyValues[10] : { DataRateValues[0]:0x07, DataRateValues[1]:0x08, DataRateValues[2]:0x09 }, HighPassFilterCutOffFrequencyValues[11] : { DataRateValues[0]:0x08, DataRateValues[1]:0x09 }, HighPassFilterCutOffFrequencyValues[12] : { DataRateValues[0]:0x09 } } HighPassFilterModes = ['Normal with reset.','Reference signal for filtering.','Normal.','Autoreset on interrupt.'] __HpmDict = { HighPassFilterModes[0]:0x0, HighPassFilterModes[1]:0x1, HighPassFilterModes[2]:0x2, HighPassFilterModes[3]:0x3 } # For calibration purposes meanX = 0 maxX = 0 minX = 0 meanY = 0 maxY = 0 minY = 0 meanZ = 0 maxZ = 0 minZ = 0 gain = 1 def Init(self): """Call this method after configuratin and before doing measurements""" print("Initiating...") if (self.Get_FullScale_Value() == self.FullScaleEnum[0]): self.gain = 0.00875 elif (self.Get_FullScale_Value() == self.FullScaleEnum[1]): self.gain = 0.0175 elif (self.Get_FullScale_Value() == self.FullScaleEnum[2]): self.gain = 0.07 print("Gain set to:{0}".format(self.gain)) def CalibrateX(self): """Returns (min, mean, max)""" print("Calibrating axis X, please do not move sensor...") buff = [] for t in range(60): while self.Get_AxisDataAvailable_Value()[0] == 0: time.sleep(0.0001) buff.append(self.Get_RawOutX_Value()) self.meanX = numpy.mean(buff) self.maxX = max(buff) self.minX = min(buff) print("Done: (min={0};mean={1};max={2})".format(self.minX, self.meanX, self.maxX)) def CalibrateY(self): """Returns (min, mean, max)""" print("Calibrating axis Y, please do not move sensor...") buff = [] for t in range(60): while self.Get_AxisDataAvailable_Value()[1] == 0: time.sleep(0.0001) buff.append(self.Get_RawOutY_Value()) self.meanY = numpy.mean(buff) self.maxY = max(buff) self.minY = min(buff) print("Done: (min={0};mean={1};max={2})".format(self.minY, self.meanY, self.maxY)) def CalibrateZ(self): """Returns (min, mean, max)""" print("Calibrating axis Z, please do not move sensor...") buff = [] for t in range(60): while self.Get_AxisDataAvailable_Value()[2] == 0: time.sleep(0.0001) buff.append(self.Get_RawOutZ_Value()) self.meanZ = numpy.mean(buff) self.maxZ = max(buff) self.minZ = min(buff) print("Done: (min={0};mean={1};max={2})".format(self.minZ, self.meanZ, self.maxZ)) def Calibrate(self): self.CalibrateX() self.CalibrateY() self.CalibrateZ() def ReturnConfiguration(self): return [ [ self.Get_DeviceId_Value.__doc__, self.Get_DeviceId_Value()], [ self.Get_DataRateAndBandwidth.__doc__, self.Get_DataRateAndBandwidth()], [ self.Get_AxisX_Enabled.__doc__, self.Get_AxisX_Enabled()], [ self.Get_AxisY_Enabled.__doc__, self.Get_AxisY_Enabled()], [ self.Get_AxisZ_Enabled.__doc__, self.Get_AxisZ_Enabled()], [ self.Get_PowerMode.__doc__, self.Get_PowerMode()], [ self.Get_HighPassCutOffFreq.__doc__, self.Get_HighPassCutOffFreq()], [ self.Get_INT1_Enabled.__doc__, self.Get_INT1_Enabled()], [ self.Get_BootStatusOnINT1_Enabled.__doc__, self.Get_BootStatusOnINT1_Enabled()], [ self.Get_ActiveConfINT1_Level.__doc__, self.Get_ActiveConfINT1_Level()], [ self.Get_PushPullOrOpenDrain_Value.__doc__, self.Get_PushPullOrOpenDrain_Value()], [ self.Get_DataReadyOnINT2_Enabled.__doc__, self.Get_DataReadyOnINT2_Enabled()], [ self.Get_FifoWatermarkOnINT2_Enabled.__doc__, self.Get_FifoWatermarkOnINT2_Enabled()], [ self.Get_FifoOverrunOnINT2_Enabled.__doc__, self.Get_FifoOverrunOnINT2_Enabled()], [ self.Get_FifoEmptyOnINT2_Enabled.__doc__, self.Get_FifoEmptyOnINT2_Enabled()], [ self.Get_SpiMode_Value.__doc__, self.Get_SpiMode_Value()], [ self.Get_FullScale_Value.__doc__, self.Get_FullScale_Value()], [ self.Get_BigLittleEndian_Value.__doc__, self.Get_BigLittleEndian_Value()], [ self.Get_BlockDataUpdate_Value.__doc__, self.Get_BlockDataUpdate_Value()], [ self.Get_BootMode_Value.__doc__, self.Get_BootMode_Value()], [ self.Get_Fifo_Enabled.__doc__, self.Get_Fifo_Enabled()], [ self.Get_HighPassFilter_Enabled.__doc__, self.Get_HighPassFilter_Enabled()], [ self.Get_INT1Selection_Value.__doc__, self.Get_INT1Selection_Value()], [ self.Get_OutSelection_Value.__doc__, self.Get_OutSelection_Value()], [ self.Get_Reference_Value.__doc__, self.Get_Reference_Value()], [ self.Get_AxisOverrun_Value.__doc__, self.Get_AxisOverrun_Value()], [ self.Get_AxisDataAvailable_Value.__doc__, self.Get_AxisDataAvailable_Value()], [ self.Get_FifoThreshold_Value.__doc__, self.Get_FifoThreshold_Value()], [ self.Get_FifoMode_Value.__doc__, self.Get_FifoMode_Value()], [ self.Get_FifoStoredDataLevel_Value.__doc__, self.Get_FifoStoredDataLevel_Value()], [ self.Get_IsFifoEmpty_Value.__doc__, self.Get_IsFifoEmpty_Value()], [ self.Get_IsFifoFull_Value.__doc__, self.Get_IsFifoFull_Value()], [ self.Get_IsFifoGreaterOrEqualThanWatermark_Value.__doc__, self.Get_IsFifoGreaterOrEqualThanWatermark_Value()], [ self.Get_Int1Combination_Value.__doc__, self.Get_Int1Combination_Value() ], [ self.Get_Int1LatchRequest_Enabled.__doc__, self.Get_Int1LatchRequest_Enabled() ], [ self.Get_Int1GenerationOnZHigh_Enabled.__doc__, self.Get_Int1GenerationOnZHigh_Enabled() ], [ self.Get_Int1GenerationOnZLow_Enabled.__doc__, self.Get_Int1GenerationOnZLow_Enabled() ], [ self.Get_Int1GenerationOnYHigh_Enabled.__doc__, self.Get_Int1GenerationOnYHigh_Enabled() ], [ self.Get_Int1GenerationOnYLow_Enabled.__doc__, self.Get_Int1GenerationOnYLow_Enabled() ], [ self.Get_Int1GenerationOnXHigh_Enabled.__doc__, self.Get_Int1GenerationOnXHigh_Enabled() ], [ self.Get_Int1GenerationOnXLow_Enabled.__doc__, self.Get_Int1GenerationOnXLow_Enabled() ], [ self.Get_Int1Active_Value.__doc__, self.Get_Int1Active_Value() ], [ self.Get_ZHighEventOccured_Value.__doc__, self.Get_ZHighEventOccured_Value() ], [ self.Get_ZLowEventOccured_Value.__doc__, self.Get_ZLowEventOccured_Value() ], [ self.Get_YHighEventOccured_Value.__doc__, self.Get_YHighEventOccured_Value() ], [ self.Get_YLowEventOccured_Value.__doc__, self.Get_YLowEventOccured_Value() ], [ self.Get_XHighEventOccured_Value.__doc__, self.Get_XHighEventOccured_Value() ], [ self.Get_XLowEventOccured_Value.__doc__, self.Get_XLowEventOccured_Value() ], [ self.Get_Int1Threshold_Values.__doc__, self.Get_Int1Threshold_Values() ], [ self.Get_Int1DurationWait_Enabled.__doc__, self.Get_Int1DurationWait_Enabled() ], [ self.Get_Int1Duration_Value.__doc__, self.Get_Int1Duration_Value() ] ] def Get_DeviceId_Value(self): """Device Id.""" return self.__readFromRegister(self.__REG_R_WHO_AM_I, 0xff) def Set_AxisX_Enabled(self, enabled): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG1, self.__MASK_CTRL_REG1_Xen, enabled, self.__EnabledDict, 'EnabledEnum') def Get_AxisX_Enabled(self): """Axis X enabled.""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG1, self.__MASK_CTRL_REG1_Xen, self.__EnabledDict) def Set_AxisY_Enabled(self, enabled): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG1, self.__MASK_CTRL_REG1_Yen, enabled, self.__EnabledDict, 'EnabledEnum') def Get_AxisY_Enabled(self): """Axis Y enabled.""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG1, self.__MASK_CTRL_REG1_Yen, self.__EnabledDict) def Set_AxisZ_Enabled(self, enabled): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG1, self.__MASK_CTRL_REG1_Zen, enabled, self.__EnabledDict, 'EnabledEnum') def Get_AxisZ_Enabled(self): """Axis Z enabled.""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG1, self.__MASK_CTRL_REG1_Zen, self.__EnabledDict) def Set_PowerMode(self, mode): if mode not in self.__PowerModeDict.keys(): raise Exception('Value:' + str(mode) + ' is not in range of: PowerModeEnum') if self.__PowerModeDict[mode] == 0: # Power-down self.__writeToRegister(self.__REG_RW_CTRL_REG1, self.__MASK_CTRL_REG1_PD, 0) elif self.__PowerModeDict[mode] == 1: # Sleep self.__writeToRegister(self.__REG_RW_CTRL_REG1, self.__MASK_CTRL_REG1_PD | self.__MASK_CTRL_REG1_Zen | self.__MASK_CTRL_REG1_Yen | self.__MASK_CTRL_REG1_Xen, 8) elif self.__PowerModeDict[mode] == 2: # Normal self.__writeToRegister(self.__REG_RW_CTRL_REG1, self.__MASK_CTRL_REG1_PD, 1) def Get_PowerMode(self): """Power mode.""" powermode = self.__readFromRegister(self.__REG_RW_CTRL_REG1, self.__MASK_CTRL_REG1_PD | self.__MASK_CTRL_REG1_Xen | self.__MASK_CTRL_REG1_Yen | self.__MASK_CTRL_REG1_Zen) print(bin(powermode)) dictval = 4 if not bitOps.CheckBit(powermode, 3): dictval = 0 elif powermode == 0b1000: dictval = 1 elif bitOps.CheckBit(powermode, 3): dictval = 2 for key in self.__PowerModeDict.keys(): if self.__PowerModeDict[key] == dictval: return key def Print_DataRateAndBandwidth_AvailableValues(self): for dr in self.__DRBW.keys(): print('Output data rate: ' + dr + '[Hz]') for bw in self.__DRBW[dr].keys(): print(' Bandwidth: ' + bw + ' (DRBW=' +'0b' + bin(self.__DRBW[dr][bw])[2:].zfill(4) +')') def Set_DataRateAndBandwidth(self, datarate, bandwidth): if datarate not in self.__DRBW.keys(): raise Exception('Data rate:' + str(datarate) + ' not in range of data rate values.') if bandwidth not in self.__DRBW[datarate].keys(): raise Exception('Bandwidth: ' + str(bandwidth) + ' cannot be assigned to data rate: ' + str(datarate)) bits = self.__DRBW[datarate][bandwidth] self.__writeToRegister(self.__REG_RW_CTRL_REG1, self.__MASK_CTRL_REG1_DR | self.__MASK_CTRL_REG1_BW, bits) def Get_DataRateAndBandwidth(self): """Data rate and bandwidth.""" current = self.__readFromRegister(self.__REG_RW_CTRL_REG1, self.__MASK_CTRL_REG1_DR | self.__MASK_CTRL_REG1_BW) for dr in self.__DRBW.keys(): for bw in self.__DRBW[dr].keys(): if self.__DRBW[dr][bw] == current: return (dr, bw) def Print_HighPassFilterCutOffFrequency_AvailableValues(self): for freq in self.__HPCF.keys(): print('High pass cut off: ' + freq + '[Hz]') for odr in self.__HPCF[freq].keys(): print(' Output data rate: ' + odr + ' (HPCF=' + '0b' + bin(self.__HPCF[freq][odr])[2:].zfill(4) + ')') def Set_HighPassCutOffFreq(self, freq): if freq not in self.__HPCF.keys(): raise Exception('Frequency:' + str(freq) + ' is not in range of high pass frequency cut off values.') datarate = self.Get_DataRateAndBandwidth()[0] if datarate not in self.__HPCF[freq].keys(): raise Exception('Frequency: ' + str(freq) + ' cannot be assigned to data rate: ' + str(datarate)) bits = self.__HPCF[freq][datarate] self.__writeToRegister(self.__REG_RW_CTRL_REG2, self.__MASK_CTRL_REG2_HPCF, bits) def Get_HighPassCutOffFreq(self): """Cut off frequency.""" current = self.__readFromRegister(self.__REG_RW_CTRL_REG2, self.__MASK_CTRL_REG2_HPCF) datarate = self.Get_DataRateAndBandwidth()[0] for freq in self.__HPCF.keys(): for dr in self.__HPCF[freq]: if dr == datarate: if self.__HPCF[freq][datarate] == current: return freq def Set_HighPassFilterMode(self, mode): if mode not in self.__HpmDict.keys(): raise Exception('EnabledEnum:' + str(mode) + ' is not in range of high pass frequency modes.') bits = self.__HpmDict[mode] self.__writeToRegister(self.__REG_RW_CTRL_REG2, self.__MASK_CTRL_REG2_HPM, bits) def Get_HighPassFilterMode(self): """High pass filter mode""" current = self.__readFromRegister(self.__REG_RW_CTRL_REG2, self.__MASK_CTRL_REG2_HPM) for mode in self.__HpmDict.keys(): if self.__HpmDict[mode] == current: return mode def Set_INT1_Enabled(self, enabled): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_I1_Int1, enabled, self.__EnabledDict, 'EnabledEnum') def Get_INT1_Enabled(self): """INT1 Enabled""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_I1_Int1, self.__EnabledDict) def Set_BootStatusOnINT1_Enabled(self, enabled): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_I1_BOOT, enabled, self.__EnabledDict, 'EnabledEnum') def Get_BootStatusOnINT1_Enabled(self): """Boot status available on INT1""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_I1_BOOT, self.__EnabledDict) def Set_ActiveConfINT1_Level(self, level): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_H_LACTIVE, level, self.__LevelDict, 'LevelEnum') def Get_ActiveConfINT1_Level(self): """Interrupt active configuration on INT1""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_H_LACTIVE, self.__LevelDict) def Set_PushPullOrOpenDrain_Value(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_PP_OD, value, self.__OutputDict, 'OutputEnum') def Get_PushPullOrOpenDrain_Value(self): """Push-pull/open drain""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_PP_OD, self.__OutputDict) def Set_DataReadyOnINT2_Enabled(self, enabled): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_I2_DRDY, enabled, self.__EnabledDict, 'EnabledEnum') def Get_DataReadyOnINT2_Enabled(self): """Date-ready on DRDY/INT2""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_I2_DRDY, self.__EnabledDict) def Set_FifoWatermarkOnINT2_Enabled(self, enabled): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_I2_WTM, enabled, self.__EnabledDict, 'EnabledEnum') def Get_FifoWatermarkOnINT2_Enabled(self): """FIFO watermark interrupt on DRDY/INT2""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_I2_WTM, self.__EnabledDict) def Set_FifoOverrunOnINT2_Enabled(self, enabled): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_I2_ORUN, enabled, self.__EnabledDict, 'EnabledEnum') def Get_FifoOverrunOnINT2_Enabled(self): """FIFO overrun interrupt in DRDY/INT2""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_I2_ORUN, self.__EnabledDict) def Set_FifoEmptyOnINT2_Enabled(self, enabled): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_I2_EMPTY, enabled, self.__EnabledDict, 'EnabledEnum') def Get_FifoEmptyOnINT2_Enabled(self): """FIFO empty interrupt on DRDY/INT2""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG3, self.__MASK_CTRL_REG3_I2_EMPTY, self.__EnabledDict) def Set_SpiMode_Value(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG4, self.__MASK_CTRL_REG4_SIM, value, self.__SimModeDict, 'SimModeEnum') def Get_SpiMode_Value(self): """SPI mode""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG4, self.__MASK_CTRL_REG4_SIM, self.__SimModeDict) def Set_FullScale_Value(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG4, self.__MASK_CTRL_REG4_FS, value, self.__FullScaleDict, 'FullScaleEnum') def Get_FullScale_Value(self): """Full scale selection""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG4, self.__MASK_CTRL_REG4_FS, self.__FullScaleDict) def Set_BigLittleEndian_Value(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG4, self.__MASK_CTRL_REG4_BLE, value, self.__BigLittleEndianDict, 'BigLittleEndianEnum') def Get_BigLittleEndian_Value(self): """Big/Little endian""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG4, self.__MASK_CTRL_REG4_BLE, self.__BigLittleEndianDict) def Set_BlockDataUpdate_Value(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG4, self.__MASK_CTRL_REG4_BDU, value, self.__BlockDataUpdateDict, 'BlockDataUpdateEnum') def Get_BlockDataUpdate_Value(self): """Block data update""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG4, self.__MASK_CTRL_REG4_BDU, self.__BlockDataUpdateDict) def Set_BootMode_Value(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG5, self.__MASK_CTRL_REG5_BOOT, value, self.__BootModeDict, 'BootModeEnum') def Get_BootMode_Value(self): """Boot mode""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG5, self.__MASK_CTRL_REG5_BOOT, self.__BootModeDict) def Set_Fifo_Enabled(self, enabled): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG5, self.__MASK_CTRL_REG5_FIFO_EN, enabled, self.__EnabledDict, 'EnabledEnum') def Get_Fifo_Enabled(self): """Fifo enabled""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG5, self.__MASK_CTRL_REG5_FIFO_EN, self.__EnabledDict) def Set_HighPassFilter_Enabled(self, enabled): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG5, self.__MASK_CTRL_REG5_HPEN, enabled, self.__EnabledDict, 'EnabledEnum') def Get_HighPassFilter_Enabled(self): """High pass filter enabled""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG5, self.__MASK_CTRL_REG5_HPEN, self.__EnabledDict) def Set_INT1Selection_Value(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG5, self.__MASK_CTRL_REG5_INT_SEL, value, self.__IntSelDict, 'IntSelEnum') def Get_INT1Selection_Value(self): """INT1 selection configuration""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG5, self.__MASK_CTRL_REG5_INT_SEL, self.__IntSelDict) def Set_OutSelection_Value(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_CTRL_REG5, self.__MASK_CTRL_REG5_OUT_SEL, value, self.__OutSelDict, 'OutSelEnum') def Get_OutSelection_Value(self): """Out selection configuration""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_CTRL_REG5, self.__MASK_CTRL_REG5_OUT_SEL, self.__OutSelDict) def Set_Reference_Value(self, value): self.__writeToRegister(self.__REG_RW_REFERENCE, 0xff, value) def Get_Reference_Value(self): """Reference value for interrupt generation""" return self.__readFromRegister(self.__REG_RW_REFERENCE, 0xff) def Get_OutTemp_Value(self): """Output temperature""" return self.__readFromRegister(self.__REG_R_OUT_TEMP, 0xff) def Get_AxisOverrun_Value(self): """(X, Y, Z) axis overrun""" zor = 0 yor = 0 xor = 0 if self.__readFromRegister(self.__REG_R_STATUS_REG, self.__MASK_STATUS_REG_ZYXOR) == 0x01: zor = self.__readFromRegister(self.__REG_R_STATUS_REG, self.__MASK_STATUS_REG_ZOR) yor = self.__readFromRegister(self.__REG_R_STATUS_REG, self.__MASK_STATUS_REG_YOR) xor = self.__readFromRegister(self.__REG_R_STATUS_REG, self.__MASK_STATUS_REG_XOR) return (xor, yor, zor) def Get_AxisDataAvailable_Value(self): """(X, Y, Z) data available""" zda = 0 yda = 0 xda = 0 if self.__readFromRegister(self.__REG_R_STATUS_REG, self.__MASK_STATUS_REG_ZYXDA) == 0x01: zda = self.__readFromRegister(self.__REG_R_STATUS_REG, self.__MASK_STATUS_REG_ZDA) yda = self.__readFromRegister(self.__REG_R_STATUS_REG, self.__MASK_STATUS_REG_YDA) xda = self.__readFromRegister(self.__REG_R_STATUS_REG, self.__MASK_STATUS_REG_XDA) return (xda, yda, zda) def Get_RawOutX_Value(self): """Raw X angular speed data""" l = self.__readFromRegister(self.__REG_R_OUT_X_L, 0xff) h_u2 = self.__readFromRegister(self.__REG_R_OUT_X_H, 0xff) h = bitOps.TwosComplementToByte(h_u2) if (h < 0): return (h*256 - l) * self.gain elif (h >= 0): return (h*256 + l) * self.gain def Get_RawOutY_Value(self): """Raw Y angular speed data""" l = self.__readFromRegister(self.__REG_R_OUT_Y_L, 0xff) h_u2 = self.__readFromRegister(self.__REG_R_OUT_Y_H, 0xff) h = bitOps.TwosComplementToByte(h_u2) if (h < 0): return (h*256 - l) * self.gain elif (h >= 0): return (h*256 + l) * self.gain def Get_RawOutZ_Value(self): """Raw Z angular speed data""" l = self.__readFromRegister(self.__REG_R_OUT_Z_L, 0xff) h_u2 = self.__readFromRegister(self.__REG_R_OUT_Z_H, 0xff) h = bitOps.TwosComplementToByte(h_u2) if (h < 0): return (h*256 - l) * self.gain elif (h >= 0): return (h*256 + l) * self.gain def Get_RawOut_Value(self): """Raw [X, Y, Z] values of angular speed""" return [self.Get_RawOutX_Value(), self.Get_RawOutY_Value(), self.Get_RawOutZ_Value()] def Get_CalOutX_Value(self): """Calibrated X angular speed data""" x = self.Get_RawOutX_Value() if(x >= self.minX and x <= self.maxX): return 0 else: return x - self.meanX def Get_CalOutY_Value(self): """Calibrated Y angular speed data""" y = self.Get_RawOutY_Value() if(y >= self.minY and y <= self.maxY): return 0 else: return y - self.meanY def Get_CalOutZ_Value(self): """Calibrated Z angular speed data""" z = self.Get_RawOutZ_Value() if(z >= self.minZ and z <= self.maxZ): return 0 else: return z - self.meanZ def Get_CalOut_Value(self): """Calibrated [X, Y, Z] value of angular speed, calibrated""" return [self.Get_CalOutX_Value(), self.Get_CalOutY_Value(), self.Get_CalOutZ_Value()] def Set_FifoThreshold_Value(self, value): self.__writeToRegister(self.__REG_RW_FIFO_CTRL_REG, self.__MASK_FIFO_CTRL_REG_WTM, value) def Get_FifoThreshold_Value(self): """Fifo threshold - watermark level""" return self.__readFromRegister(self.__REG_RW_FIFO_CTRL_REG, self.__MASK_FIFO_CTRL_REG_WTM) def Set_FifoMode_Value(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_FIFO_CTRL_REG, self.__MASK_FIFO_CTRL_REG_FM, value, self.__FifoModeDict, 'FifoModeEnum') def Get_FifoMode_Value(self): """Fifo mode""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_FIFO_CTRL_REG, self.__MASK_FIFO_CTRL_REG_FM, self.__FifoModeDict) def Get_FifoStoredDataLevel_Value(self): """Fifo stored data level""" return self.__readFromRegister(self.__REG_R_FIFO_SRC_REG, self.__MASK_FIFO_SRC_REG_FSS) def Get_IsFifoEmpty_Value(self): """Fifo empty""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_R_FIFO_SRC_REG, self.__MASK_FIFO_SRC_REG_EMPTY, self.__EnabledDict) def Get_IsFifoFull_Value(self): """Fifo full""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_R_FIFO_SRC_REG, self.__MASK_FIFO_SRC_REG_OVRN, self.__EnabledDict) def Get_IsFifoGreaterOrEqualThanWatermark_Value(self): """Fifo filling is greater or equal than watermark level""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_R_FIFO_SRC_REG, self.__MASK_FIFO_SRC_REG_WTM, self.__EnabledDict) def Set_Int1Combination_Value(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_ANDOR, value, self.__AndOrDict, 'AndOrEnum') def Get_Int1Combination_Value(self): """Interrupt combination""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_ANDOR, self.__AndOrDict) def Set_Int1LatchRequest_Enabled(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_LIR, value, self.__EnabledDict, 'EnabledEnum') def Get_Int1LatchRequest_Enabled(self): """Latch interrupt request""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_LIR, self.__EnabledDict) def Set_Int1GenerationOnZHigh_Enabled(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_ZHIE, value, self.__EnabledDict, 'EnabledEnum') def Get_Int1GenerationOnZHigh_Enabled(self): """Int 1 generation on Z higher than threshold""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_ZHIE, self.__EnabledDict) def Set_Int1GenerationOnZLow_Enabled(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_ZLIE, value, self.__EnabledDict, 'EnabledEnum') def Get_Int1GenerationOnZLow_Enabled(self): """Int 1 generation on Z lower than threshold""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_ZLIE, self.__EnabledDict) def Set_Int1GenerationOnYHigh_Enabled(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_YHIE, value, self.__EnabledDict, 'EnabledEnum') def Get_Int1GenerationOnYHigh_Enabled(self): """Int 1 generation on Y higher than threshold""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_YHIE, self.__EnabledDict) def Set_Int1GenerationOnYLow_Enabled(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_YLIE, value, self.__EnabledDict, 'EnabledEnum') def Get_Int1GenerationOnYLow_Enabled(self): """Int 1 generation on Y lower than threshold""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_YLIE, self.__EnabledDict) def Set_Int1GenerationOnXHigh_Enabled(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_XHIE, value, self.__EnabledDict, 'EnabledEnum') def Get_Int1GenerationOnXHigh_Enabled(self): """Int 1 generation on X higher than threshold""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_XHIE, self.__EnabledDict) def Set_Int1GenerationOnXLow_Enabled(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_XLIE, value, self.__EnabledDict, 'EnabledEnum') def Get_Int1GenerationOnXLow_Enabled(self): """Int 1 generation on X lower than threshold""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_INT1_CFG_REG, self.__MASK_INT1_CFG_XLIE, self.__EnabledDict) def Get_Int1Active_Value(self): """Int1 active""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_R_INT1_SRC_REG, self.__MASK_INT1_SRC_IA, self.__EnabledDict) def Get_ZHighEventOccured_Value(self): """Z high event occured""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_R_INT1_SRC_REG, self.__MASK_INT1_SRC_ZH, self.__EnabledDict) def Get_ZLowEventOccured_Value(self): """Z low event occured""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_R_INT1_SRC_REG, self.__MASK_INT1_SRC_ZL, self.__EnabledDict) def Get_YHighEventOccured_Value(self): """Y high event occured""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_R_INT1_SRC_REG, self.__MASK_INT1_SRC_YH, self.__EnabledDict) def Get_YLowEventOccured_Value(self): """Y low event occured""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_R_INT1_SRC_REG, self.__MASK_INT1_SRC_YL, self.__EnabledDict) def Get_XHighEventOccured_Value(self): """X high event occured""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_R_INT1_SRC_REG, self.__MASK_INT1_SRC_XH, self.__EnabledDict) def Get_XLowEventOccured_Value(self): """X low event occured""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_R_INT1_SRC_REG, self.__MASK_INT1_SRC_XL, self.__EnabledDict) def Set_Int1ThresholdX_Value(self, value): self.__writeToRegister(self.__REG_RW_INT1_THS_XH, self.__MASK_INT1_THS_H, (value & 0x7f00) >> 8) self.__writeToRegister(self.__REG_RW_INT1_THS_XL, self.__MASK_INT1_THS_L, value & 0x00ff) def Set_Int1ThresholdY_Value(self, value): self.__writeToRegister(self.__REG_RW_INT1_THS_YH, self.__MASK_INT1_THS_H, (value & 0x7f00) >> 8) self.__writeToRegister(self.__REG_RW_INT1_THS_YL, self.__MASK_INT1_THS_L, value & 0x00ff) def Set_Int1ThresholdZ_Value(self, value): self.__writeToRegister(self.__REG_RW_INT1_THS_ZH, self.__MASK_INT1_THS_H, (value & 0x7f00) >> 8) self.__writeToRegister(self.__REG_RW_INT1_THS_ZL, self.__MASK_INT1_THS_L, value & 0x00ff) def Get_Int1Threshold_Values(self): """(X,Y,Z) INT1 threshold value""" xh = self.__readFromRegister(self.__REG_RW_INT1_THS_XH, self.__MASK_INT1_THS_H) xl = self.__readFromRegister(self.__REG_RW_INT1_THS_XL, self.__MASK_INT1_THS_L) yh = self.__readFromRegister(self.__REG_RW_INT1_THS_YH, self.__MASK_INT1_THS_H) yl = self.__readFromRegister(self.__REG_RW_INT1_THS_YL, self.__MASK_INT1_THS_L) zh = self.__readFromRegister(self.__REG_RW_INT1_THS_ZH, self.__MASK_INT1_THS_H) zl = self.__readFromRegister(self.__REG_RW_INT1_THS_ZL, self.__MASK_INT1_THS_L) return (xh*256 + xl, yh*256 + yl, zh*256 + zl) def Set_Int1DurationWait_Enabled(self, value): self.__writeToRegisterWithDictionaryCheck(self.__REG_RW_INT1_DURATION, self.__MASK_INT1_DURATION_WAIT, value, self.__EnabledDict, 'EnabledEnum') def Get_Int1DurationWait_Enabled(self): """Int 1 duration wait""" return self.__readFromRegisterWithDictionaryMatch(self.__REG_RW_INT1_DURATION, self.__MASK_INT1_DURATION_WAIT, self.__EnabledDict) def Set_Int1Duration_Value(self, value): self.__writeToRegister(self.__REG_RW_INT1_DURATION, self.__MASK_INT1_DURATION_D, value) def Get_Int1Duration_Value(self): """Int 1 duration value""" return self.__readFromRegister(self.__REG_RW_INT1_DURATION, self.__MASK_INT1_DURATION_D)
from flask_socketio import SocketIO, emit, send from flaskext.mysql import MySQL from flask_httpauth import HTTPBasicAuth from passlib import pwd from passlib.hash import argon2 from smbus import SMBus from RPi import GPIO import time from threading import Thread import random # init hardware bus = SMBus() # Rev 2 Pi uses 1 bus.open(1) DEVICE = 0x20 # Device address (A0-A2) DEVICE1 = 0x21 IODIRA = 0x00 # Pin direction register GPIOA = 0x12 # Register for inputs GPPUA = 0x0C IODIRB = 0x01 # Pin direction register GPIOB = 0x13 # Register for inputs GPPUB = 0x0D bus.write_byte_data(DEVICE, 0x04, 0b11111111) bus.write_byte_data(DEVICE, IODIRA, 0b11111111) bus.write_byte_data(DEVICE, GPPUA, 0b11111111) bus.write_byte_data(DEVICE, IODIRB, 0b11111111)
apumpe = [Pumpe1, Pumpe2, Pumpe3, Pumpe4] spumpe = [Pumpe5, Pumpe6] #rfid setup def end_read(signal,frame): global continue_reading print ("Ctrl+C captured, ending read.") continue_reading = False GPIO.cleanup() signal.signal(signal.SIGINT, end_read) MIFAREReader = MFRC522.MFRC522() GPIO.setup(18,GPIO.IN, pull_up_down = GPIO.PUD_UP) GPIO.setup(16,GPIO.IN, pull_up_down = GPIO.PUD_UP) i2cbus = SMBus(1) # 0 = Raspberry Pi 1, 1 = Raspberry Pi > 1 oled = ssd1306(i2cbus) # Ein paar Abkürzungen, um den Code zu entschlacken draw = oled.canvas # Schriftarten festlegen FreeSans12 = ImageFont.truetype('FreeSans.ttf', 23) FreeSans13 = ImageFont.truetype('FreeSans.ttf', 18) FreeSans14 = ImageFont.truetype('FreeSans.ttf', 17) FreeSans20 = ImageFont.truetype('FreeSans.ttf', 50) # Display zum Start löschen def nohomo():
tty = "/dev/ttyPS1" delay = 0.001 ser = serial.Serial( port = tty, baudrate = 10000000, bytesize = serial.EIGHTBITS, parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE, # interCharTimeout = 0.2, timeout = 0.1, xonxoff = False, rtscts = False, dsrdtr = False); i2c = SMBus(2) print(icsp_cmd(ser, b'Z')) # tristate MCLR (icsp) data = [ 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE ] if len(sys.argv) < 4: cnt = 5 elif len(sys.argv) == 4: cnt = int(sys.argv[3], 0) else: data = [int(_,0) for _ in sys.argv[4:]] cnt = len(data) if len(sys.argv) < 3: cmd = 0x22
class ExplorerPHatJoystick(Joystick): # Based on https://github.com/pimoroni/explorer-hat/blob/master/library/explorerhat/ads1015.py UP = 18 DOWN = 27 LEFT = 0 RIGHT = 17 LB = 1 RB = 5 TRIGGER = 25 TR = 23 TL = 24 THUMB = 22 PGA_6_144V = 6144 PGA_4_096V = 4096 PGA_2_048V = 2048 PGA_1_024V = 1024 PGA_0_512V = 512 PGA_0_256V = 256 REG_CONV = 0x00 REG_CFG = 0x01 def __init__(self): self.address = 0x48 self.i2c = SMBus(1) self.samples_per_second_map = { 128: 0x0000, 250: 0x0020, 490: 0x0040, 920: 0x0060, 1600: 0x0080, 2400: 0x00A0, 3300: 0x00C0 } self.channel_map = {0: 0x4000, 1: 0x5000, 2: 0x6000, 3: 0x7000} self.programmable_gain_map = { 6144: 0x0000, 4096: 0x0200, 2048: 0x0400, 1024: 0x0600, 512: 0x0800, 256: 0x0A00 } self.axis = {'x': 0.0, 'y': 0.0, 'rx': 0.0, 'ry': 0.0} self.buttons = { 'trigger': False, 'tl': False, 'tr': False, 'thumb': False, 'dpad_up': False, 'dpad_down': False, 'dpad_left': False, 'dpad_right': False, 'thumbl': False, 'thumbr': False } GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(ExplorerPHatJoystick.UP, GPIO.IN) GPIO.setup(ExplorerPHatJoystick.DOWN, GPIO.IN) GPIO.setup(ExplorerPHatJoystick.LEFT, GPIO.IN) GPIO.setup(ExplorerPHatJoystick.RIGHT, GPIO.IN) GPIO.setup(ExplorerPHatJoystick.LB, GPIO.IN) GPIO.setup(ExplorerPHatJoystick.RB, GPIO.IN) GPIO.setup(ExplorerPHatJoystick.TRIGGER, GPIO.IN) GPIO.setup(ExplorerPHatJoystick.TR, GPIO.IN) GPIO.setup(ExplorerPHatJoystick.TL, GPIO.IN) GPIO.setup(ExplorerPHatJoystick.THUMB, GPIO.IN) def _read_se_adc(self, channel=1, programmable_gain=6144, samples_per_second=1600): # sane defaults config = 0x0003 | 0x0100 config |= self.samples_per_second_map[samples_per_second] config |= self.channel_map[channel] config |= self.programmable_gain_map[programmable_gain] # set "single shot" mode config |= 0x8000 # write single conversion flag self.i2c.write_i2c_block_data(self.address, ExplorerPHatJoystick.REG_CFG, [(config >> 8) & 0xFF, config & 0xFF]) delay = (1.0 / samples_per_second) + 0.0001 time.sleep(delay) data = self.i2c.read_i2c_block_data(self.address, ExplorerPHatJoystick.REG_CONV) return (((data[0] << 8) | data[1]) >> 4) * programmable_gain / 2048.0 / 1000.0 @staticmethod def _fix(v): r = int(((v - 2.5) / 2.5) * 127) if r < 0: r = 256 + r elif r > 127: r = 127 try: c = chr(r) except Exception as e: print("Failed to convert " + str(v) + " got " + str(r)) r = 0 # print("Read joystick value as " + str(v) + " fixed it to " + str(r)) return r def readAxis(self): self.axis['rx'] = self._fix(self._read_se_adc(3)) self.axis['ry'] = self._fix(self._read_se_adc(0)) self.axis['x'] = self._fix(self._read_se_adc(2)) self.axis['y'] = self._fix(self._read_se_adc(1)) return self.axis def readButtons(self): self.buttons['dpad_up'] = not bool(GPIO.input(ExplorerPHatJoystick.UP)) self.buttons['dpad_down'] = not bool( GPIO.input(ExplorerPHatJoystick.DOWN)) self.buttons['dpad_left'] = not bool( GPIO.input(ExplorerPHatJoystick.LEFT)) self.buttons['dpad_right'] = not bool( GPIO.input(ExplorerPHatJoystick.RIGHT)) self.buttons['thumbl'] = not bool(GPIO.input(ExplorerPHatJoystick.LB)) self.buttons['thumbr'] = not bool(GPIO.input(ExplorerPHatJoystick.RB)) self.buttons['trigger'] = not bool( GPIO.input(ExplorerPHatJoystick.TRIGGER)) self.buttons['tl'] = not bool(GPIO.input(ExplorerPHatJoystick.TL)) self.buttons['tr'] = not bool(GPIO.input(ExplorerPHatJoystick.TR)) self.buttons['thumb'] = not bool(GPIO.input( ExplorerPHatJoystick.THUMB)) return self.buttons
class PiGlow: def __init__(self): if rpi.RPI_REVISION == 1: i2c_bus = 0 elif rpi.RPI_REVISION == 2: i2c_bus = 1 elif rpi.RPI_REVISION == 3: i2c_bus = 1 else: print("Unable to determine Raspberry Pi revision.") exit self.bus = SMBus(i2c_bus) self.bus.write_i2c_block_data(0x54, 0x00, [0x01]) self.bus.write_byte_data(0x54, 0x13, 0xFF) self.bus.write_byte_data(0x54, 0x14, 0xFF) self.bus.write_byte_data(0x54, 0x15, 0xFF) def white(self, value): self.bus.write_byte_data(0x54, 0x0A, value) self.bus.write_byte_data(0x54, 0x0B, value) self.bus.write_byte_data(0x54, 0x0D, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def blue(self, value): self.bus.write_byte_data(0x54, 0x05, value) self.bus.write_byte_data(0x54, 0x0C, value) self.bus.write_byte_data(0x54, 0x0F, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def green(self, value): self.bus.write_byte_data(0x54, 0x06, value) self.bus.write_byte_data(0x54, 0x04, value) self.bus.write_byte_data(0x54, 0x0E, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def yellow(self, value): self.bus.write_byte_data(0x54, 0x09, value) self.bus.write_byte_data(0x54, 0x03, value) self.bus.write_byte_data(0x54, 0x10, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def orange(self, value): self.bus.write_byte_data(0x54, 0x08, value) self.bus.write_byte_data(0x54, 0x02, value) self.bus.write_byte_data(0x54, 0x11, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def red(self, value): self.bus.write_byte_data(0x54, 0x07, value) self.bus.write_byte_data(0x54, 0x01, value) self.bus.write_byte_data(0x54, 0x12, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def all(self, value): v = value self.bus.write_i2c_block_data( 0x54, 0x01, [v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v]) self.bus.write_byte_data(0x54, 0x16, 0xFF) def arm(self, arm, value): if arm == 1: self.bus.write_byte_data(0x54, 0x07, value) self.bus.write_byte_data(0x54, 0x08, value) self.bus.write_byte_data(0x54, 0x09, value) self.bus.write_byte_data(0x54, 0x06, value) self.bus.write_byte_data(0x54, 0x05, value) self.bus.write_byte_data(0x54, 0x0A, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) elif arm == 2: self.bus.write_byte_data(0x54, 0x0B, value) self.bus.write_byte_data(0x54, 0x0C, value) self.bus.write_byte_data(0x54, 0x0E, value) self.bus.write_byte_data(0x54, 0x10, value) self.bus.write_byte_data(0x54, 0x11, value) self.bus.write_byte_data(0x54, 0x12, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) elif arm == 3: self.bus.write_byte_data(0x54, 0x01, value) self.bus.write_byte_data(0x54, 0x02, value) self.bus.write_byte_data(0x54, 0x03, value) self.bus.write_byte_data(0x54, 0x04, value) self.bus.write_byte_data(0x54, 0x0F, value) self.bus.write_byte_data(0x54, 0x0D, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) else: print("Unknown number, expected only 1, 2 or 3") def arm1(self, value): self.bus.write_byte_data(0x54, 0x07, value) self.bus.write_byte_data(0x54, 0x08, value) self.bus.write_byte_data(0x54, 0x09, value) self.bus.write_byte_data(0x54, 0x06, value) self.bus.write_byte_data(0x54, 0x05, value) self.bus.write_byte_data(0x54, 0x0A, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def arm2(self, value): self.bus.write_byte_data(0x54, 0x0B, value) self.bus.write_byte_data(0x54, 0x0C, value) self.bus.write_byte_data(0x54, 0x0E, value) self.bus.write_byte_data(0x54, 0x10, value) self.bus.write_byte_data(0x54, 0x11, value) self.bus.write_byte_data(0x54, 0x12, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def arm3(self, value): self.bus.write_byte_data(0x54, 0x01, value) self.bus.write_byte_data(0x54, 0x02, value) self.bus.write_byte_data(0x54, 0x03, value) self.bus.write_byte_data(0x54, 0x04, value) self.bus.write_byte_data(0x54, 0x0F, value) self.bus.write_byte_data(0x54, 0x0D, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def colour(self, colour, value): if colour == 1 or colour == "white": self.bus.write_byte_data(0x54, 0x0A, value) self.bus.write_byte_data(0x54, 0x0B, value) self.bus.write_byte_data(0x54, 0x0D, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) elif colour == 2 or colour == "blue": self.bus.write_byte_data(0x54, 0x05, value) self.bus.write_byte_data(0x54, 0x0C, value) self.bus.write_byte_data(0x54, 0x0F, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) elif colour == 3 or colour == "green": self.bus.write_byte_data(0x54, 0x06, value) self.bus.write_byte_data(0x54, 0x04, value) self.bus.write_byte_data(0x54, 0x0E, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) elif colour == 4 or colour == "yellow": self.bus.write_byte_data(0x54, 0x09, value) self.bus.write_byte_data(0x54, 0x03, value) self.bus.write_byte_data(0x54, 0x10, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) elif colour == 5 or colour == "orange": self.bus.write_byte_data(0x54, 0x08, value) self.bus.write_byte_data(0x54, 0x02, value) self.bus.write_byte_data(0x54, 0x11, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) elif colour == 6 or colour == "red": self.bus.write_byte_data(0x54, 0x07, value) self.bus.write_byte_data(0x54, 0x01, value) self.bus.write_byte_data(0x54, 0x12, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) else: print("Only colours 1 - 6 or color names are allowed") def led(self, led, value): leds = [ "0x00", "0x07", "0x08", "0x09", "0x06", "0x05", "0x0A", "0x12", "0x11", "0x10", "0x0E", "0x0C", "0x0B", "0x01", "0x02", "0x03", "0x04", "0x0F", "0x0D"] self.bus.write_byte_data(0x54, int(leds[led], 16), value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led1(self, value): self.bus.write_byte_data(0x54, 0x07, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led2(self, value): self.bus.write_byte_data(0x54, 0x08, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led3(self, value): self.bus.write_byte_data(0x54, 0x09, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led4(self, value): self.bus.write_byte_data(0x54, 0x06, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led5(self, value): self.bus.write_byte_data(0x54, 0x05, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led6(self, value): self.bus.write_byte_data(0x54, 0x0A, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led7(self, value): self.bus.write_byte_data(0x54, 0x12, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led8(self, value): self.bus.write_byte_data(0x54, 0x11, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led9(self, value): self.bus.write_byte_data(0x54, 0x10, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led10(self, value): self.bus.write_byte_data(0x54, 0x0E, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led11(self, value): self.bus.write_byte_data(0x54, 0x0C, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led12(self, value): self.bus.write_byte_data(0x54, 0x0B, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led13(self, value): self.bus.write_byte_data(0x54, 0x01, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led14(self, value): self.bus.write_byte_data(0x54, 0x02, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led15(self, value): self.bus.write_byte_data(0x54, 0x03, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led16(self, value): self.bus.write_byte_data(0x54, 0x04, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led17(self, value): self.bus.write_byte_data(0x54, 0x0F, value) self.bus.write_byte_data(0x54, 0x16, 0xFF) def led18(self, value): self.bus.write_byte_data(0x54, 0x0D, value) self.bus.write_byte_data(0x54, 0x16, 0xFF)
class sgh_PCF8591P: # Constructor def __init__(self, busNum): print "init PCF8591" if busNum == 0: self.__bus = SMBus(0) # on a Rev 1 board #print "bus 0" else: self.__bus = SMBus(1) # on a Rev 2 board self.__addr = self.__checkI2Caddress(0x48) self.__DACEnabled = 0x00 print self.readADC( ) # dummy call to raise exception if no chip presnt on the i2c bus print "PCF8591 init completed" # self.__bus = __i2cBus # self.__addr = self.__checkI2Caddress(__addr) # self.__DACEnabled = 0x00 # i2c = SMBus(0) # on a Rev 1 board # # i2c = SMBus(1) # if on a Rev 2 board # # Create a PCF8591P object # sensor = PCF8591P(i2c, 0x48) # Read single ADC Channel def readADC(self, __chan=0): __checkedChan = self.__checkChannelNo(__chan) self.__bus.write_byte(self.__addr, __checkedChan | self.__DACEnabled) __reading = self.__bus.read_byte( self.__addr) # seems to need to throw away first reading __reading = self.__bus.read_byte(self.__addr) # read A/D return __reading # Read all ADC channels def readAllADC(self): __readings = [] self.__bus.write_byte(self.__addr, 0x04 | self.__DACEnabled) __reading = self.__bus.read_byte( self.__addr) # seems to need to throw away first reading for i in range(4): __readings.append(self.__bus.read_byte(self.__addr)) # read ADC return __readings # Set DAC value and enable output def writeDAC(self, __val=0): __checkedVal = self.__checkDACVal(__val) self.__DACEnabled = 0x40 self.__bus.write_byte_data(self.__addr, self.__DACEnabled, __checkedVal) # Enable DAC output def enableDAC(self): self.__DACEnabled = 0x40 self.__bus.write_byte(self.__addr, self.__DACEnabled) # Disable DAC output def disableDAC(self): self.__DACEnabled = 0x00 self.__bus.write_byte(self.__addr, self.__DACEnabled) # Check I2C address is within bounds def __checkI2Caddress(self, __addr): if type(__addr) is not int: raise I2CaddressOutOfBoundsError elif (__addr < 0): raise I2CaddressOutOfBoundsError elif (__addr > 127): raise I2CaddressOutOfBoundsError return __addr # Check if ADC channel number is within bounds def __checkChannelNo(self, __chan): if type(__chan) is not int: raise PCF8591PchannelOutOfBoundsError elif (__chan < 0): raise PCF8591PchannelOutOfBoundsError elif (__chan > 3): raise PCF8591PchannelOutOfBoundsError return __chan # Check if DAC output value is within bounds def __checkDACVal(self, __val): if type(__val) is not int: raise PCF8591PDACvalueOutOfBoundsError elif (__val < 0): raise PCF8591PDACvalueOutOfBoundsError elif (__val > 255): raise PCF8591PDACvalueOutOfBoundsError return __val
class AccelTiltSensor(object): "MMA8491Q Accel & Tilt Sensor." #Variables is_initialized = False #Pins mma8491q_en, mma8491q_x_int, mma8491q_y_int, mma8491q_z_int = 25, 17, 27, 26 #I2C Slave Address I2C_ADDRESS = 0x55 #Registers MMA8491Q_STATUS = 0x00 MMA8491Q_OUT_X_MSB = 0x01 MMA8491Q_OUT_Y_MSB = 0x03 MMA8491Q_OUT_Z_MSB = 0x05 #I2C Config bus = SMBus(1) #I2C Communication def _read_register_1ubyte(self, reg_addr): """Reads data from the I2C device. Parameters: reg_addr (byte): Read register address Returns: byte: Response from the device""" buffer = self.bus.read_i2c_block_data(self.I2C_ADDRESS, reg_addr, 1) return buffer[0] def _read_2bytes_rs2(self, reg_addr): """Reads 2 bytes from the I2C device, and then shifts two bits right. Parameters: reg_addr (byte): Read register address Returns: int: Modified response from the device""" buffer = self.bus.read_i2c_block_data(self.I2C_ADDRESS, reg_addr, 2) return (buffer[0] << 6) + (buffer[1] >> 2) def _read_array(self, reg_addr, cnt): """Reads data from the I2C device. Parameters: reg_addr (byte): Read register start address cnt (byte): Read register address Returns: byte array: Response from the device""" return self.bus.read_i2c_block_data(self.I2C_ADDRESS, reg_addr, cnt) #Initialization def __init__(self): """Initiates the MMA8491Q sensor.""" GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(self.mma8491q_en, GPIO.OUT) GPIO.setup(self.mma8491q_x_int, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(self.mma8491q_y_int, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(self.mma8491q_z_int, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) self.is_initialized = True #Sensor Read Methods def _convert_to_g(self, analog_data): """Converts raw sensor data to G value. Parameters: analog_data (int): Raw sensor output data Returns: int: G Force of the given axis""" if ((analog_data & 0x2000) == 0x2000): #If zero or negative G return (0x3FFF - analog_data) / -1024.0 else: #If positive G return analog_data / 1024.0 def read_accel_x(self): """Reads the G force of X-axis. Returns: int: G force of X-axis""" GPIO.output(self.mma8491q_en, GPIO.HIGH) time.sleep(0.001) while ((self._read_register_1ubyte(self.MMA8491Q_STATUS) & 0x01) != 0x01): time.sleep(0.001) tempData = self._read_2bytes_rs2(self.MMA8491Q_OUT_X_MSB) GPIO.output(self.mma8491q_en, GPIO.LOW) return self._convert_to_g(tempData) def read_accel_y(self): """Reads the G force of Y-axis. Returns: int: G force of Y-axis""" GPIO.output(self.mma8491q_en, GPIO.HIGH) time.sleep(0.001) while ((self._read_register_1ubyte(self.MMA8491Q_STATUS) & 0x02) != 0x02): time.sleep(0.001) tempData = self._read_2bytes_rs2(self.MMA8491Q_OUT_Y_MSB) GPIO.output(self.mma8491q_en, GPIO.LOW) return self._convert_to_g(tempData) def read_accel_z(self): """Reads the G force of Z-axis. Returns: int: G force of Z-axis""" GPIO.output(self.mma8491q_en, GPIO.HIGH) time.sleep(0.001) while ((self._read_register_1ubyte(self.MMA8491Q_STATUS) & 0x04) != 0x04): time.sleep(0.001) tempData = self._read_2bytes_rs2(self.MMA8491Q_OUT_Z_MSB) GPIO.output(self.mma8491q_en, GPIO.LOW) return self._convert_to_g(tempData) def read_accel_xyz(self): """Reads the G forces of X, Y and Z-axes. Returns: int array: G forces of X, Y and Z-axes respectively""" xyz = [ 0, 0, 0 ] GPIO.output(self.mma8491q_en, GPIO.HIGH) time.sleep(0.001) while ((self._read_register_1ubyte(self.MMA8491Q_STATUS) & 0x08) != 0x08): time.sleep(0.001) xyzArray = self._read_array(self.MMA8491Q_OUT_X_MSB, 6) GPIO.output(self.mma8491q_en, GPIO.LOW) xyz[0] = self._convert_to_g((xyzArray[0] << 6) + (xyzArray[1] >> 2)) #X-Axis xyz[1] = self._convert_to_g((xyzArray[2] << 6) + (xyzArray[3] >> 2)) #Y-Axis xyz[2] = self._convert_to_g((xyzArray[4] << 6) + (xyzArray[5] >> 2)) #Z-Axis return xyz def read_tilt_x(self): """Reads the X-Axis tilt state. Returns: bool: True if acceleration is > 0.688g or X-axis > 45, false if not""" GPIO.output(self.mma8491q_en, GPIO.HIGH) time.sleep(0.001) state = True if GPIO.input(self.mma8491q_x_int) else False GPIO.output(self.mma8491q_en, GPIO.LOW) return state def read_tilt_y(self): """Reads the Y-Axis tilt state. Returns: bool: True if acceleration is > 0.688g or Y-axis > 45, false if not""" GPIO.output(self.mma8491q_en, GPIO.HIGH) time.sleep(0.001) state = True if GPIO.input(self.mma8491q_y_int) else False GPIO.output(self.mma8491q_en, GPIO.LOW) return state def read_tilt_z(self): """Reads the Z-Axis tilt state. Returns: bool: True if acceleration is > 0.688g or Z-axis > 45, false if not""" GPIO.output(self.mma8491q_en, GPIO.HIGH) time.sleep(0.001) state = True if GPIO.input(self.mma8491q_z_int) else False GPIO.output(self.mma8491q_en, GPIO.LOW) return state def read_tilt_xyz(self): """Reads the X, Y and Z-Axis tilt states respectively. Returns: bool array: True if acceleration is > 0.688g or axis > 45, false if not""" xyz = [False, False, False] GPIO.output(self.mma8491q_en, GPIO.HIGH) time.sleep(0.001) xyz[0] = True if GPIO.input(self.mma8491q_x_int) else False xyz[1] = True if GPIO.input(self.mma8491q_y_int) else False xyz[2] = True if GPIO.input(self.mma8491q_z_int) else False GPIO.output(self.mma8491q_en, GPIO.LOW) return xyz #Disposal def __del__(self): """Releases the resources.""" try: if self.is_initialized: GPIO.output(self.mma8491q_en, GPIO.LOW) GPIO.cleanup() del self.is_initialized except: pass
#!/usr/bin/env python3 import sys import struct import time from smbus import SMBus from ina219 import INA219 from ina219 import DeviceRangeError bus = SMBus(1) # indicates /dev/ic2-1 arduinoSlaveAddress = 0x03 # Arduino bus address # Cluster devices cluster_devices = [ "Raspberry Pi", "USB module #1", "USB module #2, for serial console's (IP KVM)", "Master01 (Rock64)", "Master02 (Rock64)", "Master03 (Rock64)", "Worker01 (mini PC)", "Worker02 (mini PC)", "Worker03 (Rock64)" ] # IP KVM devices ipkvm_devices = [ "IP KVM for Worker01", "IP KVM for Worker02", "D13", "A0", "A1" ] # Params for INA219 sensors shunt_ohms = 0.1 ina219_sensors = [{ "Raspberry Pi": 0x40 }, { "Master01 (Rock64)": 0x44
class ADS1x15(object): """Base functionality for ADS1x15 analog to digital converters.""" def __init__(self, i2c, gain=1, data_rate=None, mode=Mode.SINGLE, address=_ADS1X15_DEFAULT_ADDRESS): #pylint: disable=too-many-arguments self._last_pin_read = None self.buf = bytearray(3) self._data_rate = self._gain = self._mode = None self.gain = gain self.data_rate = self._data_rate_default( ) if data_rate is None else data_rate self.mode = mode self.address = address self.i2c_device = SMBus(i2c) @property def data_rate(self): """The data rate for ADC conversion in samples per second.""" return self._data_rate @data_rate.setter def data_rate(self, rate): possible_rates = self.rates if rate not in possible_rates: raise ValueError( "Data rate must be one of: {}".format(possible_rates)) self._data_rate = rate @property def rates(self): """Possible data rate settings.""" raise NotImplementedError('Subclass must implement rates property.') @property def rate_config(self): """Rate configuration masks.""" raise NotImplementedError( 'Subclass must implement rate_config property.') @property def gain(self): """The ADC gain.""" return self._gain @gain.setter def gain(self, gain): possible_gains = self.gains if gain not in possible_gains: raise ValueError("Gain must be one of: {}".format(possible_gains)) self._gain = gain @property def gains(self): """Possible gain settings.""" g = list(_ADS1X15_CONFIG_GAIN.keys()) g.sort() return g @property def mode(self): """The ADC conversion mode.""" return self._mode @mode.setter def mode(self, mode): if mode != Mode.CONTINUOUS and mode != Mode.SINGLE: raise ValueError("Unsupported mode.") self._mode = mode def read(self, pin, is_differential=False): """I2C Interface for ADS1x15-based ADCs reads. params: :param pin: individual or differential pin. :param bool is_differential: single-ended or differential read. """ pin = pin if is_differential else pin + 0x04 return self._read(pin) def _data_rate_default(self): """Retrieve the default data rate for this ADC (in samples per second). Should be implemented by subclasses. """ raise NotImplementedError( 'Subclasses must implement _data_rate_default!') def _conversion_value(self, raw_adc): """Subclasses should override this function that takes the 16 raw ADC values of a conversion result and returns a signed integer value. """ raise NotImplementedError( 'Subclass must implement _conversion_value function!') def _read(self, pin): """Perform an ADC read. Returns the signed integer result of the read.""" if self.mode == Mode.CONTINUOUS and self._last_pin_read == pin: return self._conversion_value(self.get_last_result(True)) else: self._last_pin_read = pin config = _ADS1X15_CONFIG_OS_SINGLE config |= (pin & 0x07) << _ADS1X15_CONFIG_MUX_OFFSET config |= _ADS1X15_CONFIG_GAIN[self.gain] config |= self.mode config |= self.rate_config[self.data_rate] config |= _ADS1X15_CONFIG_COMP_QUE_DISABLE self._write_register(_ADS1X15_POINTER_CONFIG, config) if self.mode == Mode.SINGLE: while not self._conversion_complete(): pass return self._conversion_value(self.get_last_result(False)) def _conversion_complete(self): """Return status of ADC conversion.""" # OS is bit 15 # OS = 0: Device is currently performing a conversion # OS = 1: Device is not currently performing a conversion return self._read_register(_ADS1X15_POINTER_CONFIG) & 0x8000 def get_last_result(self, fast=False): """Read the last conversion result when in continuous conversion mode. Will return a signed integer value. If fast is True, the register pointer is not updated as part of the read. This reduces I2C traffic and increases possible read rate. """ return self._read_register(_ADS1X15_POINTER_CONVERSION, fast) def _write_register(self, reg, value): """Write 16 bit value to register.""" self.buf[0] = reg self.buf[1] = (value >> 8) & 0xFF self.buf[2] = value & 0xFF self.i2c_device.write_i2c_block_data(self.address, self.buf[0], list(self.buf[1:])) def _read_register(self, reg, fast=False): """Read 16 bit register value. If fast is True, the pointer register is not updated. """ if fast: a, b = self.i2c_device.read_i2c_block_data(self.address, reg, 2) else: a, b = self.i2c_device.read_i2c_block_data(self.address, reg, 2) return a << 8 | b
def __init__(self, address=0x3c): """ :param address: i2c address of ssd1306 """ self.bus = SMBus(self.bus_id()) self.address = address
class LinuxI2cBus: """A Linux I²C device, which is itself an I²C bus. Should not be instantiated directly; use `LinuxI2c.find_devices` instead. This type mimics the `smbus.SMBus` read/write/close APIs. However, `open` does not take any parameters, and not all APIs are available. """ # note: this is not a liquidctl BaseBus, as that would cause # find_liquidctl_devices to try to directly instantiate it def __init__(self, i2c_dev): self._i2c_dev = i2c_dev self._smbus = None try: assert i2c_dev.name.startswith('i2c-') self._number = int(i2c_dev.name[4:]) except: raise ValueError('cannot infer bus number') def find_devices(self, drivers, **kwargs): """Probe drivers and find compatible devices in this bus.""" for drv in drivers: yield from drv.probe(self, **kwargs) def open(self): """Open the I²C bus.""" if not self._smbus: try: self._smbus = SMBus(self._number) except FileNotFoundError: if Path('/sys/class/i2c-dev').exists(): raise raise OSError('kernel module i2c-dev not loaded') from None def read_byte(self, address): """Read a single byte from a device.""" value = self._smbus.read_byte(address) _LOGGER.debug('read byte @ 0x%02x:0x%02x', address, value) return value def read_byte_data(self, address, register): """Read a single byte from a designated register.""" value = self._smbus.read_byte_data(address, register) _LOGGER.debug('read byte data @ 0x%02x:0x%02x 0x%02x', address, register, value) return value def read_word_data(self, address, register): """Read a single 2-byte word from a given register.""" value = self._smbus.read_word_data(address, register) _LOGGER.debug('read word data @ 0x%02x:0x%02x 0x%02x', address, register, value) return value def read_block_data(self, address, register): """Read a block of up to 32 bytes from a given register.""" data = self._smbus.read_block_data(address, register) _LOGGER.debug('read block data @ 0x%02x:0x%02x: %r', address, register, LazyHexRepr(data)) return data def write_byte(self, address, value): """Write a single byte to a device.""" _LOGGER.debug('writing byte @ 0x%02x: 0x%02x', address, value) return self._smbus.write_byte(address, value) def write_byte_data(self, address, register, value): """Write a single byte to a designated register.""" _LOGGER.debug('writing byte data @ 0x%02x:0x%02x 0x%02x', address, register, value) return self._smbus.write_byte_data(address, register, value) def write_word_data(self, address, register, value): """Write a single 2-byte word to a designated register.""" _LOGGER.debug('writing word data @ 0x%02x:0x%02x 0x%02x', address, register, value) return self._smbus.write_word_data(address, register, value) def write_block_data(self, address, register, data): """Write a block of byte data to a given register.""" _LOGGER.debug('writing block data @ 0x%02x:0x%02x %r', address, register, LazyHexRepr(data)) return self._smbus.write_block_data(address, register, data) def close(self): """Close the I²C connection.""" if self._smbus: self._smbus.close() self._smbus = None def load_eeprom(self, address): """Return EEPROM name and data in `address`, or None if N/A.""" # uses kernel facilities to avoid directly reading from the EEPROM # or managing its pages, also avoiding the need for unsafe=smbus dev = f'{self._number}-{address:04x}' try: name = self._i2c_dev.joinpath(dev, 'name').read_text().strip() eeprom = self._i2c_dev.joinpath(dev, 'eeprom').read_bytes() return LinuxEeprom(name, eeprom) except Exception: return None @property def name(self): return self._i2c_dev.name @property def description(self): return self._try_sysfs_read('name') @property def parent_vendor(self): return self._try_sysfs_read_hex('device/vendor') @property def parent_device(self): return self._try_sysfs_read_hex('device/device') @property def parent_subsystem_vendor(self): return self._try_sysfs_read_hex('device/subsystem_vendor') @property def parent_subsystem_device(self): return self._try_sysfs_read_hex('device/subsystem_device') @property def parent_driver(self): try: return Path( os.readlink(self._i2c_dev.joinpath('device/driver'))).name except FileNotFoundError: return None def __str__(self): if self.description: return f'{self.name}: {self.description}' return self.name def __repr__(self): def hexid(maybe): if maybe is not None: return f'{maybe:#06x}' return 'None' return f'{self.__class__.__name__}: name: {self.name!r}, description:' \ f' {self.description!r}, parent_vendor: {hexid(self.parent_vendor)},' \ f' parent_device: {hexid(self.parent_device)}, parent_subsystem_vendor:' \ f' {hexid(self.parent_subsystem_vendor)},' \ f' parent_subsystem_device: {hexid(self.parent_subsystem_device)},' \ f' parent_driver: {self.parent_driver!r}' def _try_sysfs_read(self, *sub, default=None): try: return self._i2c_dev.joinpath(*sub).read_text().rstrip() except FileNotFoundError: return default def _try_sysfs_read_hex(self, *sub, default=None): try: return int(self._i2c_dev.joinpath(*sub).read_text(), base=16) except FileNotFoundError: return default