Python源码示例:machine.SPI

示例1
def test():
    """Bouncing sprite."""
    try:
        # Baud rate of 14500000 seems about the max
        spi = SPI(2, baudrate=14500000, sck=Pin(18), mosi=Pin(23))
        display = Display(spi, dc=Pin(17), cs=Pin(5), rst=Pin(16))
        display.clear()

        # Load sprite
        logo = BouncingSprite('images/Python41x49.raw',
                              41, 49, 128, 128, 1, display)

        while True:
            timer = ticks_us()
            logo.update_pos()
            logo.draw()
            # Attempt to set framerate to 30 FPS
            timer_dif = 33333 - ticks_diff(ticks_us(), timer)
            if timer_dif > 0:
                sleep_us(timer_dif)

    except KeyboardInterrupt:
        display.cleanup() 
示例2
def test():
    """Test code."""
    # Baud rate of 14500000 seems about the max
    spi = SPI(2, baudrate=14500000, sck=Pin(18), mosi=Pin(23))
    display = Display(spi, dc=Pin(17), cs=Pin(5), rst=Pin(16))

    # Build color list from all upper case constants (lazy approach)
    colors = [getattr(modules[__name__], name) for name in dir(
        modules[__name__]) if name.isupper() and name is not 'SPI']

    colors.sort()
    c = 0
    for x in range(1, 126, 25):
        for y in range(1, 126, 25):
            display.fill_rectangle(x, y, 25, 25, colors[c])
            c += 1
    sleep(9)
    display.cleanup() 
示例3
def test():
    """Test code."""
    spi = SPI(2, baudrate=14500000, sck=Pin(18), mosi=Pin(23))
    display = Display(spi, dc=Pin(17), cs=Pin(5), rst=Pin(16))
    display.contrast(0)
    display.draw_image('images/MicroPython128x128.raw',
                       0, 0, 128, 128)

    fixed_font = XglcdFont('fonts/FixedFont5x8.c', 5, 8)
    contrast_range = list(range(1, 16)) + list(reversed(range(15)))
    for c in contrast_range:
        display.contrast(c)
        display.draw_text(30, 120, 'contrast: {0:02d}'.format(c),
                          fixed_font, color565(255, 255, 255))
        sleep(1)

    display.cleanup() 
示例4
def test():
    """Test code."""
    spi = SPI(2, baudrate=14500000, sck=Pin(18), mosi=Pin(23))
    display = Display(spi, dc=Pin(17), cs=Pin(5), rst=Pin(16))

    display.draw_image('images/RaspberryPiWB128x128.raw', 0, 0, 128, 128)
    sleep(5)

    display.draw_image('images/MicroPython128x128.raw', 0, 0, 128, 128)
    sleep(5)

    display.draw_image('images/Tabby128x128.raw', 0, 0, 128, 128)
    sleep(5)

    display.draw_image('images/Tortie128x128.raw', 0, 0, 128, 128)
    sleep(9)

    display.cleanup() 
示例5
def spi_read(self, size: int, **kwargs) -> str:
        """
        Read from an SPI bus.

        :param size: Number of bytes to read.
        :param kwargs: Parameters to pass to :meth:`platypush.plugins.esp.EspPlugin.spi_open` and
            :meth:`platypush.plugins.esp.EspPlugin.execute`.
        :return: String representation of the read bytes, or base64-encoded representation if the
            data can't be decoded to a string.
        """
        self.spi_open(**kwargs)
        code = 'spi.read({size})'.format(size=size)
        response = self.execute(code, **kwargs).output

        try:
            return response.decode()
        except UnicodeDecodeError:
            return base64.encodebytes(response).decode() 
