Python digitalio.DigitalInOut() Examples

The following are 21 code examples of digitalio.DigitalInOut(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module digitalio , or try the search function .
Example #1
Source File: clue.py    From Adafruit_CircuitPython_PyBadger with MIT License 8 votes vote down vote up
def __init__(self):
        super().__init__()

        i2c = board.I2C()

        if i2c is not None:
            self._accelerometer = adafruit_lsm6ds.LSM6DS33(i2c)

        # NeoPixels
        self._neopixels = neopixel.NeoPixel(
            board.NEOPIXEL, self._neopixel_count, brightness=1, pixel_order=neopixel.GRB
        )

        self._buttons = GamePad(
            digitalio.DigitalInOut(board.BUTTON_A),
            digitalio.DigitalInOut(board.BUTTON_B),
        ) 
Example #2
Source File: lis3dh.py    From tinypico-micropython with MIT License 6 votes vote down vote up
def tapped(self):
        """
        True if a tap was detected recently. Whether its a single tap or double tap is
        determined by the tap param on ``set_tap``. ``tapped`` may be True over
        multiple reads even if only a single tap or single double tap occurred if the
        interrupt (int) pin is not specified.

        The following example uses ``i2c`` and specifies the interrupt pin:

        .. code-block:: python

            import adafruit_lis3dh
            import digitalio

            i2c = busio.I2C(board.SCL, board.SDA)
            int1 = digitalio.DigitalInOut(board.D11) # pin connected to interrupt
            lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, int1=int1)
            lis3dh.range = adafruit_lis3dh.RANGE_8_G

        """
        if self._int1 and not self._int1.value:
            return False
        raw = self._read_register_byte(_REG_CLICKSRC)
        return raw & 0x40 > 0 
Example #3
Source File: soil.py    From aws-builders-fair-projects with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        Sensor.__init__(self)

        self.moisture_min = float(self.config["soil"]["min"])
        self.moisture_max = float(self.config["soil"]["max"])

        # create SPI bus
        spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

        # create the cs (chip select)
        cs = digitalio.DigitalInOut(board.D8)

        # create the mcp object
        mcp = MCP.MCP3008(spi, cs)
        
        # create an analog input channel
        self.pin = []
        self.pin.append(AnalogIn(mcp, MCP.P0))
        self.pin.append(AnalogIn(mcp, MCP.P1))
        self.pin.append(AnalogIn(mcp, MCP.P2))
        self.pin.append(AnalogIn(mcp, MCP.P3))
        self.pin.append(AnalogIn(mcp, MCP.P4))
        self.pin.append(AnalogIn(mcp, MCP.P5))
        self.pin.append(AnalogIn(mcp, MCP.P6))
        self.pin.append(AnalogIn(mcp, MCP.P7)) 
Example #4
Source File: neopixel.py    From Adafruit_CircuitPython_NeoPixel with MIT License 6 votes vote down vote up
def __init__(
        self, pin, n, *, bpp=3, brightness=1.0, auto_write=True, pixel_order=None
    ):
        if not pixel_order:
            pixel_order = GRB if bpp == 3 else GRBW
        else:
            if isinstance(pixel_order, tuple):
                order_list = [RGBW[order] for order in pixel_order]
                pixel_order = "".join(order_list)

        super().__init__(
            n, brightness=brightness, byteorder=pixel_order, auto_write=auto_write
        )

        self.pin = digitalio.DigitalInOut(pin)
        self.pin.direction = digitalio.Direction.OUTPUT 
Example #5
Source File: rgb_display_pillow_animated_gif.py    From Adafruit_CircuitPython_RGB_Display with MIT License 6 votes vote down vote up
def init_button(pin):
    button = digitalio.DigitalInOut(pin)
    button.switch_to_input()
    button.pull = digitalio.Pull.UP
    return button


# pylint: disable=too-few-public-methods 
Example #6
Source File: bluefruit.py    From Adafruit_CircuitPython_CircuitPlayground with MIT License 6 votes vote down vote up
def __init__(self):
        # Only create the cpb module member when we aren't being imported by Sphinx
        if (
            "__module__" in dir(digitalio.DigitalInOut)
            and digitalio.DigitalInOut.__module__ == "sphinx.ext.autodoc"
        ):
            return

        super().__init__()

        self._sample = None

        # Define mic/sound sensor:
        self._mic = audiobusio.PDMIn(
            board.MICROPHONE_CLOCK,
            board.MICROPHONE_DATA,
            sample_rate=16000,
            bit_depth=16,
        )
        self._samples = None 
Example #7
Source File: express.py    From Adafruit_CircuitPython_CircuitPlayground with MIT License 5 votes vote down vote up
def __init__(self):
        # Only create the cpx module member when we aren't being imported by Sphinx
        if (
            "__module__" in dir(digitalio.DigitalInOut)
            and digitalio.DigitalInOut.__module__ == "sphinx.ext.autodoc"
        ):
            return

        super().__init__() 
Example #8
Source File: character_lcd.py    From Adafruit_CircuitPython_CharLCD with MIT License 5 votes vote down vote up
def __init__(
        self,
        rs,
        en,
        db4,
        db5,
        db6,
        db7,
        columns,
        lines,
        red,
        green,
        blue,
        read_write=None,
    ):

        # Define read_write (rw) pin
        self.read_write = read_write

        # Setup rw pin if used
        if read_write is not None:
            self.read_write.direction = digitalio.Direction.OUTPUT

        # define color params
        self.rgb_led = [red, green, blue]

        for pin in self.rgb_led:
            if hasattr(pin, "direction"):
                # Assume a digitalio.DigitalInOut or compatible interface:
                pin.direction = digitalio.Direction.OUTPUT
            elif not hasattr(pin, "duty_cycle"):
                raise TypeError(
                    "RGB LED objects must be instances of digitalio.DigitalInOut"
                    " or pulseio.PWMOut, or provide a compatible interface."
                )

        self._color = [0, 0, 0]
        super().__init__(rs, en, db4, db5, db6, db7, columns, lines) 
Example #9
Source File: character_lcd.py    From Adafruit_CircuitPython_CharLCD with MIT License 5 votes vote down vote up
def color(self, color):
        self._color = color
        for number, pin in enumerate(self.rgb_led):
            if hasattr(pin, "duty_cycle"):
                # Assume a pulseio.PWMOut or compatible interface and set duty cycle:
                pin.duty_cycle = int(_map(color[number], 0, 100, 65535, 0))
            elif hasattr(pin, "value"):
                # If we don't have a PWM interface, all we can do is turn each color
                # on / off.  Assume a DigitalInOut (or compatible interface) and write
                # 0 (on) to pin for any value greater than 0, or 1 (off) for 0:
                pin.value = not color[number] > 1 
Example #10
Source File: adafruit_blinka.py    From Adafruit_Blinka with MIT License 5 votes vote down vote up
def test_context_manager(self):
        import digitalio
        from testing.board import default_pin

        """Deinitialisation is triggered by __exit__() and should dispose machine.pin reference"""
        dio = digitalio.DigitalInOut(default_pin)
        self.assertIsNotNone(dio._pin)
        with dio:
            pass
        self.assertIsNone(dio._pin) 
Example #11
Source File: adc_worker.py    From mudpi-core with MIT License 5 votes vote down vote up
def __init__(self, config: dict, main_thread_running, system_ready):
        self.config = config
        self.main_thread_running = main_thread_running
        self.system_ready = system_ready
        self.node_ready = False

        spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
        cs = digitalio.DigitalInOut(ADCMCP3008Worker.PINS[config['pin']])

        self.mcp = MCP.MCP3008(spi, cs)

        self.sensors = []
        self.init_sensors()

        self.node_ready = True 
Example #12
Source File: pybadger_base.py    From Adafruit_CircuitPython_PyBadger with MIT License 5 votes vote down vote up
def __init__(self):
        self._light_sensor = None
        self._accelerometer = None
        self._label = label
        self._y_position = 1
        self._background_group = None
        self._background_image_filename = None
        self._lines = []
        self._created_background = False

        # Display
        self.display = board.DISPLAY
        self._display_brightness = 1.0

        self._neopixels = None

        # Auto dim display based on movement
        self._last_accelerometer = None
        self._start_time = time.monotonic()

        # Define audio:
        if hasattr(board, "SPEAKER_ENABLE"):
            self._speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
            self._speaker_enable.switch_to_output(value=False)
        self._sample = None
        self._sine_wave = None
        self._sine_wave_sample = None 
Example #13
Source File: pybadge.py    From Adafruit_CircuitPython_PyBadger with MIT License 5 votes vote down vote up
def __init__(self):
        super().__init__()

        i2c = None

        if i2c is None:
            try:
                i2c = board.I2C()
            except RuntimeError:
                self._accelerometer = None

        if i2c is not None:
            int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT)
            try:
                self._accelerometer = adafruit_lis3dh.LIS3DH_I2C(
                    i2c, address=0x19, int1=int1
                )
            except ValueError:
                self._accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c, int1=int1)

        # NeoPixels
        self._neopixels = neopixel.NeoPixel(
            board.NEOPIXEL, self._neopixel_count, brightness=1, pixel_order=neopixel.GRB
        )

        self._buttons = GamePadShift(
            digitalio.DigitalInOut(board.BUTTON_CLOCK),
            digitalio.DigitalInOut(board.BUTTON_OUT),
            digitalio.DigitalInOut(board.BUTTON_LATCH),
        )

        self._light_sensor = analogio.AnalogIn(board.A7) 
