Python machine.Pin() Examples

The following are 30 code examples of machine.Pin(). 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 machine , or try the search function .
Example #1
Source File: controller_esp_ttgo_lora_oled.py    From SX127x_driver_for_MicroPython_on_ESP8266 with GNU General Public License v3.0 7 votes vote down vote up
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 !') 
Example #2
Source File: demo_sprite.py    From micropython-ssd1351 with MIT License 7 votes vote down vote up
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() 
Example #3
Source File: __init__.py    From platypush with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: __init__.py    From developer-badge-2018-apps with Apache License 2.0 6 votes vote down vote up
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) 
Example #5
Source File: hmeter.py    From Micropython with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: demo_colored_squares.py    From micropython-ssd1351 with MIT License 6 votes vote down vote up
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() 
Example #7
Source File: demo_contrast.py    From micropython-ssd1351 with MIT License 6 votes vote down vote up
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() 
Example #8
Source File: demo_images.py    From micropython-ssd1351 with MIT License 6 votes vote down vote up
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() 
Example #9
Source File: __init__.py    From platypush with MIT License 6 votes vote down vote up
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) 
Example #10
Source File: ws.py    From esp8266 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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
    ## 
Example #11
Source File: __init__.py    From platypush with MIT License 6 votes vote down vote up
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) 
Example #12
Source File: __init__.py    From platypush with MIT License 6 votes vote down vote up
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) 
Example #13
Source File: __init__.py    From platypush with MIT License 6 votes vote down vote up
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) 
Example #14
Source File: __init__.py    From platypush with MIT License 6 votes vote down vote up
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) 
Example #15
Source File: test_st7789.py    From st7789py_mpy with MIT License 6 votes vote down vote up
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) 
Example #16
Source File: bitbangio.py    From Adafruit_Blinka with MIT License 6 votes vote down vote up
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()") 
Example #17
Source File: BMP.py    From illuminOS with MIT License 6 votes vote down vote up
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 
Example #18
Source File: mcp.py    From micropython-mcp230xx with GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example #19
Source File: sparkfun_esp32_thing.py    From webthing-upy with MIT License 6 votes vote down vote up
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() 
Example #20
Source File: main.py    From microhomie with MIT License 6 votes vote down vote up
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()) 
Example #21
Source File: __init__.py    From platypush with MIT License 6 votes vote down vote up
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) 
Example #22
Source File: device.py    From terkin-datalogger with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #23
Source File: system.py    From terkin-datalogger with GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example #24
Source File: esp8266.py    From tinyweb with MIT License 5 votes vote down vote up
def get(self, data):
        res = []
        for p, d in pins.items():
            val = machine.Pin(p).value()
            res.append({'gpio': p, 'nodemcu': d, 'value': val})
        return {'pins': res}


# RESTAPI: GPIO controller: turn PINs on/off 
Example #25
Source File: pmux.py    From pysmartnode with MIT License 5 votes vote down vote up
def mode(self, mode):
        if type(mode) == str:
            if mode not in dir(machine.Pin):
                raise TypeError("Mode {!r} is not available".format(mode))
            mode = getattr(machine.Pin, mode)
        self.pin.mode(mode) 
Example #26
Source File: pmux.py    From pysmartnode with MIT License 5 votes vote down vote up
def Pin(self, p):
        return Pin(self, p) 
Example #27
Source File: ulno_iot_mpr121.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def __init__(self, i2c_sda_pin, i2c_scl_pin):
        self.i2c = I2C(sda=Pin(i2c_sda_pin), scl=Pin(i2c_scl_pin))
        self.addr = 90 # I2C address of the MPR121
        # enable ELE0 - ELE3
        self.enable_elec(ELEC_ENABLE_DEFAULT) 
Example #28
Source File: bitbangio.py    From Adafruit_Blinka with MIT License 5 votes vote down vote up
def init(self, scl, sda, frequency):
        """Initialization"""
        from machine import Pin
        from machine import I2C as _I2C

        self.deinit()
        id = (  # pylint: disable=redefined-builtin
            -1
        )  # force bitbanging implementation - in future
        # introspect platform if SDA/SCL matches hardware I2C
        self._i2c = _I2C(id, Pin(scl.id), Pin(sda.id), freq=frequency) 
Example #29
Source File: pmsa003.py    From uPySensors with Apache License 2.0 5 votes vote down vote up
def __init__(self, uart, pins):
        
        self._uart = uart
        self._pins = pins
        
        self._set = machine.Pin(self._pins["set"], machine.Pin.OUT, value=0)
        self._rst = machine.Pin(self._pins["rst"], machine.Pin.OUT, value=0)
        self._uart.init(tx=self._pins["tx"], rx=self._pins["rx"])
        self.power_off() 
Example #30
Source File: ST7735.py    From uPySensors with Apache License 2.0 5 votes vote down vote up
def __init__( self, spi, aDC, aReset, aCS) :
    """aLoc SPI pin location is either 1 for 'X' or 2 for 'Y'.
       aDC is the DC pin and aReset is the reset pin."""
    self._size = ScreenSize
    self._offset = bytearray([0,0])
    self.rotate = 0                    #Vertical with top toward pins.
    self._rgb = True                   #color order of rgb.
    self.dc  = machine.Pin(aDC, machine.Pin.OUT, machine.Pin.PULL_DOWN)
    self.reset = machine.Pin(aReset, machine.Pin.OUT, machine.Pin.PULL_DOWN)
    self.cs = machine.Pin(aCS, machine.Pin.OUT, machine.Pin.PULL_DOWN)
    self.cs(1)
    self.spi = spi
    self.colorData = bytearray(2)
    self.windowLocData = bytearray(4)