示例6
def spi_write(self, data: str, binary: bool = False, **kwargs):
        """
        Write data to an SPI bus.

        :param data: Data to be written.
        :param binary: By default data will be treated as a string. Set binary to True if it should
            instead be treated as a base64-encoded binary string to be decoded before being sent.
        :param kwargs: Parameters to pass to :meth:`platypush.plugins.esp.EspPlugin.spi_open` and
            :meth:`platypush.plugins.esp.EspPlugin.execute`.
        """
        if binary:
            data = base64.decodebytes(data.encode())
        else:
            data = data.encode()

        data = 'b"' + ''.join(['\\x{:02x}'.format(b) for b in data]) + '"'
        self.spi_open(**kwargs)

        code = 'spi.write({data})'.format(data=data)
        self.execute(code, **kwargs) 
示例7
def write(self, command=None, data=None):
        """SPI write to the device: commands and data"""
        self.cs_low()
        if command is not None:
            self.dc_low()
            self.spi.write(bytes([command]))
        if data is not None:
            self.dc_high()
            self.spi.write(data)
        self.cs_high() 
示例8
def main():
    spi = machine.SPI(1, baudrate=40000000, polarity=1)
    display = st7789.ST7789(
        spi, 240, 240,
        reset=machine.Pin(5, machine.Pin.OUT),
        dc=machine.Pin(2, machine.Pin.OUT),
    )
    display.init()

    while True:
        display.fill(
            st7789.color565(
                random.getrandbits(8),
                random.getrandbits(8),
                random.getrandbits(8),
            ),
        )
        # Pause 2 seconds.
        time.sleep(2) 
示例9
def setup(use_spi=False, soft=True):
    if use_spi:
        # Pyb   SSD
        # 3v3   Vin
        # Gnd   Gnd
        # X1    DC
        # X2    CS
        # X3    Rst
        # X6    CLK
        # X8    DATA
        pdc = machine.Pin('X1', machine.Pin.OUT_PP)
        pcs = machine.Pin('X2', machine.Pin.OUT_PP)
        prst = machine.Pin('X3', machine.Pin.OUT_PP)
        if soft:
            spi = machine.SPI(sck=machine.Pin('X6'), mosi=machine.Pin('X8'), miso=machine.Pin('X7'))
        else:
            spi = machine.SPI(1)
        ssd = SSD1306_SPI(WIDTH, HEIGHT, spi, pdc, prst, pcs)
    else:  # I2C
        # Pyb   SSD
        # 3v3   Vin
        # Gnd   Gnd
        # Y9    CLK
        # Y10   DATA
        if soft:
            pscl = machine.Pin('Y9', machine.Pin.OPEN_DRAIN)
            psda = machine.Pin('Y10', machine.Pin.OPEN_DRAIN)
            i2c = machine.I2C(scl=pscl, sda=psda)
        else:
            i2c = machine.I2C(2)
        ssd = SSD1306_I2C(WIDTH, HEIGHT, i2c)
    return ssd 
示例10
def setup():
    pdc = machine.Pin('X1', machine.Pin.OUT_PP, value=0)
    pcs = machine.Pin('X2', machine.Pin.OUT_PP, value=1)
    prst = machine.Pin('X3', machine.Pin.OUT_PP, value=1)
    spi = machine.SPI(1)
    ssd = SSD(spi, pcs, pdc, prst)  # Create a display instance
    return ssd 
示例11
def setup():
    pdc = machine.Pin('X1', machine.Pin.OUT_PP, value=0)
    pcs = machine.Pin('X2', machine.Pin.OUT_PP, value=1)
    prst = machine.Pin('X3', machine.Pin.OUT_PP, value=1)
    spi = machine.SPI(1)
    ssd = SSD(spi, pcs, pdc, prst)  # Create a display instance
    return ssd 
示例12
def setup():
    pdc = machine.Pin('X1', machine.Pin.OUT_PP, value=0)
    pcs = machine.Pin('X2', machine.Pin.OUT_PP, value=1)
    prst = machine.Pin('X3', machine.Pin.OUT_PP, value=1)
    spi = machine.SPI(1)
    ssd = SSD(spi, pcs, pdc, prst, height=96)  # Create a display instance
    return ssd 