Example #14
Source File: pygamer.py    From Adafruit_CircuitPython_PyBadger with MIT License 5 votes vote down vote up
def __init__(self):
        super().__init__()

        i2c = board.I2C()

        int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT)
        try:
            self._accelerometer = adafruit_lis3dh.LIS3DH_I2C(
                i2c, address=0x19, int1=int1
            )
        except ValueError:
            self._accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c, int1=int1)

        # NeoPixels
        self._neopixels = neopixel.NeoPixel(
            board.NEOPIXEL, self._neopixel_count, brightness=1, pixel_order=neopixel.GRB
        )

        self._buttons = GamePadShift(
            digitalio.DigitalInOut(board.BUTTON_CLOCK),
            digitalio.DigitalInOut(board.BUTTON_OUT),
            digitalio.DigitalInOut(board.BUTTON_LATCH),
        )

        self._pygamer_joystick_x = analogio.AnalogIn(board.JOYSTICK_X)
        self._pygamer_joystick_y = analogio.AnalogIn(board.JOYSTICK_Y)

        self._light_sensor = analogio.AnalogIn(board.A7) 
Example #15
Source File: pewpewm4.py    From Adafruit_CircuitPython_PyBadger with MIT License 5 votes vote down vote up
def __init__(self):
        super().__init__()

        self._buttons = GamePad(
            digitalio.DigitalInOut(board.BUTTON_O),
            digitalio.DigitalInOut(board.BUTTON_X),
            digitalio.DigitalInOut(board.BUTTON_Z),
            digitalio.DigitalInOut(board.BUTTON_RIGHT),
            digitalio.DigitalInOut(board.BUTTON_DOWN),
            digitalio.DigitalInOut(board.BUTTON_UP),
            digitalio.DigitalInOut(board.BUTTON_LEFT),
        ) 
