Reputation: 418
Is there a way to get/set the mode of a Pin object in MicroPython on the Raspberry Pi Pico?
The standard library has a Pin.mode() function, but it is not supported on the Pi Pico. Is there a way to directly change/get the mode of a pin instance?
The only workaround for at least reading the pin mode I came up with is using a regular expression:
import re
from machine import Pin
def is_input(pin: Pin):
"""
Returns True, if the pin object's mode is set as INPUT, else False.
"""
return re.search(r'mode=(\w*)', str(pin)).group(1) == 'IN'
p = Pin(0, Pin.IN)
print(is_input(p)) #True
p = Pin(0, Pin.OUT)
print(is_input(p)) #False
Upvotes: 0
Views: 1223
Reputation: 418
I wrote a wrapper class to around the machine.Pin
class which keeps track of the mode and pull setting and allows to change their values by re-initializing the underlying machine.Pin
instance.
import machine.Pin
class Pin:
"""
Wrapper around machine.Pin which keeps track of mode and pull settings.
"""
def __init__(self, id, mode=machine.Pin.IN, pull=None, **kwargs):
"""
:param id: GPIO number of the Pin
:param mode: GPIO mode. Either machine.Pin.IN or machine.Pin.OUT; Defaults to machine.Pin.IN
:param pull: GPIO pu/pd. Either machine.Pin.PULL_UP, machine.Pin.PULL_DOWN, None; Default to None
:param kwargs: optional kw-only arguments for machine.Pin constructor
"""
self._mode = mode
self._pull = pull
self._id = id
self._pin = machine.Pin(id, mode=mode, pull=pull, **kwargs)
def __getattr__(self, item):
if item != '_pin':
return getattr(self._pin, item)
def __setattr__(self, key, value):
if not hasattr(self, key) and hasattr(self._pin, key):
setattr(self._pin, key, value)
else:
super().__setattr__(key, value)
def mode(self, mode=None):
"""
Get/set pin mode (input/output) by re-initializing pin.
:param mode: Either machine.Pin.IN or machine.Pin.OUT
:return: returns the current mode (machine.Pin.IN or machine.Pin.OUT) if mode was not provided.
"""
if mode is None:
return self._mode
else:
self._pin = machine.Pin(self._id, mode=mode, pull=self._pull)
self._mode = mode
def pull(self, pull=None):
"""
Get/set pin pull-up/pull-down by re-initializing pin.
:param pull: machine.Pin.PULL_UP, machine.Pin.PULL_DOWN, None
:return: returns the current pull setting (machine.Pin.PULL_UP, machine.Pin.PULL_DOWN, None) if pull was not \
provided.
"""
if pull is None:
return self._pull
else:
self._pin = machine.Pin(self._id, mode=self._mode, pull=pull)
self._pull = pull
Upvotes: 2