def __init__(self,gps=False,servo_port=SERVO_PORT): # devices self.compass = Compass(I2C(COMPASS_I2C_ADDRESS),I2C(ACCELEROMETER_I2C_ADDRESS)) self.rudder_servo = Servo(serial.Serial(servo_port),RUDDER_SERVO_CHANNEL,RUDDER_MIN_PULSE,RUDDER_MIN_ANGLE,RUDDER_MAX_PULSE,RUDDER_MAX_ANGLE) try: while True: current_bearing = self.compass.bearing difference = angle_between(TARGET_BEARING, current_bearing) # for definite rudder deflection at low angles for difference: # scaled_diff = max(5, abs(difference/3)) # rudder_angle = copysign(scaled_diff,difference) # for tolerance of small differences rudder_angle = difference/3 if abs(difference) > 5 else 0 self.rudder_servo.set_position(rudder_angle) print('Current bearing {:+.1f}, target {:+.1f}, rudder {:+.1f}'.format(current_bearing, TARGET_BEARING, rudder_angle)) # smooth response with a sleep time of less than 100ms ? time.sleep(0.1) except (KeyboardInterrupt, SystemExit): quit()
def __init__(self, addr=SHT31_BASEADDR, lock=None): I2C.__init__(self, lock) self.i2c_addr = addr self.__temperature = 0 self.__humidity = 0 self.__lastread = -1
def __init__(self, address): I2C.__init__(self, address) self.write(0x21) self.write(0x81) # clear buffer for d in range(0, 10, 2): self.write16(d, 0)
def __init__(self, bus = 1): I2C.__init__(self, 0x40, bus) self.CMD_RESET = 0xFE self.CMD_READ_TEMP_NO_HOLD = 0xE3 self.CMD_READ_HUM_NO_HOLD = 0xF5 self.CMD_READ_REG = 0xE7 self.CMD_WRITE_REG = 0xE6
def offExpander(): from i2c import I2C i2cpath = request.query['i2cpath'] i2c = I2C(i2cpath) msgs = [I2C.Message([0x00, 0x00], read=False)] i2c.transfer(0x20, msgs) i2c.close() return msgs[1].data[0]
def measureDistance(): from i2c import I2C i2cpath = request.query['i2cpath'] i2c = I2C(i2cpath) msgs = [I2C.Message([0xFF, 0xFF], read=False)] i2c.transfer(0x20, msgs) i2c.close() return msgs[1].data[0]
def __init__(self, bus=1, bl=1): I2C.__init__(self, 0x27, bus) self.bl = bl self._write_cmd(self.CMD_FSET | self.SET_2LINES) self._write_cmd(self.CMD_ON | self.ON_DISPLAY) self._write_cmd(self.CMD_ENTRY | self.ENTRY_RIGHT) self.cls()
def get_ranges(self): """Requests the last measurements of all sensors""" cmd = I2C.pack8(Command.MeasureAll, 0) self.send(cmd) data = self.receive(2 * self.n) ranges = list() for i in range(self.n): j = i * 2 ranges.append(I2C.pack16(data[(i * 2) + 1], data[i * 2])) return ranges
def __init__(self, gps=False, servo_port=SERVO_PORT): # devices self._gps = gps self.windsensor = WindSensor(I2C(WINDSENSOR_I2C_ADDRESS)) self.compass = Compass(I2C(COMPASS_I2C_ADDRESS), I2C(ACCELEROMETER_I2C_ADDRESS)) self.red_led = GpioWriter(17, os) self.green_led = GpioWriter(18, os) # Navigation self.globe = Globe() self.timer = Timer() self.application_logger = self._rotating_logger(APPLICATION_NAME) self.position_logger = self._rotating_logger("position") self.exchange = Exchange(self.application_logger) self.timeshift = TimeShift(self.exchange, self.timer.time) self.event_source = EventSource(self.exchange, self.timer, self.application_logger, CONFIG['event source']) self.sensors = Sensors(self.gps, self.windsensor, self.compass, self.timer.time, self.exchange, self.position_logger, CONFIG['sensors']) self.gps_console_writer = GpsConsoleWriter(self.gps) self.rudder_servo = Servo(serial.Serial(servo_port), RUDDER_SERVO_CHANNEL, RUDDER_MIN_PULSE, RUDDER_MIN_ANGLE, RUDDER_MAX_PULSE, RUDDER_MAX_ANGLE) self.steerer = Steerer(self.rudder_servo, self.application_logger, CONFIG['steerer']) self.helm = Helm(self.exchange, self.sensors, self.steerer, self.application_logger, CONFIG['helm']) self.course_steerer = CourseSteerer(self.sensors, self.helm, self.timer, CONFIG['course steerer']) self.navigator = Navigator(self.sensors, self.globe, self.exchange, self.application_logger, CONFIG['navigator']) self.self_test = SelfTest(self.red_led, self.green_led, self.timer, self.rudder_servo, RUDDER_MIN_ANGLE, RUDDER_MAX_ANGLE) # Tracking self.tracking_logger = self._rotating_logger("track") self.tracking_sensors = Sensors(self.gps, self.windsensor, self.compass, self.timer.time, self.exchange, self.tracking_logger, CONFIG['sensors']) self.tracker = Tracker(self.tracking_logger, self.tracking_sensors, self.timer)
def setPinOn(): from i2c import I2C i2cpath = request.query['i2cpath'] pinNo = request.query['pinNo'] i2c = I2C(i2cpath) msgs = [I2C.Message([0xFF, 0xFF], read=True)] i2c.transfer(0x20, msgs) array1 = msgs[1].data[0] array2 = msgs[1].data[1] if pinNo.find('A') == -1: print('A') pinNo = pinNo.replace('A', '') else: print('B') i2c.close() return msgs[1].data[0]
def __init__(self, refPath, dataPath, dbFilename): GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setup(self.AUTO_START_GPIO_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) self.__i2c = I2C(2) self.__analog = Analog(sel.__i2c.getLock(), 0x49) self.default = Default() self.database = Database(dataPath, dbFilename) self.waterlevel = Waterlevel(debug, self.database) self.light = Light(self.database) self.curtain = Curtain(self.database) self.pressure = Pressure(self.database, self.default, self.__analog) self.temperature = Temperature("28-0417716a37ff", self.database) self.redox = Redox(debug, self.database, self.default, self.__analog) self.ph = PH(debug, self.database, self.default, self.__analog, self.temperature) self.robot = Robot(debug, self.database) self.pump = Pump(debug, self.database, self.default, self.robot, self.redox, self.ph, self.temperature) self.panel = Panel(debug, self.database, self.default, self.pump, self.redox, self.ph, self.__i2c) self.statistic = Statistic(debug, self.pump, self.robot, self.redox, self.ph, self.temperature, self.pressure, self.waterlevel) self.refPath = refPath self.__autoSaveTick = 0 self.__today = date.today().day - 1 debug.TRACE(debug.DEBUG, "Initialisation done (Verbosity level: %s)\n", debug)
def startNLP(model): #model = sys.argv[1] def detectedCallback(): detector.terminate() # So google Assistant can use audio device snowboydecoder.play_audio_file(snowboydecoder.DETECT_DING) assistant.startAssist() snowboydecoder.play_audio_file(snowboydecoder.DETECT_DONG) detector.start(detected_callback=detectedCallback, interrupt_check=interrupt_callback, sleep_time=0.03) i2c = I2C(SLAVE_ADDR) assistant = GoogleAssistant(i2c) # capture SIGINT signal, e.g., Ctrl+C signal.signal(signal.SIGINT, signal_handler) # The obj contains the hotword detection snowboydecoder.play_audio_file(snowboydecoder.DETECT_DING) snowboydecoder.play_audio_file(snowboydecoder.DETECT_DONG) detector = snowboydecoder.HotwordDetector(model, sensitivity=0.5) print('Listening... Press Ctrl+C to exit') # main loop detector.start( detected_callback=detectedCallback, #snowboydecoder.play_audio_file, interrupt_check=interrupt_callback, sleep_time=0.03) detector.terminate()
def init_sensors(self): """Initializes the I2C Bus including the SHT21 and MCP3424 sensors.""" try: self.i2c = I2C() self.sht21 = SHT21(1) self.mcp3424 = MCP3424(self.i2c.get_smbus()) except IOError as err: sys.stderr.write('I2C Connection Error: ' + str(err) + '. This must be run as root. Did you use the right device number?')
def __init__(self, address, dev_node, busnum=-1): self.i2c = I2C(address=address, busnum=busnum, dev_node=dev_node) self.address = address self.i2c.write8(MCP23017_IODIRA, 0xFF) # all inputs on port A self.i2c.write8(MCP23017_IODIRB, 0xFF) # all inputs on port B self.direction = self.i2c.readU8(MCP23017_IODIRA) self.direction |= self.i2c.readU8(MCP23017_IODIRB) << 8 self.i2c.write8(MCP23017_GPPUA, 0x00) self.i2c.write8(MCP23017_GPPUB, 0x00)
def __init__(self, path, debug=True): #setup i2c bus and sensor address #Assumes use of RPI device that is new enough #to use SMBus=1, older devices use SMBus = 0 self.i2c = I2C(path) self.address = address self.debug = debug #Module identification defaults self.idModel = 0x00 self.idRev = 0x00
def __init__(self, args): super(Solarium, self).__init__(args) i2c = I2C() addresses = i2c.scan_bus() logger.debug("Found device addresses: {}".format(addresses)) self.rays = [] self.led_values = None for idx in range(0, len(addresses) / 3, 3): ray = Ray(i2c, addresses[idx], addresses[idx + 1], addresses[idx + 2]) self.rays.append(ray)
def __init__(self, i2c_addr=BME_680_BASEADDR, gas_measurement=True, qv_temp=None, \ qv_humi=None, qv_pressure=None, qv_airquality=None, lock=None): BME680Data.__init__(self) I2C.__init__(self, lock) self.i2c_addr = i2c_addr self.gas_measurement = gas_measurement self.__qv_temp = qv_temp self.__qv_humi = qv_humi self.__qv_pressure = qv_pressure self.__qv_airquality = qv_airquality self.chip_id = self._get_regs(CHIP_ID_ADDR, 1) if self.chip_id != CHIP_ID: raise RuntimeError( "BME680 not found. Invalid CHIP ID: 0x{0:02x}".format( self.chip_id)) self.soft_reset() self.set_power_mode(SLEEP_MODE) self._get_calibration_data() self.set_humidity_oversample(OS_2X) self.set_pressure_oversample(OS_4X) self.set_temperature_oversample(OS_8X) self.set_filter(FILTER_SIZE_3) self.set_gas_status(ENABLE_GAS_MEAS) self.get_sensor_data_lock = threading.Lock() self.get_sensor_data() self.baselinethread = None if self.gas_measurement: self._calculate_air_quality_baseline()
def talker(): rospy.init_node('LTC2497_ADC_HAT') publishers = [] for i in range(0, 8): #supports 8 pub = rospy.Publisher("ADC_Channels/CH" + str(i), Float64, queue_size=10) publishers.append(pub) frequency = rospy.get_param("~frequency", 100) i2c_address = rospy.get_param("~address", 0x18) rate = rospy.Rate(frequency) adc = I2C(i2c_address, 1) while not rospy.is_shutdown(): for i in range(0, 8): adc_val = read_adc(adc, i) publishers[i].publish(adc_val) rate.sleep()
def __init__(self, address, num_gpios): assert num_gpios >= 0 and num_gpios <= 16, "Number of GPIOs must be between 0 and 16" self.i2c = I2C(address=address) self.address = address self.num_gpios = num_gpios # set defaults if num_gpios <= 8: self.i2c.write8(MCP23017_IODIRA, 0xFF) # all inputs on port A self.direction = self.i2c.readU8(MCP23017_IODIRA) self.i2c.write8(MCP23008_GPPUA, 0x00) elif num_gpios > 8 and num_gpios <= 16: self.i2c.write8( MCP23017_IODIRA, 0x00) # GPA0-7 all OUTPUTS (with 0xFF all inputs on port A) self.i2c.write8( MCP23017_IODIRB, 0x00) # GPB0-7 all OUTPUTS (with 0xFF all inputs on port B) self.direction = self.i2c.readU8(MCP23017_IODIRA) self.direction |= self.i2c.readU8(MCP23017_IODIRB) << 8 self.i2c.write8(MCP23017_GPPUA, 0x00) self.i2c.write8(MCP23017_GPPUB, 0x00)
def __init__(self, theBank, theMode, theRoach = None, theValon = None, hpc_macs = None, unit_test = False): """ Creates an instance of the vegas internals. """ # Save a reference to the bank self.test_mode = unit_test if self.test_mode: print "Backend.py:: UNIT TEST MODE!!!" self.roach = None self.valon = None self.i2c = None else: self.roach = theRoach self.valon = theValon if self.roach: self.i2c = I2C(theRoach) else: self.i2c = None # Figure out what we need here -- looks like this is the setup for access to shared memory. But why here # why a vegas status buffer in the base backend class? #print "Backend.py:: Setting instance_id" self.instance_id = self.bank2inst(theBank.name) #print "Backend.py:: Set instance_id" #print self.instance_id #print "Backend.py:: Setting self.status to vegas_status" #self.status = vegas_status(instance_id = self.instance_id) #print "Backend.py:: Done!" self.status_mem_local = {} self.roach_registers_local = {} self.hpc_macs = hpc_macs # This is already checked by player.py, we won't get here if not set self.dibas_dir = os.getenv("DIBAS_DIR") self.dataroot = os.getenv("DIBAS_DATA") # Example /lustre/gbtdata if self.dataroot is None: self.dataroot = "/tmp" self.mode = theMode self.bank = theBank self.start_time = None self.start_scan = False self.hpc_process = None self.obs_mode = 'SEARCH' self.max_databuf_size = 128 # in MBytes self.observer = "unspecified" self.source = "unspecified" self.source_ra_dec = None self.cal_freq = "unspecified" self.telescope = "unspecified" self.projectid = "" self.datadir = self.dataroot + "/" + self.projectid self.scan_running = False self.monitor_mode = False print "BFBE: Backend():: Setting self.frequency to", self.mode.frequency self.filter_bw_bits = self.bank.filter_bw_bits self.frequency = self.mode.frequency self.setFilterBandwidth(self.mode.filter_bw) self.setNoiseSource(NoiseSource.OFF) self.setNoiseTone1(NoiseTone.NOISE) self.setNoiseTone2(NoiseTone.NOISE) self.setScanLength(30.0) self.params = {} # TBF: Rething "frequency" & "bandwidth" parameters. If one or # both are parameters, then changing them must deprogram roach # first, set frequency, then reprogram roach. For now, these are # removed from the parameter list here and in derived classes, # and frequency is set when programming roach. Frequency changes # may be made via the Bank.set_mode() function. # self.params["frequency" ] = self.setValonFrequency self.params["filter_bw" ] = self.setFilterBandwidth self.params["observer" ] = self.setObserver self.params["project_id" ] = self.setProjectId self.params["noise_tone_1" ] = self.setNoiseTone1 self.params["noise_tone_2" ] = self.setNoiseTone2 self.params["noise_source" ] = self.setNoiseSource self.params["cal_freq" ] = self.setCalFreq self.params["scan_length" ] = self.setScanLength self.params["source" ] = self.setSource self.params["source_ra_dec"] = self.setSourceRADec self.params["telescope" ] = self.setTelescope # CODD mode is special: One roach has up to 8 interfaces, and # each is the DATAHOST for one of the Players. This distribution # gets set here. If not a CODD mode, just use the one in the # BANK section. if self.mode.cdd_mode: self.datahost = self.mode.cdd_roach_ips[self.bank.name] else: self.datahost = self.bank.datahost self.dataport = self.bank.dataport self.bof_file = self.mode.bof
def test_should_treat_bytes_as_2s_comp(self): i2c = I2C(44) stubSmbus.setup_byte_data([0x01, 0x02]) self.assertEqual(i2c.read16_2s_comp(23), 258) stubSmbus.setup_byte_data([0xFF, 0xF9]) self.assertEqual(i2c.read16_2s_comp(23), -7)
def test_should_return_reverse_consecutive_data_in_one_value_with_false( self): i2c = I2C(44) stubSmbus.setup_byte_data([0x01, 0x02]) self.assertEqual(i2c.read16(23, high_low=False), 0x0201)
def test_should_return_consecutive_data_in_one_value(self): i2c = I2C(44) stubSmbus.setup_byte_data([0x01, 0x02]) self.assertEqual(i2c.read16(23, high_low=True), 0x0102)
def test_should_return_configured_8_bit_data(self): i2c = I2C(44) stubSmbus.setup_byte_data([0xFF]) self.assertEqual(i2c.read8(23), 0xFF)
from i2c import I2C bus = I2C(0x40, 1) bus.open() bus.write(b"\2\4") bus.close()
from i2c import I2C smb = I2C() class _8bitIO(): def configPorts(self): smb.write( '0x73', '03FC', False ) #write to config register 1111 1011. All are set as input except ZA and ZB Armed def arm(self, zone, disarm): if disarm == True: if zone == 'a': res = smb.write_read('0x73', '1', '00', False) res = int(res[0], 16) if (1 << 1) and res: smb.write('0x73', '0103', False) #writes a 1 to pin 0 while pin 1 is set if not ((1 << 1) and res): smb.write( '0x73', '0101', False) #writes a 1 to pin 0 while pin 1 is not set smb.read('0x73', '1', False) elif zone == 'b': res = smb.write_read('0x73', '1', '00', False) res = int(res[0], 16) if (1 << 0) and res: smb.write('0x73', '0103', False) #writes a 1 to pin 1 while pin 1 is set if not ((1 << 0) and res): smb.write(
def __init__(self, address): I2C.__init__(self, address)
def __init__(self): """Whole project is run from this constructor """ # +++++++++++++++ Init +++++++++++++++ # self.keep_run = 1 # used in run for daemon loop, reset by SIGTERM self.ret_code = 0 # return code to command line (10 = shutdown) # +++++++++++++++ Objects +++++++++++++++ # # Each inner object will get reference to PyBlaster as self.main. # exceptions in child threads are put here self.ex_queue = queue.Queue() self.log = Log(self) self.settings = Settings(self) self.settings.parse() PB_GPIO.init_gpio(self) self.led = LED(self) self.buttons = Buttons(self) self.lirc = Lirc(self) self.dbhandle = DBHandle(self) self.cmd = Cmd(self) self.mpc = MPC(self) self.bt = RFCommServer(self) self.alsa = AlsaMixer(self) self.i2c = I2C(self) self.usb = UsbDrive(self) # +++++++++++++++ Init Objects +++++++++++++++ # # Make sure to run init functions in proper order! # Some might depend upon others ;) self.led.init_leds() self.dbhandle.dbconnect() self.mpc.connect() self.bt.start_server_thread() self.alsa.init_alsa() self.i2c.open_bus() self.usb.start_uploader_thread() # +++++++++++++++ Daemoninze +++++++++++++++ # self.check_pidfile() self.daemonize() self.create_pidfile() # +++++++++++++++ Daemon loop +++++++++++++++ # self.led.show_init_done() self.buttons.start() self.lirc.start() self.run() # +++++++++++++++ Finalize +++++++++++++++ # self.log.write(log.MESSAGE, "Joining threads...") # join remaining threads self.usb.join() self.bt.join() self.buttons.join() self.lirc.join() self.mpc.join() self.led.join() self.log.write(log.MESSAGE, "leaving...") # cleanup self.mpc.exit_client() self.delete_pidfile() PB_GPIO.cleanup(self)
# configuration for BayEOSWriter and BayEOSSender PATH = '/tmp/raspberrypi/' NAME = 'RaspberryPi' URL = 'http://bayconf.bayceer.uni-bayreuth.de/gateway/frame/saveFlat' # instantiate objects of BayEOSWriter and BayEOSSender writer = BayEOSWriter(PATH) sender = BayEOSSender(PATH, NAME, URL) # initialize GPIO Board on Raspberry Pi gpio = GPIO(ADDR_PINS, EN_PIN, DATA_PIN) # initialize I2C Bus with sensors try: i2c = I2C() sht21 = SHT21(1) mcp3424 = MCP3424(i2c.get_smbus()) except IOError as err: sys.stderr.write( 'I2C Connection Error: ' + str(err) + '. This must be run as root. Did you use the right device number?') # measurement method def measure(seconds=10): """Measures temperature, humidity and CO2 concentration. @param seconds: how long should be measured @return statistically calculated parameters """ measured_seconds = []
def get_number_of_sensors(self): """Requests the number of available sensors""" cmd = I2C.pack8(Command.Count, 0) self.send(cmd) return self.receive()
#!/usr/bin/env python3 from i2c import I2C import argparse import app_api import sys # choose i2c bus i2c_device = I2C(bus = 1) # get services from api SERVICES = app_api.Services() def on_boot(logger): print("OnBoot logic") def on_command(logger): print("OnBoot logic") slave_address = 0x51 num_read = 20 data = def main(): logger = app_api.logging_setup("i2c-app") parser = argparse.ArgumentParser()
def get_range(self, sensor): """Requests the last measurement of a specific sensor""" cmd = I2C.pack8(Command.MeasureOne, sensor) self.send(cmd) r = self.receive(2) return I2C.pack16(r[1], r[0])