Example #16
Source File: circuit_playground_base.py    From Adafruit_CircuitPython_CircuitPlayground with MIT License 4 votes vote down vote up
def __init__(self):
        self._a = digitalio.DigitalInOut(board.BUTTON_A)
        self._a.switch_to_input(pull=digitalio.Pull.DOWN)
        self._b = digitalio.DigitalInOut(board.BUTTON_B)
        self._b.switch_to_input(pull=digitalio.Pull.DOWN)
        self.gamepad = gamepad.GamePad(self._a, self._b)

        # Define switch:
        self._switch = digitalio.DigitalInOut(board.SLIDE_SWITCH)
        self._switch.switch_to_input(pull=digitalio.Pull.UP)

        # Define LEDs:
        self._led = digitalio.DigitalInOut(board.D13)
        self._led.switch_to_output()
        self._pixels = neopixel.NeoPixel(board.NEOPIXEL, 10)

        # Define sensors:
        self._temp = adafruit_thermistor.Thermistor(
            board.TEMPERATURE, 10000, 10000, 25, 3950
        )
        self._light = Photocell(board.LIGHT)

        # Define touch:
        # Initially, self._touches stores the pin used for a particular touch. When that touch is
        # used for the first time, the pin is replaced with the corresponding TouchIn object.
        # This saves a little RAM over using a separate read-only pin tuple.
        # For example, after `cp.touch_A2`, self._touches is equivalent to:
        # [None, board.A1, touchio.TouchIn(board.A2), board.A3, ...]
        # Slot 0 is not used (A0 is not allowed as a touch pin).
        self._touches = [
            None,
            board.A1,
            board.A2,
            board.A3,
            board.A4,
            board.A5,
            board.A6,
            board.TX,
        ]
        self._touch_threshold_adjustment = 0

        # Define acceleration:
        self._i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
        self._int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT)
        self._lis3dh = adafruit_lis3dh.LIS3DH_I2C(
            self._i2c, address=0x19, int1=self._int1
        )
        self._lis3dh.range = adafruit_lis3dh.RANGE_8_G

        # Define audio:
        self._speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
        self._speaker_enable.switch_to_output(value=False)
        self._sample = None
        self._sine_wave = None
        self._sine_wave_sample = None

        # Initialise tap:
        self._detect_taps = 1
        self.detect_taps = 1 
