示例#1
0
 def __init__(self, freq, sck, sdo, sdi=None, spidev=None):
   _mi = Pin(sdi) if sdi else None
   _mo = Pin(sdo)
   _sc = Pin(sck)
   if spidev == None:
     self._spi = SPI(baudrate=freq, sck=_sc, mosi=_mo, miso=_mi)
   elif spidev >= 0:
     self._spi = SPI(spidev, baudrate=freq, sck=_sc, mosi=_mo, miso=_mi)
   else:
     self._spi = SoftSPI(sck=_sc, mosi=_mo, miso=_mi)
示例#2
0
def main():
    '''
    Draw greetings on display cycling thru hershey fonts and colors
    '''
    try:
        # Turn power on display power
        axp = axp202c.PMU()
        axp.enablePower(axp202c.AXP202_LDO2)
        axp.enablePower(axp202c.AXP202_DCDC3)

        # initialize spi port
        spi = SoftSPI(
            2,
            baudrate=32000000,
            polarity=1,
            phase=0,
            bits=8,
            firstbit=0,
            sck=Pin(18, Pin.OUT),
            mosi=Pin(19, Pin.OUT))

        # configure display
        tft = st7789.ST7789(
            spi,
            240,
            240,
            cs=Pin(5, Pin.OUT),
            dc=Pin(27, Pin.OUT),
            backlight=Pin(12, Pin.OUT),
            rotation=2)

        tft.init()
        tft.fill(st7789.BLACK)
        height = tft.height()
        width = tft.width()
        row = 0

        while True:
            row += 32
            color = next(COLORS)
            tft.fill_rect(0, row-16, width, 32, st7789.BLACK)
            tft.draw(next(FONTS), next(GREETINGS), 0, row, color)

            if row > 192:
                row = 0

            utime.sleep(0.25)

    finally:
        # shutdown spi
        if 'spi' in locals():
            spi.deinit()
示例#3
0
def main():

    def center(font, string, row, color=st7789.WHITE):
        screen = tft.width                        # get screen width
        width = tft.write_width(font, string)     # get the width of the string
        if width and width < screen:              # if the string < display
            col = tft.width // 2 - width // 2     # find the column to center
        else:                                     # otherwise
            col = 0                               # left justify

        tft.write(font, string, col, row, color)  # and write the string

    try:
        spi = SoftSPI(
            baudrate=20000000,
            polarity=1,
            phase=0,
            sck=Pin(18),
            mosi=Pin(19),
            miso=Pin(13))

        tft = st7789.ST7789(
            spi,
            135,
            240,
            reset=Pin(23, Pin.OUT),
            cs=Pin(5, Pin.OUT),
            dc=Pin(16, Pin.OUT),
            backlight=Pin(4, Pin.OUT),
            rotation=1)

        # enable display and clear screen
        tft.fill(st7789.BLACK)

        row = 16

        # center the name of the first font, using the font
        center(noto_sans, "NotoSans", row, st7789.RED)
        row += noto_sans.HEIGHT

        # center the name of the second font, using the font
        center(noto_serif, "NotoSerif", row, st7789.GREEN)
        row += noto_serif.HEIGHT

        # center the name of the third font, using the font
        center(noto_mono, "NotoSansMono", row, st7789.BLUE)
        row += noto_mono.HEIGHT

    finally:
        # shutdown spi
        if 'spi' in locals():
            spi.deinit()
示例#4
0
def main():

    tft = st7789.ST7789(SoftSPI(2,
                                baudrate=30000000,
                                polarity=1,
                                phase=1,
                                sck=Pin(18),
                                mosi=Pin(19)),
                        135,
                        240,
                        reset=Pin(23, Pin.OUT),
                        cs=Pin(5, Pin.OUT),
                        dc=Pin(16, Pin.OUT),
                        backlight=Pin(4, Pin.OUT),
                        rotation=3)

    tft.init()
    tft.fill(st7789.BLACK)

    start = utime.ticks_ms()
    tft.text(font, "MicroPython", 0, 0, st7789.WHITE)
    tft.text(font, "MicroPython", 0, 32, st7789.RED)
    tft.text(font, "MicroPython", 0, 64, st7789.GREEN)
    tft.text(font, "MicroPython", 0, 96, st7789.BLUE)
    print("time:", utime.ticks_ms() - start, "ms")
示例#5
0
def spi_jtag_on():
    global hwspi, swspi
    try:  # ESP32 classic
        hwspi = SPI(2,
                    baudrate=spi_freq,
                    polarity=1,
                    phase=1,
                    bits=8,
                    firstbit=SPI.MSB,
                    sck=Pin(jtagpin.tck),
                    mosi=Pin(jtagpin.tdi),
                    miso=Pin(jtagpin.tdo))
    except:  # ESP32-S2
        hwspi = SPI(baudrate=spi_freq,
                    polarity=1,
                    phase=1,
                    bits=8,
                    firstbit=SPI.MSB,
                    sck=Pin(jtagpin.tck),
                    mosi=Pin(jtagpin.tdi),
                    miso=Pin(jtagpin.tdo))
    swspi = SoftSPI(baudrate=spi_freq,
                    polarity=1,
                    phase=1,
                    bits=8,
                    firstbit=SPI.MSB,
                    sck=Pin(jtagpin.tck),
                    mosi=Pin(jtagpin.tdi),
                    miso=Pin(jtagpin.tdo))