示例13
def setup():
    pdc = machine.Pin('X1', machine.Pin.OUT_PP, value=0)
    pcs = machine.Pin('X2', machine.Pin.OUT_PP, value=1)
    prst = machine.Pin('X3', machine.Pin.OUT_PP, value=1)
    spi = machine.SPI(1)
    ssd = SSD(spi, pcs, pdc, prst, height=96)  # Create a display instance
    return ssd 
示例14
def test():
    """Bouncing box."""
    try:
        # Baud rate of 14500000 seems about the max
        spi = SPI(2, baudrate=14500000, sck=Pin(18), mosi=Pin(23))
        display = Display(spi, dc=Pin(17), cs=Pin(5), rst=Pin(16))
        display.clear()

        colors = [color565(255, 0, 0),
                  color565(0, 255, 0),
                  color565(0, 0, 255),
                  color565(255, 255, 0),
                  color565(0, 255, 255),
                  color565(255, 0, 255)]
        sizes = [12, 11, 10, 9, 8, 7]
        boxes = [Box(128, 128, sizes[i], display,
                 colors[i]) for i in range(6)]

        while True:
            timer = ticks_us()
            for b in boxes:
                b.update_pos()
                b.draw()
            # Attempt to set framerate to 30 FPS
            timer_dif = 33333 - ticks_diff(ticks_us(), timer)
            if timer_dif > 0:
                sleep_us(timer_dif)

    except KeyboardInterrupt:
        display.cleanup() 
示例15
def test():
    """Test code."""
    # Baud rate of 14500000 seems about the max
    spi = SPI(2, baudrate=14500000, sck=Pin(18), mosi=Pin(23))
    display = Display(spi, dc=Pin(17), cs=Pin(5), rst=Pin(16))

    c = 0
    for x in range(0, 128, 16):
        for y in range(0, 128, 16):
            color = color565(*hsv_to_rgb(c / 64, 1, 1))
            display.fill_circle(x + 7, y + 7, 7, color)
            c += 1
    sleep(9)
    display.cleanup() 
示例16
def spi_close(self, **kwargs):
        """
        Turn off an SPI bus.

        :param kwargs: Parameters to pass to :meth:`platypush.plugins.esp.EspPlugin.spi_open` and
            :meth:`platypush.plugins.esp.EspPlugin.execute`.
        """
        self.spi_open(**kwargs)
        self.execute('spi.deinit()', **kwargs) 
示例17
def __init__(self, spi, width, height, reset, dc, cs=None, backlight=None,
                 xstart=-1, ystart=-1):
        """
        display = st7789.ST7789(
            SPI(1, baudrate=40000000, phase=0, polarity=1),
            240, 240,
            reset=machine.Pin(5, machine.Pin.OUT),
            dc=machine.Pin(2, machine.Pin.OUT),
        )

        """
        self.width = width
        self.height = height
        self.spi = spi
        if spi is None:
            import machine
            self.spi = machine.SPI(1, baudrate=40000000, phase=0, polarity=1)
        self.reset = reset
        self.dc = dc
        self.cs = cs
        self.backlight = backlight
        if xstart >= 0 and ystart >= 0:
            self.xstart = xstart
            self.ystart = ystart
        elif (self.width, self.height) == (240, 240):
            self.xstart = 0
            self.ystart = 0
        elif (self.width, self.height) == (135, 240):
            self.xstart = 52
            self.ystart = 40
        else:
            raise ValueError(
                "Unsupported display. Only 240x240 and 135x240 are supported "
                "without xstart and ystart provided"
            ) 
