def __init__(self, bus=1, mode=I2C.MASTER, addr=WHO_AM_I): """MPU6050 Constructor. Initialize an I2C object to communicate with IMU. Waking up the device is required since it starts in sleep. We will use the conventions of a word in the MPU-6050 is 2 bytes or 16 bits. :param bus: I2C bus on pyboard. :param mode: Either master or slave mode. :param addr: Slave address that communicates with master (pyboard). """ self.i2c = I2C(bus) self.i2c.init(mode) self.addr = addr self.accel_data = [0.0] * 3 self.accel_range = 16.0 self.accel_rate = 2048.0 self.gyro_data = [0.0] * 3 self.gyro_range = 2000.0 self.gyro_rate = 16.4 self.block_buffer = bytearray(6) # Wake and initialize the accelerometer and gyro to highest sensitivity. self.wake() self._write_reg(0b00011000, ACCEL_CONFIG) self._write_reg(0b00011000, GYRO_CONFIG)
def __init__(self, i2c_num): self.i2c = I2C(i2c_num, I2C.MASTER, baudrate=100000) self.i2c.scan() self.i2c.is_ready(BMP180_I2C_ADDR) self.AC1 = self.short(self.getReg(0xAA)) self.AC2 = self.short(self.getReg(0xAC)) self.AC3 = self.short(self.getReg(0xAE)) self.AC4 = self.getReg(0xB0) self.AC5 = self.getReg(0xB2) self.AC6 = self.getReg(0xB4) self.B1 = self.short(self.getReg(0xB6)) self.B2 = self.short(self.getReg(0xB8)) self.MB = self.short(self.getReg(0xBA)) self.MC = self.short(self.getReg(0xBC)) self.MD = self.short(self.getReg(0xBE)) self.UT = 0 self.UP = 0 self.B3 = 0 self.B4 = 0 self.B5 = 0 self.B6 = 0 self.B7 = 0 self.X1 = 0 self.X2 = 0 self.X3 = 0
def test_main(): """Test function for verifying basic functionality.""" print("Running test_main") i2c = I2C(1, I2C.MASTER) lcd = I2cLcd(i2c, DEFAULT_I2C_ADDR, 2, 16) lcd.putstr("SnekTek!\nSsSssSSsss") delay(3000) lcd.clear() count = 0 while True: lcd.move_to(0, 0) lcd.putstr("%7d" % (millis() // 1000)) delay(1000) count += 1 if count % 10 == 3: print("Turning backlight off") lcd.backlight_off() if count % 10 == 4: print("Turning backlight on") lcd.backlight_on() if count % 10 == 5: print("Turning display off") lcd.display_off() if count % 10 == 6: print("Turning display on") lcd.display_on() if count % 10 == 7: print("Turning display & backlight off") lcd.backlight_off() lcd.display_off() if count % 10 == 8: print("Turning display & backlight on") lcd.backlight_on() lcd.display_on()
def __init__(self, port=1, addr=0x69): self.bus = I2C(port, I2C.MASTER) self.addr = addr self.setPowerManagement(0x00) self.setSampleRateDivider(0x07) self.setDLPFAndFullScale(self.FullScale_2000_sec, self.DLPF_188_1) self.setInterrupt(self.IC_LatchUntilIntCleared, self.IC_IntOnDeviceReady, self.IC_IntOnDataReady)
def main(): """Main function.""" print("main_test(): start") micropython.alloc_emergency_exception_buf(100) ## Create the LCD instance. i2c = I2C(1, I2C.MASTER) lcd = I2cLcd(i2c, 0x27, 4, 20) ## Create the keypad instance. keypad = Keypad_uasyncio(queue_size=4, start=True) ## Get a handle to the asyncio event loop. loop = asyncio.get_event_loop() ## Add the keypad scanning and keypad watcher coroutines. loop.create_task(keypad.scan_coro()) loop.create_task(keypad_lcd_task(lcd=lcd, keypad=keypad)) ## Start running the coroutines loop.run_forever() print("main_test(): end")
def init_i2c(q, bus=2, role=I2C.MASTER, baudrate=115200, self_addr=0x42): q.i2c = I2C(bus) q.addr = self_addr q.br = baudrate q.i2c.init(role, addr=q.addr, baudrate=q.br) print('I2C initialized: self_addr=0x{0:02X} = {0} dec, br={1}'.\ format(q.addr, q.br))
def get_data(): s_light = pyb.ADC(pyb.Pin.cpu.A4) s_humidity = pyb.ADC(pyb.Pin.cpu.A1) s_temp = I2C(2, I2C.MASTER, baudrate=100000) #Y9-10 s_flex = pyb.ADC(pyb.Pin.cpu.A0) print("Light:", s_light.read(), "Humidity:", s_humidity.read(), "WindSpeed:", s_flex.read(), " "), pyb.LED(4).on()
def getPressure(self): """Pressure, Temperature (and Humidity) Args: None Returns: None Raises: None """ from BME280 import BME280 from pyb import I2C i2c = I2C(1, I2C.MASTER) bme = BME280(i2c=i2c) comment = '' # Log electrical conductivity temperature = 0 pressure = 0 humidity = 0 status_qualifier = 'Success' if self.test: status_qualifier = 'Test' try: temperature, pressure, humidity = bme.get_data() #print("T", temperature) except Exception as e: #print("Exception", e) status_qualifier = 'Failure' if test: status_qualifier = 'Test' comment = str(e) self._temperature = temperature # save for EC compensation subject = 'Water' sensor = 'BME280' attribute = 'Pressure' unit = 'mbar' print("T2", temperature) self.save_Env(subject, attribute, "{:1.1f}".format(pressure), unit, sensor, status_qualifier, comment) attribute = 'Temperature' unit = 'C' self.save_Env(subject, attribute, "{:1.1f}".format(temperature), unit, sensor, status_qualifier, comment) attribute = 'Humidity' unit = '%' self.save_Env(subject, attribute, "{:1.1f}".format(humidity), unit, sensor, status_qualifier, comment)
def run(): # Test of continuous data reading from pyb import I2C i2c = I2C(1, I2C.MASTER) b = BME280(i2c=i2c) while True: t, p, h = b.get_data() print("{:.2f}C".format(t)) print("{:.2f}hPa".format(p / 100)) print("{:.2f}%".format(h)) time.sleep(2)
def __init__(self, port=2, address=30, gauss="1.3", declination=(0, 0)): self.bus = I2C(port, I2C.MASTER, baudrate=100000) self.address = address degrees, minutes = declination self.__declDegrees = degrees self.__declMinutes = minutes self.__declination = (degrees + minutes / 60) * math.pi / 180 reg, self.__scale = self.__scales[gauss] self.bus.mem_write(0x70, self.address, 0x00) # 8 Average, 15 Hz, normal measurement self.bus.mem_write(reg << 5, self.address, 0x01) # Scale self.bus.mem_write(0x00, self.address, 0x02) # Continuous measurement
def __init__(self, addr=reg.I2C_ADDRESS, bus=True, mode=True): """ Init I2C object :param addr: An address of I2C Device, default is 0x68 :param bus: Select the RX/TX bus of micro-python board True is (X9|SCL, X10|SDA), False is (Y9|SCL, Y10|SDA) :param mode: Select the I2C device mode, MASTER or SLAVE :return: None """ self._ADDR = addr if bus: self._mpu = I2C(self._BUS[0]) else: self._mpu = I2C(self._BUS[1]) # Init I2C object if mode: self._dev_init(self._MODE[0]) else: self._dev_init(self._MODE[1])
def init_i2c(self, bus=2, role=I2C.MASTER, baudrate=115200, self_addr=0x42): self.i2c = I2C(bus) self.addr = self_addr self.br = baudrate self.i2c.init(role, addr=self.addr, baudrate=self.br) print('I2C initialized: self_addr=0x{0:02X} = {0} dec, br={1}'.\ format(self.addr, self.br))
def __init__(self): self.saddres = 104 self.accel = 0 self.env_gyr = 0 self.env_accel = 0 self.gyr = 0 self.acel = 2 self.tem = 340 self.g = 0 self.y = 128 self.sen = 0 self.i2c = I2C(1, I2C.MASTER) self.i2c.init(I2C.MASTER, baudrate=400000)
def PCA8574_tests(): try: # Initialize I2C 1 i2c = I2C(I2C_BUS1, I2C.MASTER, baudrate=100000) # returns list of slave addresses I2C_List = i2c.scan() if I2C_List: print("I2C Slaves Present =", I2C_List) else: print("There are no I2C devices present! Exiting application.") sys.exit(0) except Exception as e: print(e) p_out = Pin('PD14', Pin.OUT_PP) p_out.high() # Test that we can initialize the object try: PCA8574_Object = PCA8574_IO(i2c, I2C_List[0]) print("PCA8574, Object Creation, Passed") except: print("PCA8574, Object Creation, Failed") try: PCA8574_Object1 = PCA8574_IO(i2c, 256) print("PCA8574, I2C Address Out-of-Bounds, Failed") except: print("PCA8574, I2C Address Out-of-Bounds, Passed") ####### # Test reading the switch ####### # Set the switch to not pressed p_out.high() Result = PCA8574_Object.Read() if Result is 0xFF: print("PCA8574, LSB I/O - High, Passed") else: print("PCA8574, LSB I/O - High, Failed,", Result) # Set the switch to pressed p_out.low() Result = PCA8574_Object.Read() if Result is 0xFE: print("PCA8574, LSB I/O - Low, Passed") else: print("PCA8574, LSB I/O - Low, Failed,", Result)
def __init__(self, pin: int, addr: int, slot: int): """Initialize I2C communication to motor. Args: pin: I2C bus' pin (2 or 4) addr: slave's address slot: motor's slot (1 or 2) """ self.__slot = slot - 1 self.__addr = addr self.__i2c = I2C(pin) self.__i2c.init(I2C.MASTER) self.__speed = 0 self._stopper = Timer(callback=self.stop)
def __init__(self): print("start") self.i2c = I2C(2, I2C.MASTER) # create and init as a master self.i2c.init(I2C.MASTER, baudrate=100000) # init as a master # init as a slave with given address print("initialized") self.i2c.is_ready(0x1D) #i2c.send(0x00, addr=0x1D) a = self.i2c.mem_read(1, 0x1D, 0) print(a) self.i2c.mem_write(0x31, 0x1D, 0x31) # self.i2c.send(0x31, 0x1D) # self.i2c.send(0x31, 0x1D) self.i2c.mem_write(0x08, 0x1D, 0x2D)
def init_lcd(self): self.i2c = I2C(1, I2C.MASTER) self.i2c.init(I2C.MASTER, baudrate=400000) # 400kHz self.send_command(0x38) self.send_command(0x39) self.send_command(0x14) self.send_command(0x70) # Voltage 3.3v self.send_command(0x56) # Voltage 3.3v self.send_command(0x6C) time.sleep(0.2) self.send_command(0x38) self.send_command(0x0C) self.send_command(0x01) time.sleep(1.2)
def __init__(self, all_resistors=[1600, 800, 400, 200, 100, 50, 25, 12.5, 6.25, 3.125]): """Inits Resistor class.""" self.all_resistors = all_resistors self.current_resistor_binary = [1,1,1,1,1,1,1,1,1,1] self.current_resistor = (self.dot_prod(self.negate_binary_list(self.current_resistor_binary), self.all_resistors) + 1000.0) self.i2c = I2C(2) self.i2c = I2C(2, I2C.MASTER) self.i2c.init(I2C.MASTER, baudrate=20000) info = self.i2c.scan() #print("scan ",info) #LCD self.lcd = lcd160cr.LCD160CR('YX') self.lcd.set_orient(lcd160cr.LANDSCAPE) self.lcd.set_pos(30, 20) self.lcd.set_text_color(self.lcd.rgb(255, 255, 255), self.lcd.rgb(0, 0, 0)) self.lcd.set_font(1,1,0,0,0) self.lcd.erase() self.lcd.set_pos(25, 60) self.lcd.write("0000.000Ω") self.adc = pyb.ADC(pyb.Pin('X19')) self.adc_value = float(self.adc.read()/4096.0)
def __init__(self, i2c_id=2, address=0x57, pin='X1'): print("intpin: {0}, address: {1}".format(pin, address)) self.i2c = I2C(i2c_id, I2C.MASTER, baudrate=400000) self.address = address self.interrupt = Pin(pin, Pin.IN) #设置中断引脚为输入模式 self.reset() #软复位 pyb.delay(1000) #reg_data = self.i2c.mem_read(1, self.address, REG_INTR_STATUS_1) addr = self.i2c.scan() if address not in addr: print('max30102 device not found') elif not self.i2c.is_ready(address): print('max30102 device not response') else: self.setup()
def __init__( self, movementscls=MovementsCls ): """:Params movementscls: list of Movement classes available to the robot.""" self.i2c = I2C( 2, I2C.MASTER ) RobotBase.__init__( self, controlers=[(self.i2c,0x40)], movementscls=MovementsCls ) # PCA9685 is wired on I2C 2 self.members.append( Member2DF( self, 0, 1) ) # Front right self.members.append( Member2DF( self, 2, 3) ) # Front left self.members.append( Member2DF( self, 6, 7) ) # Rear right self.members.append( Member2DF( self, 4, 5) ) # Rear left self.members[1].shoulder.inverted(True) # Invert control on member 1 shoulder self.members[3].shoulder.inverted(True) self.members[1].wrist.inverted(True) # Invert control on member 2 wrist self.members[3].wrist.inverted(True) self.reset()
def luxMittaus(): i2c = I2C(1, I2C.MASTER, baudrate=100000) i2c.send(0x49, 0x39) luettu = i2c.recv(1, 0x39) i2c.send(0x83, 0x39) luettu2 = i2c.recv(1, 0x39) chord = (luettu[0] >> 4) & 7 chord2 = (luettu2[0] >> 4) & 7 step = (luettu[0]) & 15 step2 = (luettu2[0]) & 15 countvalue = (int(16.5 * ((2**chord) - 1)) + (step * (2**chord))) countvalue2 = (int(16.5 * ((2**chord2) - 1)) + (step2 * (2**chord2))) luxit = (countvalue * 0.46 * (math.exp( (-3.13 * countvalue2 / countvalue)))) print("Valon intensiteetti on:", luxit, "luxia.") return luxit
def __init__(self, bus, address=0x76): """Create an Bmp280_i2c object. Arguments: bus: which connections we use. address: I2C address. Defaults to 0x76 """ self._i2c = I2C(bus, I2C.MASTER) self._address = address self._temp = None self._press = None # Read the compensation coefficients. data = self._i2c.mem_read(24, self._address, REG_COMP) comp = unpack("<HhhHhhhhhhhh", data) comp = [float(j) for j in comp] self._tempcal = comp[:3] self._presscal = comp[3:]
def test(): # Validation test print("Testing BME280") try: from pyb import I2C i2c = I2C(1, I2C.MASTER) b = BME280(i2c=i2c) except Exception as e: print("ERROR: Failure creating BME280 sensor") return t, p, h = b.get_data() print("{:.2f}C".format(t)) print("{:.2f}hPa".format(p / 100)) print("{:.2f}%".format(h)) print("Altitude", "{:.2f}".format(b.altitude)) print("Dew point", "{:.2f}".format(b.dew_point)) print("Done")
def __init__(self, id=1, addr=0x42): self._id = id self._addr = addr self.i2c = I2C(self._id) self.i2c.init(I2C.SLAVE, addr=self._addr) self._txbuffer = bytearray(4 * READINGS_LENGTH) self._txsendretries = 0 self._mv_txbuffer = memoryview( self._txbuffer ) #pointer for speed optimization, slicing will not create a new buffer self._headings_mv = None self._distance_mv = None self._send_mode = 0 self._num_in_txbuff = 0 self._rxbuffer = bytearray(32) self._mv_rxbuffer = memoryview( self._rxbuffer ) #pointer for speed optimization, slicing will not create a new buffer
def __init__(self, port=1, address=BMP085_ADDRESS, mode=BMP085_STANDARD, debug=False): self.i2c = I2C(port, I2C.MASTER) self.address = address self.debug = debug # Make sure the specified mode is in the appropriate range if ((mode < 0) | (mode > 3)): if (self.debug): print("Invalid Mode: Using STANDARD by default") self.mode = self.BMP085_STANDARD else: self.mode = mode # Read the calibration data self.readCalibrationData()
def __init__(self, led): self.led = led self.i2c = I2C(2, I2C.MASTER) self.buf1 = bytearray(2) self.buf2 = bytearray(2) self.buf1 = self.i2c.mem_read(2, 0x26, 0) self.buf2 = self.i2c.mem_read(2, 0x27, 0) self.intr1 = 0 self.intr2 = 0 self.counter = 0 self.left_down = Pin('X12', Pin.IN, Pin.PULL_UP) self.left_enter = Pin('Y12', Pin.IN, Pin.PULL_UP) self.camera = Pin('X11', Pin.IN, Pin.PULL_UP) self.u6 = UART(6, baudrate=9600, read_buf_len=4096) print(self.buf1) print(self.buf2) print("hello world") ExtInt('X19', ExtInt.IRQ_FALLING, Pin.PULL_UP, self.intr1_cb) ExtInt('X20', ExtInt.IRQ_FALLING, Pin.PULL_UP, self.intr2_cb)
def __init__(self, rst=None, address=BNO055_ADDRESS_A, i2c=1, gpio=None, serial_port=None, serial_timeout_sec=5, **kwargs): # If reset pin is provided save it and a reference to provided GPIO # bus (or the default system GPIO bus if none is provided). self._rst = rst if self._rst is not None: # if gpio is None: # import Adafruit_GPIO as GPIO # gpio = GPIO.get_platform_gpio() # Setup the reset pin as an output at a high level. self._gpio = pyb.Pin(IMU_RESET_PIN, pyb.Pin.OUT_OD) # self._gpio.setup(self._rst, GPIO.OUT) self._gpio.value(1) # Wait a 650 milliseconds in case setting the reset high reset the chip. pyb.delay(650) self._serial = None self._i2c_device = None if serial_port is not None: # Use serial communication if serial_port name is provided. # Open the serial port at 115200 baud, 8N1. Add a 5 second timeout # to prevent hanging if device is disconnected. self._serial = serial.Serial(serial_port, 115200, timeout=serial_timeout_sec, writeTimeout=serial_timeout_sec) else: # Use I2C if no serial port is provided. # Assume we're using platform's default I2C bus if none is specified. # if i2c is None: # import Adafruit_GPIO.I2C as I2C # i2c = I2C # Save a reference to the I2C device instance for later communication. # self._i2c_device = I2C(i2c) self._i2c_device = I2C(1, I2C.MASTER)
def __init__(self, i2c_bus=1, address=36, reset=None, req=None, debug=False): self.debug = debug if reset: if debug: print("Resetting") _reset(reset) self.debug = debug self._req = req self._i2c = I2C(i2c_bus, I2C.MASTER) self.address = address self._wakeup() assert self.address in self._i2c.scan()
def pins_test(): i2c = I2C(1, I2C.MASTER) spi = SPI(2, SPI.MASTER) uart = UART(3, 9600) servo = Servo(1) adc = ADC(Pin.board.X3) dac = DAC(1) pin = Pin('X4', mode=Pin.AF_PP, af=Pin.AF3_TIM9) pin = Pin('Y1', mode=Pin.AF_OD, af=3) pin = Pin('Y2', mode=Pin.OUT_PP) pin = Pin('Y3', mode=Pin.OUT_OD, pull=Pin.PULL_UP) pin.high() pin = Pin('Y4', mode=Pin.OUT_OD, pull=Pin.PULL_DOWN) pin.high() pin = Pin('X18', mode=Pin.IN, pull=Pin.PULL_NONE) pin = Pin('X19', mode=Pin.IN, pull=Pin.PULL_UP) pin = Pin('X20', mode=Pin.IN, pull=Pin.PULL_DOWN) print('===== output of pins() =====') pins() print('===== output of af() =====') af()
def __init__(self, name: str, size: int, i2c: int, wp: str, a0: str, a1: str, a2: str, i2c_addr: int = 80, addr_bytes_num: int = 16) -> None: self.name = name self.size = size self.addr_bytes_num = addr_bytes_num self.a0 = Pin(a0, Pin.OUT_PP) self.a1 = Pin(a1, Pin.OUT_PP) self.a2 = Pin(a2, Pin.OUT_PP) self.wp = Pin(wp, Pin.OUT_PP) self.i2c = I2C(i2c, I2C.MASTER, baudrate=20000) # item_size to prevent memory allocation error in dump() self.item_size = size if size <= MAX_READ_ITEM_SIZE else MAX_READ_ITEM_SIZE self.items_cnt = self.size // self.item_size self.i2c_addr = i2c_addr