Example #17
Source File: matrix.py    From kmk_firmware with GNU General Public License v3.0 4 votes vote down vote up
def __init__(
        self,
        cols,
        rows,
        diode_orientation=DiodeOrientation.COLUMNS,
        rollover_cols_every_rows=None,
    ):
        self.len_cols = len(cols)
        self.len_rows = len(rows)

        # A pin cannot be both a row and column, detect this by combining the
        # two tuples into a set and validating that the length did not drop
        #
        # repr() hackery is because CircuitPython Pin objects are not hashable
        unique_pins = {repr(c) for c in cols} | {repr(r) for r in rows}
        assert (
            len(unique_pins) == self.len_cols + self.len_rows
        ), 'Cannot use a pin as both a column and row'
        del unique_pins
        gc.collect()

        self.diode_orientation = diode_orientation

        if self.diode_orientation == DiodeOrientation.COLUMNS:
            self.outputs = [digitalio.DigitalInOut(x) for x in cols]
            self.inputs = [digitalio.DigitalInOut(x) for x in rows]
            self.translate_coords = True
        elif self.diode_orientation == DiodeOrientation.ROWS:
            self.outputs = [digitalio.DigitalInOut(x) for x in rows]
            self.inputs = [digitalio.DigitalInOut(x) for x in cols]
            self.translate_coords = False
        else:
            raise ValueError(
                'Invalid DiodeOrientation: {}'.format(self.diode_orientation)
            )

        for pin in self.outputs:
            pin.switch_to_output()

        for pin in self.inputs:
            pin.switch_to_input(pull=digitalio.Pull.DOWN)

        self.rollover_cols_every_rows = rollover_cols_every_rows
        if self.rollover_cols_every_rows is None:
            self.rollover_cols_every_rows = self.len_rows

        self.len_state_arrays = self.len_cols * self.len_rows
        self.state = bytearray(self.len_state_arrays)
        self.report = bytearray(3) 