示例18
def read(self, size=HCI_READ_PACKET_SIZE, retry=5):
        """
        Read packet from BlueNRG-MS module
        """
        result = None
        while retry:
            with CSContext(self._nss_pin):
                # Exchange header
                self._spi_bus.write_readinto(
                    _READ_HEADER_MASTER,
                    self._rw_header_slave
                )
                rx_read_bytes = (
                    self._rw_header_slave[4] << 8
                ) | self._rw_header_slave[3]
                if self._rw_header_slave[0] == 0x02 and rx_read_bytes > 0:
                    # SPI is ready
                    # avoid to read more data that size of the buffer
                    if rx_read_bytes > size:
                        rx_read_bytes = size
                    data = b'\xFF' * rx_read_bytes
                    result = bytearray(rx_read_bytes)
                    self._spi_bus.write_readinto(data, result)
                    break
                else:
                    utime.sleep_us(50)
            retry -= 1

        # Add a small delay to give time to the BlueNRG to set the IRQ pin low
        # to avoid a useless SPI read at the end of the transaction
        utime.sleep_us(150)
        return result 
示例19
def test(spi=3, cs='PB0'):
    print("SPI flash")
    cs = Pin(cs, Pin.OUT)
    spi = SPI(spi, baudrate=42000000, polarity=0, phase=0)
    flash = SPIFlash(spi, cs)

    print("Getting chip ID...")
    flash.wait()
    id_ = flash.getid()
    print("ID:", ubinascii.hexlify(id_))

    print("Reading block (32b) from address 0...")
    buf = bytearray(32)
    flash.read_block(0, buf)
    print(ubinascii.hexlify(buf))

    addr = 12 * 600 + 8
    print("Reading block (32b) from address {}...".format(addr))
    flash.read_block(addr, buf)
    print(ubinascii.hexlify(buf))

    addr = 524288
    print("Erasing 4k block at address {}...".format(addr))
    t1 = ticks_us()
    flash.erase(addr, '4k')
    # flash.erase(addr, '32k')
    # flash.erase(addr, '64k')
    # flash.erase_chip()
    t = ticks_diff(ticks_us(), t1)
    print("erase {} us".format(t))

    print("Writing blocks (256b) at address {}...".format(addr))
    buf = bytearray(range(256))
    t1 = ticks_us()
    flash.write_block(addr, buf)
    t = ticks_diff(ticks_us(), t1)
    mbs = len(buf) * 8. / t
    print("write({}) {} us, {} mbs".format(len(buf), t, mbs))

    print("Verifying write...")
    v = bytearray(256)
    flash.read_block(addr, v)
    if (v == buf):
        print("write/read ok")
    else:
        print("write/read FAILed")

    print("Timing 32k read from address 0...")
    gc.collect()
    buf = bytearray(32 * 1024)
    t1 = ticks_us()
    flash.read_block(0, buf)
    t = ticks_diff(ticks_us(), t1)
    mbs = len(buf) * 8. / t
    print("read({}) {} us, {} mbs".format(len(buf), t, mbs)) 
示例20
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() 
示例21
def spi_open(self, id=1, baudrate: int = 1000000, polarity: int = 0, phase: int = 0,
                 bits: int = 8, sck: Optional[int] = None, mosi: Optional[int] = None,
                 miso: Optional[int] = None, **kwargs):
        """
        Open a connection to an SPI port.
        Note that ``sck``, ``mosi`` and ``miso`` parameters are only allowed if you're setting up a software
        managed SPI connection. If you're using the hardware SPI implementation then those PINs are
        pre-defined depending on the model of your board.

        :param id: Values of id depend on a particular port and its hardware. Values 0, 1, etc. are commonly used to
            select hardware SPI block #0, #1, etc. Value -1 can be used for bit-banging (software) implementation of
            SPI (if supported by a port).
        :param baudrate: Port baudrate/SCK clock rate (default: 1 MHz).
        :param polarity: It can be 0 or 1, and is the level the idle clock line sits at.
        :param phase: It can be 0 or 1 to sample data on the first or second clock edge respectively.
        :param bits: Number of bits per character. It can be 7, 8 or 9.
        :param sck: SCK PIN number.
        :param mosi: MOSI PIN number.
        :param miso: MISO PIN number.
        :param kwargs: Parameters to pass to :meth:`platypush.plugins.esp.EspPlugin.execute`.
        """
        code = '''
args = {
    'baudrate': {baudrate},
    'polarity': {polarity},
    'phase': {phase},
    'bits': {bits},
}
'''.format(baudrate=baudrate, polarity=polarity, phase=phase, bits=bits)

        self.execute(code, **kwargs)
        code = '''
import machine

if {sck}:
    args['sck'] = machine.Pin({sck})
if {mosi}:
    args['mosi'] = machine.Pin({mosi})
if {miso}:
    args['miso'] = machine.Pin({miso})
'''.format(sck=sck, mosi=mosi, miso=miso)

        self.execute(code, **kwargs)
        code = 'spi = machine.SPI({id}, **args)'.format(id=id)
        self.execute(code, **kwargs) 