示例#6
0
def mount_sdcard():
    spisd = SoftSPI(-1, miso=Pin(13), mosi=Pin(12), sck=Pin(14))

    sd = SDCard(spisd, Pin(27))

    vfs = os.VfsFat(sd)
    os.mount(vfs, '/sd')
示例#7
0
def main():
    # enable display and clear screen
    spi = SoftSPI(baudrate=20000000,
                  polarity=1,
                  phase=0,
                  sck=Pin(18),
                  mosi=Pin(19),
                  miso=Pin(13))

    tft = st7789.ST7789(spi,
                        135,
                        240,
                        reset=Pin(23, Pin.OUT),
                        cs=Pin(5, Pin.OUT),
                        dc=Pin(16, Pin.OUT),
                        backlight=Pin(4, Pin.OUT),
                        rotation=1)

    tft.fill(st7789.BLACK)

    row = 0
    tft.write(font_16, "abcdefghijklmnopqrst", 0, row, st7789.RED)
    row += font_16.HEIGHT

    tft.write(font_32, "abcdefghij", 0, row, st7789.GREEN)
    row += font_32.HEIGHT

    tft.write(font_64, "abcd", 0, row, st7789.BLUE)
    row += font_64.HEIGHT
示例#8
0
def main():
    spi = SoftSPI(baudrate=20000000,
                  polarity=1,
                  phase=0,
                  sck=Pin(18),
                  mosi=Pin(19),
                  miso=Pin(13))

    tft = st7789.ST7789(spi,
                        135,
                        240,
                        reset=Pin(23, Pin.OUT),
                        cs=Pin(5, Pin.OUT),
                        dc=Pin(16, Pin.OUT),
                        backlight=Pin(4, Pin.OUT),
                        rotation=0)

    while True:
        for rotation in range(4):
            tft.rotation(rotation)
            tft.fill(0)
            col_max = tft.width - font.WIDTH * 6
            row_max = tft.height - font.HEIGHT

            for _ in range(100):
                tft.text(
                    font, "Hello!", random.randint(0, col_max),
                    random.randint(0, row_max),
                    st7789.color565(random.getrandbits(8),
                                    random.getrandbits(8),
                                    random.getrandbits(8)),
                    st7789.color565(random.getrandbits(8),
                                    random.getrandbits(8),
                                    random.getrandbits(8)))
示例#9
0
def main():
    '''
    Draw greetings on display cycling thru hershey fonts and colors
    '''
    # configure display
    tft = st7789.ST7789(SoftSPI(2,
                                baudrate=30000000,
                                polarity=1,
                                phase=1,
                                sck=Pin(18),
                                mosi=Pin(19)),
                        135,
                        240,
                        reset=Pin(23, Pin.OUT),
                        cs=Pin(5, Pin.OUT),
                        dc=Pin(16, Pin.OUT),
                        backlight=Pin(4, Pin.OUT),
                        rotation=3)

    tft.init()
    tft.fill(st7789.BLACK)
    width = tft.width()
    row = 0

    while True:
        row += 32
        color = next(COLORS)
        tft.fill_rect(0, row - 16, width, 38, st7789.BLACK)
        tft.draw(next(FONTS), next(GREETINGS), 0, row, color)
        print(row)
        if row == 96:
            row = 0

        utime.sleep(0.25)
