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, 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 __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 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 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 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, 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 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 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()
def __init__(self): """ """ # RELAY self.CON_PIN1_2 = 4 self.CON_PIN3_4 = 17 self.CON_PIN5_6 = 27 self.CON_PIN7_8 = 22 self.CON_PIN9_10 = 10 self.CON_PIN11_12 = 9 self.CON_PIN13_14 = 11 self.CON_PIN15_16 = 5 self.CON_PIN17_18 = 6 self.CON_PIN19_20 = 13 # LED self.GREEN_LED = 19 self.STATUS_GREEN_LED = 0 self.STATUS_RED_LED = 0 # BUTTON self.START_BUTTON = 26 # OPTO self.OPTO1 = 16 self.OPTO2 = 12 self.OPTO3 = 7 self.OPTO4 = 8 self.OPTOAUX = 20 self.MOVE_IN = 21 # ST-Link self.TCK = 25 self.TMS = 24 self.NRST = 23 # Serial self.Port = Port() self.Port.open() # I2C self.I2C_ADC = I2C(0x36) self.I2C_PINS = I2C(0x20) self.I2C_PINS_Mascara = 0x00 self.RED_LED = 0x01 self.BTN1 = 0x02 self.BTN2 = 0x04 self.BTN3 = 0x08 self.BTN4 = 0x10 self.BTN5 = 0x20 self.BTN6 = 0x40 self.BTN7 = 0x80 self.Status_OPTO = False self.Status_RELE = False self.Status_REGULADOR = False self.Status_ENERGIA = False self.Status_PRESSAO = False self.Status_XBEE = False self.Status_BTN = False self.PWM = None
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 = []
from sensors import SCD30, SDS011, BME280, DGR8H from time import sleep from schedule import every, run_pending from buttons import Buttons from IT8951 import Display, DisplayModes from presenter import Presenter from utils import * from scrape import load_websites init_logger() log = logging.getLogger("AirMonitor") db = AirMonitorDbClient("test") i2c = I2C(bus=1) scd30 = SCD30(i2c, 0x61) bme280 = BME280(i2c, 0x76) sds011 = SDS011("/dev/ttyS0") dgr8h = DGR8H(18) buttons = Buttons([20, 21]) disp = Display(vcom=-1.64) presenter = Presenter(db) refresh_interval = 5 * 60 @catch_exceptions() def init_scd30(): scd30.start_continous_measurement() scd30.set_measurement_interval(10)
def __init__(self, address=0x68, alpf=2, glpf=1): self.i2c = I2C(address) self.address = address self.min_az = 0.0 self.max_az = 0.0 self.min_gx = 0.0 self.max_gx = 0.0 self.min_gy = 0.0 self.max_gy = 0.0 self.min_gz = 0.0 self.max_gz = 0.0 self.ax_offset = 0.0 self.ay_offset = 0.0 self.az_offset = 0.0 self.gx_offset = 0.0 self.gy_offset = 0.0 self.gz_offset = 0.0 logger.info('Reseting MPU-6050') #------------------------------------------------------------------------------------------- # Reset all registers #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_PWR_MGMT_1, 0x80) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Sets sample rate to 1kHz/(1+0) = 1kHz or 1ms (note 1kHz assumes dlpf is on - setting # dlpf to 0 or 7 changes 1kHz to 8kHz and therefore will require sample rate divider # to be changed to 7 to obtain the same 1kHz sample rate. #------------------------------------------------------------------------------------------- sample_rate_divisor = int(round(adc_frequency / sampling_rate)) logger.warning("SRD:, %d", sample_rate_divisor) self.i2c.write8(self.__MPU6050_RA_SMPLRT_DIV, sample_rate_divisor - 1) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Sets clock source to gyro reference w/ PLL #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_PWR_MGMT_1, 0x01) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Gyro DLPF => 1kHz sample frequency used above divided by the sample divide factor. # # 0x00 = 250Hz @ 8kHz sampling - DO NOT USE, THE ACCELEROMETER STILL SAMPLES AT 1kHz WHICH PRODUCES EXPECTED BUT NOT CODED FOR TIMING AND FIFO CONTENT PROBLEMS # 0x01 = 184Hz # 0x02 = 92Hz # 0x03 = 41Hz # 0x04 = 20Hz # 0x05 = 10Hz # 0x06 = 5Hz # 0x07 = 3600Hz @ 8kHz # # 0x0* FIFO overflow overwrites oldest FIFO contents # 0x4* FIFO overflow does not overwrite full FIFO contents #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_CONFIG, 0x40 | glpf) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Disable gyro self tests, scale of +/- 250 degrees/s # # 0x00 = +/- 250 degrees/s # 0x08 = +/- 500 degrees/s # 0x10 = +/- 1000 degrees/s # 0x18 = +/- 2000 degrees/s # See SCALE_GYRO for conversion from raw data to units of radians per second #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_GYRO_CONFIG, int(round(math.log(self.__RANGE_GYRO / 250, 2))) << 3) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Accel DLPF => 1kHz sample frequency used above divided by the sample divide factor. # # 0x00 = 460Hz # 0x01 = 184Hz # 0x02 = 92Hz # 0x03 = 41Hz # 0x04 = 20Hz # 0x05 = 10Hz # 0x06 = 5Hz # 0x07 = 460Hz #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU9250_RA_ACCEL_CFG_2, alpf) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Disable accel self tests, scale of +/-8g # # 0x00 = +/- 2g # 0x08 = +/- 4g # 0x10 = +/- 8g # 0x18 = +/- 16g # See SCALE_ACCEL for convertion from raw data to units of meters per second squared #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_ACCEL_CONFIG, int(round(math.log(self.__RANGE_ACCEL / 2, 2))) << 3) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Set INT pin to push/pull, latch 'til read, any read to clear #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_INT_PIN_CFG, 0x30) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Initialize the FIFO overflow interrupt 0x10 (turned off at startup). #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_INT_ENABLE, 0x00) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Enabled the FIFO. #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_USER_CTRL, 0x40) #------------------------------------------------------------------------------------------- # Accelerometer / gyro goes into FIFO later on - see flushFIFO() #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_FIFO_EN, 0x00) #------------------------------------------------------------------------------------------- # Read ambient temperature #------------------------------------------------------------------------------------------- temp = self.readTemperature() logger.critical("IMU core temp (boot): ,%f", temp / 333.86 + 21.0)
def __init__(self): self.i2c = I2C() self.wk = Workflows() pass
def main(args=None): sw = switch_4() smb = I2C() par = parse() adc = ADC() pers = _8bitIO() port = _16bitIO() parser = par.get_parser() args = parser.parse_args(args) #inspect the command line err_flag = False if ((args.i2c0 and not args.i2c1) or (args.i2c1 and not args.i2c0)): try: data = smb.parse_func(args.data[0]) except: err_flag = True raise print('Error parsing or invalid syntax, use "-h" for help') if not err_flag: if i2c.w_found and not i2c.r_found: try: smb.write(data[0], data[1], not args.i2c0) # data[0] is data_i, data[1] is data_w print('ACK') except IOError: print('NACK...confirm you are transacting with the correct bus') except: raise print('Invalid Syntax') if not i2c.w_found and not i2c.r_found: try: smb.detect(data[0], not args.i2c0) print('ACK') except: print('NACK...confirm you are transacting with the correct bus') if i2c.r_found and not i2c.w_found: try: smb.read(data[0], data[2], not args.i2c0) except IOError: print('NACK...confirm you are transacting with the correct bus') except: raise print('Invalid Syntax') if i2c.r_found and i2c.w_found: smb.write_read(data[0], data[2], data[1], not args.i2c0) elif args.gpio and 'getall' in args.data: try: os.system('raspi-gpio get') except: print('Invalid syntax') elif args.gpio and 'get' in args.data: try: os.system('raspi-gpio get ' + args.data[1]) print('Success') except: print('Invalid syntax') elif args.gpio and 'set' in args.data: if len(args.data) == 3: try: os.system('raspi-gpio set ' + args.data[1] + ' ' + args.data[2]) print('Success') except: print('Invalid syntax') if len(args.data) == 4: try: os.system('raspi-gpio set ' + args.data[1] + ' ' + args.data[2] + ' ' + args.data[3]) print('Success') except: print('Invalid syntax') if len(args.data) == 5: try: os.system('raspi-gpio set ' + args.data[1] + ' ' + args.data[2] + ' ' + args.data[3] + ' ' + args.data[4]) print('Success') except: print('Invalid syntax') elif args.adc: if args.data[0] == 'raw' and len(args.data) == 2: try: adc.raw_adc(args.data[1]) except IOError: print('NACK...confirm device is powered on') except: print('Invalid syntax') elif args.data[0] == 'volt' and len(args.data) == 2: try: print(adc.volt_adc(args.data[1])) except IOError: print('NACK...confirm device is powered on') except: print('Invalid syntax') else: print('Invalid syntax') elif args.per: if(args.data[0] == 'config'): try: pers.configPorts() print('Success') except IOError: print('NACK...confirm device is powered on') except: print('Fail!') elif(args.data[0] == 'arm'): try: pers.arm(args.data[1], False) print('Success') except IOError: print('NACK...confirm device is powered on') except: print('Invalid syntax') elif(args.data[0] == 'disarm'): try: pers.arm(args.data[1], True) print('Success') except IOError: print('NACK...confirm device is powered on') except: print('Invalid syntax') elif(args.data[0] == 'read'): try: pers.read_inputs() print('Success') except IOError: print('NACK...confirm device is powered on') except: print('Invalid syntax') elif args.port: if(args.data[0] == 'config'): try: port.configPorts() print('Success') except IOError: print('NACK...confirm device is powered on') except: print('Fail!') elif args.data[0] == 'readall': try: port.zone_readall(args.data[1]) except IOError: print('NACK...confirm device is powered on') except: print('Invalid syntax') elif args.data[0] == 'read': try: port.zone_read(args.data[1], args.data[2]) except IOError: print('NACK...confirm device is powered on') except: print('Invalid syntax') elif args.data[0] == 'led': try: port.led_toggle(args.data[1], args.data[2], args.data[3]) except IOError: print('NACK...confirm device is powered on') except: print('Invalid syntax') else: print('Invalid syntax') elif args.switch: if args.data[0] == 'write': try: sw.ch_write(args.data[1], args.data[2], args.data[3]) except IOError: print('NACK...confirm device is powered on') except: print('Invalid syntax') elif args.data[0] == 'readint': try: sw.read_int(args.data[1]) except IOError: print('NACK...confirm device is powered on') except: print('Invalid syntax') elif args.data[0] == 'read': try: sw.read_dat(args.data[1], args.data[2]) except IOError: print('NACK...confirm device is powered on') except: print('Invalid syntax') else: print('Invalid syntax')
#!/usr/bin/python from mcp3424 import MCP3424 from i2c import I2C import time import os """ This demo is inspired by https://github.com/abelectronicsuk/ABElectronics_Python_Libraries/ Initialise the ADC device using the default addresses and sample rate, change this value if you have changed the address selection jumpers. Sample rate can be 12, 14, 16 or 18 bit. """ i2c_instance = I2C() bus = i2c_instance.get_smbus() adc = MCP3424(bus, address=0x68, rate=18) while (True): # clear the console os.system('clear') # read from adc channels and print to screen print("Channel 1: %02f" % adc.read_voltage(1)) print("Channel 2: %02f" % adc.read_voltage(2)) print("Channel 3: %02f" % adc.read_voltage(3)) print("Channel 4: %02f" % adc.read_voltage(4)) # wait 0.5 seconds before reading the pins again
from i2c import I2C bus = I2C(0x20) print bus
#!/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()
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(