Example #18
Source File: apa102.py    From apa102-pi with GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, num_led=8, global_brightness=31,
                 order='rgb', mosi=10, sclk=11, ce=None, bus_speed_hz=8000000):
        """Initializes the library

        :param num_led: Number of LEDs in the strip
        :param global_brightness: Overall brightness
        :param order: Order in which the colours are addressed (this differs from strip to strip)
        :param mosi: Master Out pin. Use 10 for SPI0, 20 for SPI1, any GPIO pin for bitbang.
        :param sclk: Clock, use 11 for SPI0, 21 for SPI1, any GPIO pin for bitbang.
        :param ce: GPIO to use for Chip select. Can be any free GPIO pin. Warning: This will slow down the bus
                   significantly. Note: The hardware CE0 and CE1 are not used
        :param bus_speed_hz: Speed of the hardware SPI bus. If glitches on the bus are visible, lower the value.
        """
        self.num_led = num_led
        order = order.lower()  # Just in case someone use CAPS here.
        self.rgb = RGB_MAP.get(order, RGB_MAP['rgb'])
        self.global_brightness = global_brightness
        self.use_bitbang = False  # Two raw SPI devices exist: Bitbang (software) and hardware SPI.
        self.use_ce = False  # If true, use the BusDevice abstraction layer on top of the raw SPI device

        self.leds = [self.LED_START, 0, 0, 0] * self.num_led  # Pixel buffer
        if ce is not None:
            # If a chip enable value is present, use the Adafruit CircuitPython BusDevice abstraction on top
            # of the raw SPI device (hardware or bitbang)
            # The next line is just here to prevent an "unused" warning from the IDE
            digitalio.DigitalInOut(board.D1)
            # Convert the chip enable pin number into an object (reflection à la Python)
            ce = eval("digitalio.DigitalInOut(board.D"+str(ce)+")")
            self.use_ce = True
        # Heuristic: Test for the hardware SPI pins. If found, use hardware SPI, otherwise bitbang SPI
        if mosi == 10:
            if sclk != 11:
                raise ValueError("Illegal MOSI / SCLK combination")
            self.spi = busio.SPI(clock=board.SCLK, MOSI=board.MOSI)
        elif mosi == 20:
            if sclk != 21:
                raise ValueError("Illegal MOSI / SCLK combination")
            self.spi = busio.SPI(clock=board.SCLK_1, MOSI=board.MOSI_1)
        else:
            # Use Adafruit CircuitPython BitBangIO, because the pins do not match one of the hardware SPI devices
            # Reflection à la Python to get at the digital IO pins
            self.spi = bitbangio.SPI(clock=eval("board.D"+str(sclk)), MOSI=eval("board.D"+str(mosi)))
            self.use_bitbang = True
        # Add the BusDevice on top of the raw SPI
        if self.use_ce:
            self.spibus = SPIDevice(spi=self.spi,  chip_select=ce, baudrate=bus_speed_hz)
        else:
            # If the BusDevice is not used, the bus speed is set here instead
            while not self.spi.try_lock():
                pass
            self.spi.configure(baudrate=bus_speed_hz)
            self.spi.unlock()
        # Debug
        if self.use_ce:
            print("Use software chip enable")
        if self.use_bitbang:
            print("Use bitbang SPI")
        else:
            print("Use hardware SPI") 