示例22
def __init__(
        self,
        spi_bus=machine.SPI(2, baudrate=8000000, polarity=0),
        irq_pin=machine.Pin('B8', machine.Pin.IN, machine.Pin.PULL_DOWN),
        rst_pin=machine.Pin('B9', machine.Pin.OUT_PP),
        nss_pin=machine.Pin('B12', machine.Pin.OUT_PP),
    ):
        """
        Defaults:
            - SPI(2) on the Y position:
                (NSS, SCK, MISO, MOSI) = (Y5, Y6, Y7, Y8) = (PB12, PB13, PB14, PB15)
              Params:
                phase: 0
                dir: SPI_DIRECTION_2LINES
                bits: 8
                nss: SPI_NSS_SOFT
                firstbit: SPI_FIRSTBIT_MSB
                ti: SPI_TIMODE_DISABLED
                crc:
                crc_calc: SPI_CRCCALCULATION_DISABLED

            PYBV1x:
            - IRQ  on Y3/B8 Pin
            - RST  on Y4/B9 Pin
            - NSS  on Y5/B12 Pin
            - SCK  on Y6/B13 Pin
            - MISO on Y7/B14 Pin
            - MOSI on Y8/B15 Pin

            ESPRUINO_PICO:
            - IRQ  on B8 Pin
            - RST  on B9 Pin
            - NSS  on A10 Pin
            - SCK  on A7 Pin
            - MISO on A6 Pin
            - MOSI on A5 Pin

        """

        if not isinstance(spi_bus, machine.SPI):
            raise TypeError("")

        m_pins = (irq_pin, rst_pin, nss_pin)
        if not all([isinstance(pin, machine.Pin) for pin in m_pins]):
            raise TypeError("")

        self._spi_bus = spi_bus

        self._irq_pin = irq_pin
        self._rst_pin = rst_pin
        self._nss_pin = nss_pin

        self._rw_header_slave = bytearray(5)

        # Release CS line
        self._nss_pin.on() 
示例23
def write(self, header, param, retry=5):
        """
        Write packet to BlueNRG-MS module
        """
        result = None
        while retry:
            with CSContext(self._nss_pin):
                # Exchange header
                self._spi_bus.write_readinto(
                    _WRITE_HEADER_MASTER,
                    self._rw_header_slave
                )
                rx_write_bytes = self._rw_header_slave[1]
                rx_read_bytes = (
                    self._rw_header_slave[4] << 8
                ) | self._rw_header_slave[3]
                if self._rw_header_slave[0] == 0x02 and (
                        rx_write_bytes > 0 or rx_read_bytes > 0):
                    # SPI is ready
                    if header:
                        # avoid to write more data that size of the buffer
                        if rx_write_bytes >= len(header):
                            result = bytearray(len(header))
                            self._spi_bus.write_readinto(header, result)
                            if param:
                                rx_write_bytes -= len(header)
                                # avoid to read more data that size of the
                                # buffer
                                if len(param) > rx_write_bytes:
                                    tx_bytes = rx_write_bytes
                                else:
                                    tx_bytes = len(param)
                                result = bytearray(tx_bytes)
                                self._spi_bus.write_readinto(param, result)
                                break
                            else:
                                break
                        else:
                            break
                    else:
                        break
                else:
                    utime.sleep_us(50)
            retry -= 1

        return result 
