Python源码示例:machine.Pin()

示例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 __init__(self,
                 pin_id_led = ON_BOARD_LED_PIN_NO,
                 on_board_led_high_is_on = ON_BOARD_LED_HIGH_IS_ON,
                 pin_id_reset = PIN_ID_FOR_LORA_RESET,
                 blink_on_start = (2, 0.5, 0.5),
                 oled_width = OLED_WIDTH, oled_height = OLED_HEIGHT,
                 scl_pin_id = PIN_ID_SCL, sda_pin_id = PIN_ID_SDA,
                 freq = OLED_I2C_FREQ):

        controller_esp.Controller.__init__(self,
                                           pin_id_led,
                                           on_board_led_high_is_on,
                                           pin_id_reset,
                                           blink_on_start)

        self.reset_pin(self.prepare_pin(self.PIN_ID_FOR_OLED_RESET))

        i2c = machine.I2C(scl = machine.Pin(scl_pin_id, machine.Pin.OUT),
                          sda = machine.Pin(sda_pin_id),
                          freq = freq)
        display_ssd1306_i2c.Display.__init__(self, i2c,
                                             width = oled_width, height = oled_height)
        self.show_text('Hello !') 
示例3
def main():
    # Wemos D1 Mini NeoPixel Shield is on pin 4 (D2)
    pin = machine.Pin(4, machine.Pin.OUT)
    # There is just 1 Neopixel LED on Shield
    n = neopixel.NeoPixel(pin, 1)
    # Wemos D1 Mini DHT Shield is on pin 2 (D4)
    d = dht.DHT22(machine.Pin(2))

    while True:
        d.measure()
        h = d.humidity()
        print(h)

        if (h < 45):
            # RGB values
            n[0] = (127, 0, 0)
        else:
            n[0] = (0, 127, 0)
        
        # Write value to LEDs
        n.write()

        time.sleep(10) 
示例4
def main():
    #h = DHT11(machine.Pin(33)) # J8
    h = DHT11(machine.Pin(26)) # J7

    ugfx.set_default_font('IBMPlexMono_Bold24')
    ugfx.clear()
    ugfx.Label(40, 0, 240, 60, text='DHT11/22 Demo')

    ugfx.set_default_font('IBMPlexMono_Regular24')
    l = ugfx.Label(40, 60, 240, 120, text='')

    while True:
        h.measure()
        h.temperature()
        l.text('temperature:{},humidity:{}'.format(h.temperature(), h.humidity()))
        time.sleep(1) 
示例5
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() 
示例6
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() 
示例7
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() 
示例8
def pin_on(self, pin: Union[int, str], pull_up: bool = False, **kwargs):
        """
        Set the specified PIN to HIGH.

        :param pin: GPIO PIN number or configured name.
        :param pull_up: Set to True if the PIN has a (weak) pull-up resistor attached.
        :param kwargs: Parameters to pass to :meth:`platypush.plugins.esp.EspPlugin.execute`.
        """
        device = self._get_device(**kwargs)
        pin = device.get_pin(pin)
        code = '''
import machine
pin = machine.Pin({pin}, machine.Pin.OUT{pull_up})
pin.on()
'''.format(pin=pin, pull_up=', machine.Pin.PULL_UP' if pull_up else '')

        self.execute(code, **kwargs) 
示例9
def pin_off(self, pin: Union[int, str], pull_up: bool = False, **kwargs):
        """
        Set the specified PIN to LOW.

        :param pin: GPIO PIN number.
        :param pull_up: Set to True if the PIN has a (weak) pull-up resistor attached.
        :param kwargs: Parameters to pass to :meth:`platypush.plugins.esp.EspPlugin.execute`.
        """
        device = self._get_device(**kwargs)
        pin = device.get_pin(pin)
        code = '''
import machine
pin = machine.Pin({pin}, machine.Pin.OUT{pull_up})
pin.off()
'''.format(pin=pin, pull_up=', machine.Pin.PULL_UP' if pull_up else '')

        self.execute(code, **kwargs) 
示例10
def pin_toggle(self, pin: Union[int, str], pull_up: bool = False, **kwargs):
        """
        Toggle a PIN state - to HIGH if LOW, to LOW if HIGH.

        :param pin: GPIO PIN number or configured name.
        :param pull_up: Set to True if the PIN has a (weak) pull-up resistor attached.
        :param kwargs: Parameters to pass to :meth:`platypush.plugins.esp.EspPlugin.execute`.
        """
        device = self._get_device(**kwargs)
        pin = device.get_pin(pin)
        code = '''
import machine
pin = machine.Pin({pin}, machine.Pin.OUT{pull_up})
if pin.value():
    pin.off()
else:
    pin.on()
'''.format(pin=pin, pull_up=', machine.Pin.PULL_UP' if pull_up else '')

        self.execute(code, **kwargs) 