示例#10
0
def main():
    spi = SoftSPI(baudrate=20000000,
                  polarity=1,
                  phase=0,
                  sck=Pin(18),
                  mosi=Pin(19),
                  miso=Pin(13))

    tft = st7789.ST7789(spi,
                        135,
                        240,
                        reset=Pin(23, Pin.OUT),
                        cs=Pin(5, Pin.OUT),
                        dc=Pin(16, Pin.OUT),
                        backlight=Pin(4, Pin.OUT),
                        rotation=0)

    tft.fill(st7789.BLACK)

    while True:
        tft.line(
            random.randint(0, tft.width), random.randint(0, tft.height),
            random.randint(0, tft.width), random.randint(0, tft.height),
            st7789.color565(random.getrandbits(8), random.getrandbits(8),
                            random.getrandbits(8)))

        width = random.randint(0, tft.width // 2)
        height = random.randint(0, tft.height // 2)
        col = random.randint(0, tft.width - width)
        row = random.randint(0, tft.height - height)
        tft.fill_rect(
            col, row, width, height,
            st7789.color565(random.getrandbits(8), random.getrandbits(8),
                            random.getrandbits(8)))
示例#11
0
    def __init__(self):
        # Create a DotStar instance
        spi = SoftSPI(sck=Pin(TinyPICO.DOTSTAR_CLK),
                      mosi=Pin(TinyPICO.DOTSTAR_DATA),
                      miso=Pin(TinyPICO.SPI_MISO))
        self.dotstar = DotStar(
            spi, 1, brightness=0.5)  # Just one DotStar, half brightness

        # Turn on the power to the DotStar
        TinyPICO.set_dotstar_power(True)
        self.dotstar[0] = (255, 0, 0, 0.5)

        # Define state
        self.x = 0
        self.y = 0

        self.prev_x = 0
        self.prev_y = 0

        # Define buttons
        self.pin_forward = Pin(5, Pin.IN)
        self.pin_reverse = Pin(23, Pin.IN)
        self.pin_right = Pin(19, Pin.IN)
        self.pin_left = Pin(18, Pin.IN)

        # Create our device
        self.joystick = Joystick("Joystick")
        # Set a callback function to catch changes of device state
        self.joystick.set_state_change_callback(self.joystick_state_callback)
        # Start our device
        self.joystick.start()
示例#12
0
    def test_mfrc522_write(self):
        """
        test mfrc522_write properly writes a value
        """
        # Setup
        sck = Pin(18, Pin.OUT)
        copi = Pin(23, Pin.OUT)
        cipo = Pin(19, Pin.OUT)
        spi = SoftSPI(baudrate=100000, polarity=0, phase=0, sck=sck, mosi=copi, miso=cipo)
        sda = Pin(21, Pin.OUT)

        # Instantiate
        reader = MFRC522(spi, sda)

        # Calls
        (status, tag_type) = reader.request(reader.CARD_REQIDL)
        if status == reader.OK:
            (status, raw_uid) = reader.anticoll()
            if status == reader.OK:
                if reader.select_tag(raw_uid) == reader.OK:
                    key = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
                    if reader.auth(reader.AUTH, 8, key, raw_uid) == reader.OK:
                        status = reader.write(8, b'\x08\x06\x07\x05\x03\x00\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00')
                        reader.stop_crypto1()
        
        # Asserts
        self.assertEqual(status, 0)
示例#13
0
    def test_mfrc522_read(self):
        """
        test mfrc522_read properly reads a value
        """
        # Setup
        input('\nPLEASE PLACE CARD IN FRONT OF READER TO PROCEED AND PRESS ENTER WHEN READY')
        sck = Pin(18, Pin.OUT)
        copi = Pin(23, Pin.OUT)
        cipo = Pin(19, Pin.OUT)
        spi = SoftSPI(baudrate=100000, polarity=0, phase=0, sck=sck, mosi=copi, miso=cipo)
        sda = Pin(21, Pin.OUT)

        # Instantiate
        reader = MFRC522(spi, sda)

        # Calls
        (status, tag_type) = reader.request(reader.CARD_REQIDL)
        if status == reader.OK:
            (status, raw_uid) = reader.anticoll()
            if status == reader.OK:
                if reader.select_tag(raw_uid) == reader.OK:
                    key = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
                    if reader.auth(reader.AUTH, 8, key, raw_uid) == reader.OK:
                        reader.stop_crypto1()
        
        # Asserts
        self.assertEqual(status, 0)
示例#14
0
class SPIBus(object):
  """SPI bus access."""

  def __init__(self, freq, sck, sdo, sdi=None, spidev=None):
    _mi = Pin(sdi) if sdi else None
    _mo = Pin(sdo)
    _sc = Pin(sck)
    if spidev == None:
      self._spi = SPI(baudrate=freq, sck=_sc, mosi=_mo, miso=_mi)
    elif spidev >= 0:
      self._spi = SPI(spidev, baudrate=freq, sck=_sc, mosi=_mo, miso=_mi)
    else:
      self._spi = SoftSPI(sck=_sc, mosi=_mo, miso=_mi)

  def deinit(self):
    self._spi.deinit()

  @property
  def bus(self):
    return self._spi

  def write_readinto(self, wbuf, rbuf):
    self._spi.write_readinto(wbuf, rbuf)

  def write(self, wbuf):
    self._spi.write(wbuf)
示例#15
0
def init_APA102():
    global DOTSTAR
    # Configure SPI for controlling the DotStar
    # Internally we are using software SPI for this as the pins being used are not hardware SPI pins
    spi = SoftSPI(sck=Pin(TinyPICO.DOTSTAR_CLK),
                  mosi=Pin(TinyPICO.DOTSTAR_DATA),
                  miso=Pin(TinyPICO.SPI_MISO))
    # Create a DotStar instance
    DOTSTAR = DotStar(spi, 1,
                      brightness=0.4)  # Just one DotStar, half brightness
    # Turn on the power to the DotStar
    TinyPICO.set_dotstar_power(True)
    return True
示例#16
0
def main():
    Pin(22, Pin.OUT, value=1)

    spi = SoftSPI(baudrate=20000000,
                  polarity=1,
                  phase=0,
                  sck=Pin(2),
                  mosi=Pin(3),
                  miso=Pin(13))

    tft = st7789.ST7789(spi,
                        135,
                        240,
                        reset=Pin(0, Pin.OUT),
                        cs=Pin(5, Pin.OUT),
                        dc=Pin(1, Pin.OUT),
                        backlight=Pin(4, Pin.OUT),
                        rotation=0)

    last_line = tft.height - font.HEIGHT
    tfa = 40
    tfb = 40
    tft.vscrdef(tfa, 240, tfb)

    tft.fill(st7789.BLUE)
    scroll = 0
    character = 0
    while True:
        tft.fill_rect(0, scroll, tft.width, 1, st7789.BLUE)

        if scroll % font.HEIGHT == 0:
            tft.text(font, '\\x{:02x}= {:s} '.format(character,
                                                     chr(character)), 0,
                     (scroll + last_line) % tft.height, st7789.WHITE,
                     st7789.BLUE)

            character = character + 1 if character < 256 else 0

        tft.vscsad(scroll + tfa)
        scroll += 1

        if scroll == tft.height:
            scroll = 0

        utime.sleep(0.01)
示例#17
0
def main():
    """
    Initialize the display and draw flying toasters and toast
    """
    spi = SoftSPI(baudrate=20000000,
                  polarity=1,
                  phase=0,
                  sck=Pin(18),
                  mosi=Pin(19),
                  miso=Pin(13))

    tft = st7789.ST7789(spi,
                        135,
                        240,
                        reset=Pin(23, Pin.OUT),
                        cs=Pin(5, Pin.OUT),
                        dc=Pin(16, Pin.OUT),
                        backlight=Pin(4, Pin.OUT),
                        rotation=0)

    tft.fill(st7789.BLACK)
    # create toast spites in random positions
    sprites = [
        toast(TOASTERS, 135 - 64, 0),
        toast(TOAST, 135 - 64 * 2, 80),
        toast(TOASTERS, 135 - 64 * 4, 160)
    ]

    # move and draw sprites
    while True:
        for man in sprites:
            bitmap = man.sprites[man.step]
            tft.fill_rect(man.x + bitmap.WIDTH - man.speed, man.y, man.speed,
                          bitmap.HEIGHT, st7789.BLACK)

            man.move()

            if man.x > 0:
                tft.bitmap(bitmap, man.x, man.y)
            else:
                tft.fill_rect(0, man.y, bitmap.WIDTH, bitmap.HEIGHT,
                              st7789.BLACK)
示例#18
0
def main():
    Pin(22, Pin.OUT, value=1)

    spi = SoftSPI(baudrate=20000000,
                  polarity=1,
                  phase=0,
                  sck=Pin(2),
                  mosi=Pin(3),
                  miso=Pin(13))

    tft = st7789.ST7789(spi,
                        135,
                        240,
                        reset=Pin(0, Pin.OUT),
                        cs=Pin(5, Pin.OUT),
                        dc=Pin(1, Pin.OUT),
                        backlight=Pin(4, Pin.OUT),
                        rotation=0)

    tft.vscrdef(40, 240, 40)

    while True:
        for font in (font1, font2, font3, font4):
            tft.fill(st7789.BLUE)
            line = 0
            col = 0

            for char in range(font.FIRST, font.LAST):
                tft.text(font, chr(char), col, line, st7789.WHITE, st7789.BLUE)
                col += font.WIDTH
                if col > tft.width - font.WIDTH:
                    col = 0
                    line += font.HEIGHT

                    if line > tft.height - font.HEIGHT:
                        utime.sleep(3)
                        tft.fill(st7789.BLUE)
                        line = 0
                        col = 0

            utime.sleep(3)
示例#19
0
def main():
    tft = st7789.ST7789(SoftSPI(2,
                                baudrate=30000000,
                                polarity=1,
                                phase=1,
                                sck=Pin(18),
                                mosi=Pin(19)),
                        135,
                        240,
                        reset=Pin(23, Pin.OUT),
                        cs=Pin(5, Pin.OUT),
                        dc=Pin(16, Pin.OUT),
                        backlight=Pin(4, Pin.OUT),
                        rotation=3)

    tft.init()

    while True:
        for font in (font1, font2, font3, font4):
            tft.fill(st7789.BLUE)
            line = 0
            col = 0
            for char in range(font.FIRST, font.LAST):
                tft.text(font, chr(char), col, line, st7789.WHITE, st7789.BLUE)
                col += font.WIDTH
                if col > tft.width() - font.WIDTH:
                    col = 0
                    line += font.HEIGHT

                    if line > tft.height() - font.HEIGHT:
                        utime.sleep(3)
                        tft.fill(st7789.BLUE)
                        line = 0
                        col = 0

            utime.sleep(3)
示例#20
0
class NRF24L01:

    SCK = 5
    MOSI = 4
    MISO = 0

    def __init__(self, ce, csn, spi=None, baudrate=400000, payload_size=16):
        self._csn = Pin(csn) if type(csn) == int else csn
        self._ce = Pin(ce) if type(ce) == int else ce
        self._payload_size = payload_size
        self._spi = spi

        self._init_spi(baudrate)

        self._ce.init(Pin.OUT, value=0)
        self._csn.init(Pin.OUT, value=1)

        self._buf = bytearray(1)
        self._write_reg(SETUP_AW, FIVE_BYTE_ADDRESS)
        if self._read_reg(SETUP_AW) != FIVE_BYTE_ADDRESS:
            print('Failed to set address width!')

        self._flush_tx()
        self._flush_rx()

    def _write_reg(self, reg, data):
        self._csn(0)
        self._spi.readinto(self._buf, 0x20 | reg)
        ret = self._buf[0]
        self._spi.readinto(self._buf, data)
        self._csn(1)
        return ret

    def _write_reg_bytes(self, reg, data):
        self._csn(0)
        self._spi.readinto(self._buf, 0x20 | reg)
        self._spi.write(data)
        self._csn(1)
        return self._buf[0]

    def _read_reg(self, reg):
        self._csn(0)
        self._spi.readinto(self._buf, 0x00 | reg)
        self._spi.readinto(self._buf)
        self._csn(1)
        return self._buf[0]

    def read_reg(self, reg):
        return bin(self._read_reg(reg))

    def _init_spi(self, baudrate):
        if self._spi is None:
            self._spi = SoftSPI(baudrate=baudrate, polarity=0, phase=0,
                                sck=Pin(self.SCK), mosi=Pin(self.MOSI),
                                miso=Pin(self.MISO))
        self._spi.init(baudrate=baudrate)

    def _flush_rx(self):
        self._csn(0)
        self._spi.readinto(self._buf, FLUSH_RX)
        self._csn(1)

    def _flush_tx(self):
        self._csn(0)
        self._spi.readinto(self._buf, FLUSH_TX)
        self._csn(1)

    def set_channel(self, channel):
        self._write_reg(RF_CH, channel)

    def set_speed(self, speed):
        self._write_reg(RF_SETUP, self._read_reg(RF_SETUP) | speed)

    def set_power(self, power):
        self._write_reg(RF_SETUP, self._read_reg(RF_SETUP) | power)

    def _get_address(self, address):
        # Ensure that address is in byte-format
        if type(address) == list:
            address = bytes(address)
        elif type(address) == str:
            address = binascii.unhexlify(address)
        return address

    # Set both RX and TX address to the given value.
    # Default pipe used is PIPE 0
    def open_tx_pipe(self, address):
        address = self._get_address(address)

        self._write_reg_bytes(RX_ADDR_P0, address)
        self._write_reg_bytes(TX_ADDR, address)
        # Must enable RX pipe by writing data-length to it (CAN'T be 0)
        self._write_reg(RX_PW_P0, self._payload_size)
        self._ce(0)


    # Default pipe is PIPE 0
    def open_rx_pipe(self, address):
        address = self._get_address(address)
        # Set RX address
        self._write_reg_bytes(RX_ADDR_P0, address)
        # Nbr of bytes in RX payload
        self._write_reg(RX_PW_P0, self._payload_size)
        # Enable RX
        self._write_reg(EN_RXADDR, self._read_reg(EN_RXADDR) | ERX_P0)

        self._write_reg(EN_AA, self._read_reg(EN_AA) & ~ENAA_P0)

    def enable_auto_ack(self):
        self._write_reg(EN_AA, self._read_reg(EN_AA) | ENAA_P0)

    # The parameter crc is the ammount of bytes to be used.
    # Only 1 or 2 is accepted.
    def set_crc(self, crc):
        # read config reg (wihtout the current CRC value)
        config = self._read_reg(CONFIG) & ~CRC
        if crc == 1:
            config |= CRC_ENA
        elif crc == 2:
            config |= CRC_ENA | CRC
        self._write_reg(CONFIG, config)

    def start_listening(self):
        # Power-up and enable RX
        self._write_reg(CONFIG, self._read_reg(CONFIG) | PWR_UP | PRIM_RX)
        self._write_reg(STATUS,
                        self._read_reg(STATUS) | RX_DR | TX_DS | MAX_RT)

        # Flush fifos and set CE HIGH to start listening.
        self._flush_rx()
        self._flush_tx()
        self._ce(1)

    def stop_listening(self):
        self._ce(0)
        self._flush_rx()
        self._flush_tx()

    def read(self):
        # Read the data from the payload reg
        self._ce(0)
        self._csn(0)            # R_RX_PAYLOAD = 0x61
        self._spi.readinto(self._buf, 0x61)
        data = self._spi.read(self._payload_size)

        # Must toggle CE here as well, to disable receiver temporarly
        self._ce(1)
        self._csn(1)

        # Clear RX ready flag when done
        self._write_reg(STATUS, self._read_reg(STATUS) | RX_DR)
        return data

    def send(self, buf, timeout=500):
        self._send_start(buf)
        start = time.ticks_ms()
        result = None
        while (result is None and
               time.ticks_diff(time.ticks_ms(), start) < timeout):
            result = self._send_done()

        print('result: %s' % result)

    def _send_done(self):
        status = self._read_reg(STATUS)
        if not (status & (TX_DS | MAX_RT)):
            # Haven't finished yet
            return None

        # Transmission is over, clear the interrupt bits in the status-reg
        self._write_reg(STATUS, status | RX_DR | TX_DS | MAX_RT)

        if status & TX_DS:
            # Successfull send
            return 1
        else:
            # MAX attempts have passed, return 2 to indicate failure
            return 2

    def _send_start(self, buf):
        # Power-up and enable TX
        self._write_reg(CONFIG, (self._read_reg(CONFIG) | PWR_UP) & ~PRIM_RX)
        time.sleep_us(200)

        # Send the data
        self._csn(0)             # W_TX_PAYLOAD = 0xA0
        self._spi.readinto(self._buf, 0xA0)
        self._spi.write(buf)
        # Need to pad the rest of the packet if data ist too small.
        if len(buf) < self._payload_size:
            self._spi.write(b'\x00' * (self._payload_size - len(buf)))

        self._csn(1)

        # Toggle the ce-signal to send that data
        self._ce(1)
        time.sleep_us(15)   # MINIMUM 10 us according to datasheet
        self._ce(0)

    def close(self):
        self._spi.deinit()
示例#21
0
from machine import Pin, SoftSPI

from micropython_mfrc522.mfrc522 import MFRC522

sck = Pin(18, Pin.OUT)
copi = Pin(23, Pin.OUT)  # Controller out, peripheral in
cipo = Pin(19, Pin.OUT)  # Controller in, peripheral out
spi = SoftSPI(baudrate=100000,
              polarity=0,
              phase=0,
              sck=sck,
              mosi=copi,
              miso=cipo)
sda = Pin(21, Pin.OUT)
reader = MFRC522(spi, sda)

print('Place Card In Front Of Device To Write Unique Address')
print('')

while True:
    try:
        (status, tag_type) = reader.request(reader.CARD_REQIDL)
        if status == reader.OK:
            (status, raw_uid) = reader.anticoll()
            if status == reader.OK:
                print('New Card Detected')
                print('  - Tag Type: 0x%02x' % tag_type)
                print('  - UID: 0x%02x%02x%02x%02x' %
                      (raw_uid[0], raw_uid[1], raw_uid[2], raw_uid[3]))
                print('')
                if reader.select_tag(raw_uid) == reader.OK:
示例#22
0
import ssd1306
import time

PWR_ON = 2
OLED_PWR = 33
TOUCH = 15
TOUCH_PWR = 32

TOUCHD = False

pwr_on = Pin(2, Pin.OUT, value=0)
oled_pwr = Pin(33, Pin.OUT, value=0)
touch = Pin(TOUCH, Pin.IN)
touch_pwr = Pin(TOUCH_PWR, Pin.OUT, value=0)

spi = SoftSPI(baudrate=27000000, sck=Pin(18), mosi=Pin(23), miso=Pin(32))
dc = Pin(19)
rst = Pin(4)
cs = Pin(5)

pwr_on.value(1)
touch_pwr.value(0)

oled_pwr.value(1)
display = ssd1306.SSD1306_SPI(128, 64, spi, dc, rst, cs)
display.poweron()
display.text('Hello', 0, 0, 1)
display.show()

while (1):
    SoftSPI.deinit(spi)
示例#23
0
 def _init_spi(self, baudrate):
     if self._spi is None:
         self._spi = SoftSPI(baudrate=baudrate, polarity=0, phase=0,
                             sck=Pin(self.SCK), mosi=Pin(self.MOSI),
                             miso=Pin(self.MISO))
     self._spi.init(baudrate=baudrate)
示例#24
0
def initSPI():
    spi = SoftSPI(baudrate=config.BAUD,
                  sck=Pin(config.SCK),
                  mosi=Pin(config.MOSI),
                  miso=Pin(config.MISO))
    return spi
示例#25
0
def main():
    global m_selected_device, m_selected_device_idx, m_all_devices, m_env_data, m_has_update, m_tim0
    global CLOCKMODE
    mqtt_client = None
    hasNetwork = initNetwork(secrets.SSID, secrets.PASS)
    spi = initSPI()
    display = initDisplay(spi)
    bignum = Writer(display, largedigits, verbose=False)
    wris = Writer(display, smallfont, verbose=False)
    wrisc = Writer(display, tinyfont, verbose=False)
    if hasNetwork:
        mqtt_client = initMQTT()
        ntptime.settime()
    powerOn()
    display.poweron()
    adc = initADC()
    batt_lvl = readBatteryLevel(adc)
    display.fill(0)
    wris.set_textpos(display, 0, 0)
    wris.printstring('Weather 1.0')
    if hasNetwork:
        display.text('WiFi', 0, 48, 1)
    if mqtt_client is not None:
        display.text('WiFi+MQTT', 0, 48, 1)
    display.show()
    time.sleep(2)
    was_touched = False
    virgin = True
    touch_start_time = 0
    m_tim0 = None
    while 1:
        mc = False
        if mqtt_client is not None:
            mqtt_client.check_msg()
            # mc = mqtt_client.connect(clean_session=False)
            mc = True
        # Touch power overlapped with MISO, need to take SPI away fist
        SoftSPI.deinit(spi)
        touch = initTouch()
        time.sleep_ms(50)
        # We only act when finger lifted
        touched = (touch.value() == 1)
        if (touched and not was_touched):
            touch_start_time = time.time()
        released = (not touched and was_touched)
        was_touched = touched
        if not released and touched:
            if (touch_start_time > 0) and (
                (time.time() - touch_start_time) > 3):
                # Hold for 5 seconds, a long touch
                if not CLOCKMODE:
                    touch_start_time = 0
                    CLOCKMODE = True
                else:
                    CLOCKMODE = False
                    touch_start_time = 0
                    virgin = True
                    if m_tim0 is not None:
                        m_tim0.deinit()
                        m_tim0 = None
        elif released and (
            (time.time() - touch_start_time) <= 3) and CLOCKMODE:
            if CLOCKMODE:
                touch_start_time = 0
                m_tim0 = Timer(0)
                m_tim0.init(period=2000,
                            mode=Timer.ONE_SHOT,
                            callback=lambda t: set_clockMode())
                virgin = True
            CLOCKMODE = False
        # We are done, SPI again
        spi = initSPI()
        if (released or virgin) and not CLOCKMODE:
            if m_tim0 is not None:
                m_tim0.deinit()
                m_tim0 = Timer(0)
                m_tim0.init(period=2000,
                            mode=Timer.ONE_SHOT,
                            callback=lambda t: set_clockMode())
            if len(m_all_devices) > 0:
                if not virgin:
                    # First touch will not move pointer forward
                    m_selected_device_idx = m_selected_device_idx + 1
                    if m_selected_device_idx >= len(m_all_devices):
                        m_selected_device_idx = 0
                    m_has_update = False
                if released:
                    virgin = False  # Touched, no longer virgin
                m_selected_device = m_all_devices[m_selected_device_idx]
        (temp, humi, pres, lux) = m_env_data[m_selected_device]
        #            display.fill_rect(0, 0, 127, 16, 0)
        if not CLOCKMODE:
            display.fill(0)
            #            display.text(m_selected_device, 0, 0, 1)
            if (config.STYLE == 0):
                if (temp is not None):
                    display.text(temp, 8, 16, 1)
                if (humi is not None):
                    display.text(humi, 64, 16, 1)
                if (pres is not None):
                    display.text(pres, 8, 32, 1)
                if (lux is not None):
                    display.text(lux, 64, 32, 1)
            else:
                row = 24
                if (temp is not None):
                    bignum.set_textpos(display, col=0, row=row)
                    bignum.printstring(str(temp) + '"c')
                if (humi is not None):
                    wris.set_textpos(display,
                                     col=config.DISPLAY_WIDTH -
                                     wris.stringlen('{:s}%'.format(humi)),
                                     row=row + 10)
                    wris.printstring('{:s}%'.format(humi))
        else:
            print_clock(display, bignum, wris)
            if temp is not None:
                temp = '{:d}'.format(round(float(temp)))
                wris.set_textpos(display,
                                 col=config.DISPLAY_WIDTH -
                                 wris.stringlen(temp),
                                 row=42)
                wris.printstring(temp)

        batt_lvl = readBatteryLevel(adc)
        print_status(display, hasNetwork, mqtt_client is not None,
                     m_has_update, batt_lvl)

    if mqtt_client is not None:
        mqtt_client.disconnect()
def callback_b2(p):
    fill_random_color()


button1.irq(
    trigger=Pin.IRQ_FALLING, handler=callback_b1
)  # interrupt for right button (button 2)
button2.irq(
    trigger=Pin.IRQ_FALLING, handler=callback_b2
)  # interrupt for left button (button 1)

BLK = Pin(BL_Pin, Pin.OUT)
spi = SoftSPI(
    baudrate=80000000,
    miso=Pin(MISO_Pin),
    mosi=Pin(MOSI_Pin, Pin.OUT),
    sck=Pin(SCLK_Pin, Pin.OUT),
)

display = st7789.ST7789(spi, 135, 240, cs=Pin(CS_Pin), dc=Pin(DC_Pin), rst=None)


def clear_screen():
    display._set_mem_access_mode(0, False, False, False)
    display.fill(0)  # filling the display with black


def fill_random_color():
    fill_hline()
    fill_vline()
    display.fill(random_color())
示例#27
0
from machine import Pin, SoftSPI
import tinypico as TinyPICO
from dotstar import DotStar
import time, random, micropython, gc

# Configure SPI for controlling the DotStar
# Internally we are using software SPI for this as the pins being used are not hardware SPI pins
spi = SoftSPI(sck=Pin(TinyPICO.DOTSTAR_CLK),
              mosi=Pin(TinyPICO.DOTSTAR_DATA),
              miso=Pin(TinyPICO.SPI_MISO))

# Create a DotStar instance
dotstar = DotStar(spi, 1, brightness=0.5)  # Just one DotStar, half brightness

# Turn on the power to the DotStar
TinyPICO.set_dotstar_power(True)

# Say hello
print("\nHello from TinyPICO!")
print("--------------------\n")

# Show some info on boot
print("Battery Voltage is {}V".format(TinyPICO.get_battery_voltage()))
print("Battery Charge State is {}\n".format(TinyPICO.get_battery_charging()))

# Show available memory
print("Memory Info - micropython.mem_info()")
print("------------------------------------")
micropython.mem_info()

# Create a colour wheel index int
示例#28
0
    i2c_sda = Pin(4, Pin.OUT, Pin.PULL_UP)
    # Create the bus object
    i2c = SoftI2C(scl=i2c_scl, sda=i2c_sda)
    # Create the display object
    oled = SSD1306_I2C(oled_width, oled_height, i2c)
    oled.fill(0)
    oled.text('Samim SmartHome', 0, 10)
    oled.text('LoRaMQTTDev '+str(DEV_VER), 0, 20)
    oled.show()
    print("OLED configured")

if module_config['module_type']=='ESP32':
    print("Configuring ESP32.")
    device_spi = SoftSPI(baudrate = 10000000, 
            polarity = 0, phase = 0, bits = 8, firstbit = SoftSPI.MSB,
            sck = Pin(device_config['sck'], Pin.OUT, Pin.PULL_DOWN),
            mosi = Pin(device_config['mosi'], Pin.OUT, Pin.PULL_UP),
            miso = Pin(device_config['miso'], Pin.IN, Pin.PULL_UP))
else:
    print("Configuring ESP8266")
    device_spi = SoftSPI(baudrate = 10000000, 
            polarity = 0, phase = 0, bits = 8, firstbit = SoftSPI.MSB,
            sck = Pin(device_config['sck'], Pin.OUT),
            mosi = Pin(device_config['mosi'], Pin.OUT, Pin.PULL_UP),
            miso = Pin(device_config['miso'], Pin.IN, Pin.PULL_UP))

wdt.feed()
    
lora = SX127x(device_spi, pins=device_config, parameters=lora_parameters)

wdt.feed()
示例#29
0
adc.read()  # read value, 0-4095 across voltage range 0.0v - 1.0v

adc.atten(ADC.ATTN_11DB)  # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v)
adc.width(ADC.WIDTH_9BIT)  # set 9 bit return values (returned range 0-511)
adc.read()  # read value using the newly configured attenuation and width


# Software SPI bus


from machine import Pin, SoftSPI

# construct a SoftSPI bus on the given pins
# polarity is the idle state of SCK
# phase=0 means sample on the first edge of SCK, phase=1 means the second
spi = SoftSPI(baudrate=100000, polarity=1, phase=0, sck=Pin(0), mosi=Pin(2), miso=Pin(4))

spi.init(baudrate=200000)  # set the baudrate

spi.read(10)  # read 10 bytes on MISO
spi.read(10, 0xFF)  # read 10 bytes while outputting 0xff on MOSI

buf = bytearray(50)  # create a buffer
spi.readinto(buf)  # read into the given buffer (reads 50 bytes in this case)
spi.readinto(buf, 0xFF)  # read into the given buffer and output 0xff on MOSI

spi.write(b"12345")  # write 5 bytes on MOSI

buf = bytearray(4)  # create a buffer
spi.write_readinto(b"1234", buf)  # write to MOSI and read from MISO into the buffer
spi.write_readinto(buf, buf)  # write buf to MOSI and read MISO back into buf
示例#30
0
def main():
    '''
    The big show!
    '''
    #enable display and clear screen

    tft = st7789.ST7789(SoftSPI(baudrate=30000000,
                                polarity=1,
                                sck=Pin(10),
                                mosi=Pin(11),
                                miso=Pin(16)),
                        135,
                        240,
                        reset=Pin(12, Pin.OUT),
                        cs=Pin(9, Pin.OUT),
                        dc=Pin(8, Pin.OUT),
                        backlight=Pin(13, Pin.OUT),
                        rotation=1)

    tft.fill(st7789.BLACK)  # clear screen

    height = tft.height  # height of display in pixels
    width = tft.width  # width if display in pixels

    tfa = 40  # top free area when scrolling
    bfa = 40  # bottom free area when scrolling

    scroll = 0  # scroll position
    wheel = 0  # color wheel position

    tft.vscrdef(tfa, width, bfa)  # set scroll area
    tft.vscsad(scroll + tfa)  # set scroll position
    tft.fill(st7789.BLACK)  # clear screen

    half = (height >> 1) - 1  # half the height of the dislay
    interval = 0  # steps between new points
    increment = 0  # increment per step
    counter = 1  # step counter, overflow to start
    current_y = 0  # current_y value (right point)
    last_y = 0  # last_y value (left point)

    # segment offsets
    x_offsets = [x * (width // 8) - 1 for x in range(2, 9)]

    while True:
        # when the counter exceeds the interval, save current_y to last_y,
        # choose a new random value for current_y between 0 and 1/2 the
        # height of the display, choose a new random interval then reset
        # the counter to 0

        if counter > interval:
            last_y = current_y
            current_y = random.randint(0, half)
            counter = 0
            interval = random.randint(10, 100)
            increment = 1 / interval  # increment per step

        # clear the first column of the display and scroll it
        tft.vline(scroll, 0, height, st7789.BLACK)
        tft.vscsad(scroll + tfa)

        # get the next point between last_y and current_y
        tween = int(between(last_y, current_y, counter * increment))

        # draw mirrored pixels across the display at the offsets using the color_wheel effect
        for i, x_offset in enumerate(x_offsets):
            tft.pixel((scroll + x_offset) % width, half + tween,
                      color_wheel(wheel + (i << 2)))
            tft.pixel((scroll + x_offset) % width, half - tween,
                      color_wheel(wheel + (i << 2)))

        # increment scroll, counter, and wheel
        scroll = (scroll + 1) % width
        wheel = (wheel + 1) % 256
        counter += 1