示例24
def __init__(self, spi, rst, ce, dc, light, pwr=None):
        self.width  = 84
        self.height = 48
        self.power      = self.POWER_DOWN
        self.addressing = self.ADDRESSING_HORIZ
        self.instr      = self.INSTR_BASIC
        self.display_mode = self.DISPLAY_BLANK
        self.temp_coeff = self.TEMP_COEFF_0
        self.bias       = self.BIAS_1_11
        self.voltage    = 3060

        # init the SPI bus and pins
        spi.init(spi.MASTER, baudrate=328125, bits=8, polarity=0, phase=1, firstbit=spi.MSB)
        if "OUT_PP" in dir(rst):
            # pyBoard style
            rst.init(rst.OUT_PP, rst.PULL_NONE)  # Reset line
            ce.init(ce.OUT_PP, ce.PULL_NONE)     # Chip Enable
            dc.init(dc.OUT_PP, dc.PULL_NONE)     # Data(1) / Command(0) mode
            light.init(light.OUT_PP, light.PULL_NONE)
            if pwr:
                pwr.init(pwr.OUT_PP, pwr.PULL_NONE)
        else:
            # WiPy style
            rst.init(rst.OUT, None)
            ce.init(ce.OUT, None)
            dc.init(dc.OUT, None)
            light.init(light.OUT, None)
            if pwr:
                pwr.init(pwr.OUT, None)

        self.spi   = spi
        self.rst   = rst
        self.ce    = ce
        self.dc    = dc
        self.light = light
        self.pwr   = pwr

        self.light_off()
        self.power_on()
        self.ce.value(1)  # set chip to disable (don't listen to input)
        self.reset()
        self.set_contrast(0xbf)
        self.clear()
        self.lcd_font = font.FONT6_8()
        self.chinese = chinese.CN_UTF8() 
示例25
def init_card(self):
        # init CS pin
        self.cs.init(self.cs.OUT, value=1)

        # init SPI bus; use low data rate for initialisation
        self.init_spi(10000000)

        # clock card at least 100 cycles with cs high
        for i in range(16):
            self.spi.write(b'\xff')

        # CMD0: init card; should return _R1_IDLE_STATE (allow 5 attempts)
        for _ in range(5):
            if self.cmd(0, 0, 0x95) == _R1_IDLE_STATE:
                break
        else:
            raise OSError("no SD card")

        # CMD8: determine card version
        r = self.cmd(8, 0x01aa, 0x87, 4)
        if r == _R1_IDLE_STATE:
            self.init_card_v2()
        elif r == (_R1_IDLE_STATE | _R1_ILLEGAL_COMMAND):
            self.init_card_v1()
        else:
            raise OSError("couldn't determine SD card version")

        # get the number of sectors
        # CMD9: response R2 (R1 byte + 16-byte block read)
        if self.cmd(9, 0, 0, 0, False) != 0:
            raise OSError("no response from SD card")
        csd = bytearray(16)
        self.readinto(csd)
        if csd[0] & 0xc0 == 0x40: # CSD version 2.0
            self.sectors = ((csd[8] << 8 | csd[9]) + 1) * 1024
        elif csd[0] & 0xc0 == 0x00: # CSD version 1.0 (old, <=2GB)
            c_size = csd[6] & 0b11 | csd[7] << 2 | (csd[8] & 0b11000000) << 4
            c_size_mult = ((csd[9] & 0b11) << 1) | csd[10] >> 7
            self.sectors = (c_size + 1) * (2 ** (c_size_mult + 2))
        else:
            raise OSError("SD card CSD format not supported")
        #print('sectors', self.sectors)

        # CMD16: set block length to 512 bytes
        if self.cmd(16, 512, 0) != 0:
            raise OSError("can't set 512 block size")

        # set to high data rate now that it's initialised
        self.init_spi(1320000)