示例11
def pin_read(self, pin: Union[int, str], out: bool = False, pull_up: bool = False, **kwargs) -> bool:
        """
        Get the ON/OFF value of a PIN.

        :param pin: GPIO PIN number or configured name.
        :param out: Treat the PIN as an output PIN - e.g. if you usually write to it and now want to read the
            value. If not set, then the PIN will be treated as an input PIN.
        :param pull_up: Set to True if the PIN has a (weak) pull-up resistor attached.
        :param kwargs: Parameters to pass to :meth:`platypush.plugins.esp.EspPlugin.execute`.
        """
        device = self._get_device(**kwargs)
        pin = device.get_pin(pin)
        code = '''
import machine
pin = machine.Pin({pin}, machine.Pin.{inout}{pull_up})
pin.value()
'''.format(pin=pin, inout='OUT' if out else 'IN', pull_up=', machine.Pin.PULL_UP' if pull_up else '')

        return bool(self.execute(code, **kwargs).output) 
示例12
def pwm_freq(self, pin: Union[int, str], freq: Optional[int] = None, **kwargs) -> Optional[int]:
        """
        Get/set the frequency of a PWM PIN.

        :param pin: GPIO PIN number or configured name.
        :param freq: If set, set the frequency for the PIN in Hz.
        :param kwargs: Parameters to pass to :meth:`platypush.plugins.esp.EspPlugin.execute`.
        """
        device = self._get_device(**kwargs)
        pin = device.get_pin(pin)
        code = '''
import machine
pin = machine.PWM(machine.Pin({pin}))
pin.freq({freq})
'''.format(pin=pin, freq=freq if freq else '')

        ret = self.execute(code, **kwargs).output
        if not freq:
            return int(ret) 
示例13
def pwm_on(self, pin: Union[int, str], freq: Optional[int] = None, duty: Optional[int] = None, **kwargs):
        """
        Set the specified PIN to HIGH.

        :param pin: GPIO PIN number or configured name.
        :param freq: PWM PIN frequency.
        :param duty: PWM PIN duty cycle.
        :param kwargs: Parameters to pass to :meth:`platypush.plugins.esp.EspPlugin.execute`.
        """
        device = self._get_device(**kwargs)
        pin = device.get_pin(pin)
        code = '''
import machine
pin = machine.PWM(machine.Pin({pin}))

if {freq}:
    pin.freq({freq})
if {duty}:
    pin.duty({duty})

pin.on()
'''.format(pin=pin, freq=freq, duty=duty)

        self.execute(code, **kwargs) 
示例14
def pwm_off(self, pin: Union[int, str], **kwargs):
        """
        Turn off a PWM PIN.

        :param pin: GPIO PIN number or configured name.
        :param kwargs: Parameters to pass to :meth:`platypush.plugins.esp.EspPlugin.execute`.
        """
        device = self._get_device(**kwargs)
        pin = device.get_pin(pin)
        code = '''
import machine
pin = machine.PWM(machine.Pin({pin}))
pin.deinit()
'''.format(pin=pin)

        self.execute(code, **kwargs) 
示例15
def tick(self, pin=2) :
        import dht
        import machine
        try :
            d = dht.DHT11(machine.Pin(pin))
            d.measure()
            tempf = 32.0 + 1.8 * d.temperature()
            humidity = d.humidity()
            logging.debug("Read measurements off DHT11: temp(f): %s humidity: %s" % (tempf, humidity))
            self._upload(tempf, humidity)
            util.clear_led_error()
        except Exception as E :
            logging.error("An error occurred taking measurements: %s", E)
            util.set_led_error()
    
    ##
    ## Internal operations
    ## 
示例16
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) 
示例17
def configure(self, baudrate=100000, polarity=0, phase=0, bits=8):
        """Update the configuration"""
        from machine import Pin
        from machine import SPI as _SPI

        if self._locked:
            # TODO verify if _spi obj 'caches' sck, mosi, miso to
            # avoid storing in _attributeIds (duplicated in busio)
            # i.e. #init ignores MOSI=None rather than unsetting
            self._spi.init(
                baudrate=baudrate,
                polarity=polarity,
                phase=phase,
                bits=bits,
                firstbit=_SPI.MSB,
                sck=Pin(self._pins[0].id),
                mosi=Pin(self._pins[1].id),
                miso=Pin(self._pins[2].id),
            )
        else:
            raise RuntimeError("First call try_lock()") 
示例18
def __init__(self, type, scl, sda):
        self.type = type

        if self.type == 0:
            i2c_bus = I2C(scl=Pin(scl), sda=Pin(sda), freq=100000)
            self.sensor = BMP180.BMP180(i2c_bus)
            self.sensor.oversample_sett = 2
            self.sensor.baseline = 101325

        elif self.type == 1:
             pass #TODO

        else:
            log.error("Unknown sensor type '{}'. Cannot instantiate it.".format(self.type))

    # @timed_function 