Example #19
Source File: demo_circuitpython.py    From micropython-ssd1351 with MIT License 4 votes vote down vote up
def test():
    """CircuitPython Text, Shape & Sprite"""
    if implementation.name != 'circuitpython':
        print()
        print('This demo is for CircuitPython only!')
        exit()
    try:
        # Configuratoin for CS and DC pins:
        cs_pin = DigitalInOut(board.P0_15)
        dc_pin = DigitalInOut(board.P0_17)
        rst_pin = DigitalInOut(board.P0_20)

        # Setup SPI bus using hardware SPI:
        spi = SPI(clock=board.P0_24, MOSI=board.P0_22)

        # Create the SSD1351 display:
        display = Display(spi, dc=dc_pin, cs=cs_pin, rst=rst_pin)
        display.clear()

        # Load Fixed Font
        fixed = XglcdFont('fonts/FixedFont5x8.c', 5, 8, letter_count=96)

        # Title
        WIDTH = 128
        text = 'CircuitPython Demo'
        # Measure text and center
        length = fixed.measure_text(text)
        x = int((WIDTH / 2) - (length / 2))
        display.draw_text(x, 6, text, fixed, color565(255, 255, 0))

        # Draw title outline
        display.draw_rectangle(0, 0, 127, 20, color565(0, 255, 0))

        # Load sprite
        logo = BouncingSprite('images/blinka45x48.raw',
                              45, 48, 128, 128, 1, display)

        while True:
            timer = monotonic()
            logo.update_pos()
            logo.draw()
            # Attempt to set framerate to 30 FPS
            timer_dif = .033333333 - (monotonic() - timer)
            if timer_dif > 0:
                sleep(timer_dif)

    except KeyboardInterrupt:
        display.cleanup() 
Example #20
Source File: demo_scrolling_marquee.py    From micropython-ssd1351 with MIT License 4 votes vote down vote up
def test():
    """Scrolling Marquee"""

    try:
        # Implementation dependant pin and SPI configuration
        if implementation.name == 'circuitpython':
            import board
            from busio import SPI
            from digitalio import DigitalInOut
            cs_pin = DigitalInOut(board.P0_15)
            dc_pin = DigitalInOut(board.P0_17)
            rst_pin = DigitalInOut(board.P0_20)
            spi = SPI(clock=board.P0_24, MOSI=board.P0_22)
        else:
            from machine import Pin, SPI
            cs_pin = Pin(5)
            dc_pin = Pin(17)
            rst_pin = Pin(16)
            spi = SPI(2, baudrate=14500000, sck=Pin(18), mosi=Pin(23))

        # Create the SSD1351 display:
        display = Display(spi, dc=dc_pin, cs=cs_pin, rst=rst_pin)
        display.clear()

        # Draw non-moving circles
        display.fill_circle(63, 63, 63, color565(27, 72, 156))
        display.fill_circle(63, 63, 53, color565(0, 0, 0))
        display.fill_circle(63, 63, 43, color565(189, 0, 36))
        display.fill_circle(63, 63, 33, color565(0, 0, 0))

        # Load Marquee image
        display.draw_image('images\Rototron128x26.raw', 0, 50, 128, 26)

        # Set up scrolling
        display.set_scroll(horiz_offset=1, vert_start_row=50,
                           vert_row_count=26, vert_offset=0, speed=1)
        display.scroll(True)

        while True:
            # Do nothing, scrolling handled by hardware
            sleep(1)

    except KeyboardInterrupt:
        display.cleanup() 
Example #21
Source File: adafruit_dotstar.py    From Adafruit_CircuitPython_DotStar with MIT License 4 votes vote down vote up
def __init__(
        self,
        clock,
        data,
        n,
        *,
        brightness=1.0,
        auto_write=True,
        pixel_order=BGR,
        baudrate=4000000
    ):
        self._spi = None
        try:
            self._spi = busio.SPI(clock, MOSI=data)
            while not self._spi.try_lock():
                pass
            self._spi.configure(baudrate=baudrate)

        except (NotImplementedError, ValueError):
            self.dpin = digitalio.DigitalInOut(data)
            self.cpin = digitalio.DigitalInOut(clock)
            self.dpin.direction = digitalio.Direction.OUTPUT
            self.cpin.direction = digitalio.Direction.OUTPUT
            self.cpin.value = False

        # Supply one extra clock cycle for each two pixels in the strip.
        trailer_size = n // 16
        if n % 16 != 0:
            trailer_size += 1

        # Four empty bytes for the header.
        header = bytearray(START_HEADER_SIZE)
        # 0xff bytes for the trailer.
        trailer = bytearray(b"\xff") * trailer_size

        super().__init__(
            n,
            byteorder=pixel_order,
            brightness=brightness,
            auto_write=auto_write,
            header=header,
            trailer=trailer,
        )