示例19
def __init__(self, address=0x20, gpioScl=5, gpioSda=4):
        """Initialize MCP230xx at specified I2C address and bus number.  If bus
        is not specified it will default to the appropriate platform detected bus.
        """
        self.address = address
        self.i2c = I2C(scl=Pin(gpioScl),sda=Pin(gpioSda))
        # Assume starting in ICON.BANK = 0 mode (sequential access).
        # Compute how many bytes are needed to store count of GPIO.
        self.gpio_bytes = self.NUM_GPIO//8
        # Buffer register values so they can be changed without reading.
        self.iodir = bytearray(self.gpio_bytes)  # Default direction to all inputs.
        self.gppu = bytearray(self.gpio_bytes)  # Default to pullups disabled.
        self.gpio = bytearray(self.gpio_bytes)
        # Write current direction and pullup buffer state.
        self.write_iodir()
        self.write_gppu() 
示例20
def __init__(self, pin):
        Thing.__init__(self,
                       'Button 0',
                       ['BinarySensor'],
                       'Button 0 on SparkFun ESP32 Thing')
        self.pin = machine.Pin(pin, machine.Pin.IN)

        self.button = Value(False)
        self.add_property(
            Property(self,
                     'on',
                     self.button,
                     metadata={
                         'type': 'boolean',
                         'description': 'Button 0 pressed',
                         'readOnly': True,
                     }))
        self.prev_pressed = self.is_pressed() 
示例21
def __init__(self, name="One Wire DS18B20", pin=12, interval=10, pull=-1):
        super().__init__(id="ds18b20", name=name, type="ds18b20")
        self.ds18b20 = DS18X20(OneWire(Pin(pin)))
        addrs = self.ds18b20.scan()
        if not addrs:
            raise Exception("no DS18B20 found at bus on pin %d" % pin)
        # save what should be the only address found
        self.addr = addrs.pop()

        self.temperature = 0

        self.interval = interval

        self.temp_property = HomieNodeProperty(
            id="temperature",
            name="Temperature",
            datatype=FLOAT,
            format="-40:80",
            unit="°F",
        )
        self.add_property(self.temp_property)

        loop = get_event_loop()
        loop.create_task(self.update_data()) 
示例22
def __init__(self, settings):
        """
        Initialized ADC unit.
        """

        super().__init__(settings)

        # ADC Pin to sample from.
        self.pin = None

        # Main resistor value (R1).
        self.resistor_r1 = None

        # Resistor between input pin and ground (R2).
        self.resistor_r2 = None

        # Reference to platform ADC object.
        self.adc = None

        self.setup() 
示例23
def blink_led(self, color, count=1):
        """

        :param color: rgb value as three hex values 0-255, e.g. 0x00FF00 for green
        :param count:  (Default value = 1)

        """
        if self.platform_info.vendor == self.platform_info.MICROPYTHON.Pycom:
            import pycom
            terkin_blink_pattern = self.settings.get('main.rgb_led.terkin', False)
            if terkin_blink_pattern:
                for _ in range(count):
                    pycom.rgbled(color)
                    time.sleep(0.15)
                    pycom.rgbled(0x000000)
                    time.sleep(0.10)
        elif self.settings.get('main.rgb_led.simple', False):
            led = machine.Pin(int(self.settings.get('main.rgb_led.pin')[1:]),machine.Pin.OUT)
            for _ in range(count):
                led.value(1)
                time.sleep(0.15)
                led.value(0)
                time.sleep(0.10) 
示例24
def __init__(self, 
                 width = 128, height = 64, 
                 scl_pin_id = 5, sda_pin_id = 4,
                 freq = 400000): 
                 
        self.width = width
        self.height = height
        self.i2c = machine.I2C(scl = machine.Pin(scl_pin_id, machine.Pin.OUT),
                               sda = machine.Pin(sda_pin_id), 
                               freq = freq) 
        self.display = ssd1306.SSD1306_I2C(width, height, self.i2c)
        self.show = self.display.show 
示例25
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 
示例26
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 
示例27
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 
示例28
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 
示例29
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 
示例30
def main():
    led = machine.Pin(2, machine.Pin.OUT)
    led.value(1)
    s = socket.socket()
    ai = socket.getaddrinfo("0.0.0.0", 8080)
    addr = ai[0][-1]

    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    s.bind(addr)
    s.listen(5)
    print("Listening, connect your browser to http://<this_host>:8080/")

    counter = 0
    while True:
        res = s.accept()
        client_s = res[0]
        client_addr = res[1]
        req = client_s.recv(1024)
        cmd = getCommand(req)
        
        print(cmd)

        if (cmd == "/on"):
            led.value(0)
        elif (cmd == "/off"):
            led.value(1)
        
        client_s.send(CONTENT % counter)
        client_s.close()
        counter += 1
        print()