not logged in | [Login]

Here we show how to control Pins using the pyb.Pin interface. The programmers guide is here.

  • Setting a pin up
  • Reading a pin's digital value
  • Writing (setting) a pin's high or low
  • Reading an Analog value
  • Writing an Analog Value

Basic usage

Setting a pin to a digital value

g = pyb.Pin(pin_id, mode, pull) # mode and pull are optional arguments and default to input and no-pullup
# e.g. if:
#    X1 is how the pin is labeled on the board,
#    using X1 for output to control an LED,
#    we want a pullup resistor on the output.
g = pyb.Pin('X1', pyb.Pin.OUT_PP, Pin.PULL_UP)
g.high() # sets the pin high
g.value(True) # sets it high, False is low
Reading a digital value from a Pin
g = pyb.Pin('X1', pyb.Pin.IN)
state = g.value() # no argument to value means read.
Reading an Analog value from a Pin
g = pyb.Pin('X1', pyb.Pin.ANALOG)
state = g.value() # no argument to value means read.

Details

Selecting a Pin

There are several ways to identify the pin to control.

  • by name
    • 'X1' (example above) which is defined on the board
  • by board lookup
    • mypin = pyb.Pin.board.X1
  • by cpu lookup (not all pins are exposed on the edge connectors on every board)
    • mypin = pyb.Pin.cpu.C12
  • by defining your own mapping
    • pyb.Pin.dict["LeftMotorDir"] = pyb.Pin.cpu.C12
    • mypin = pyb.Pin("LeftMotorDir")

and use it like so: g = pyb.Pin(mypin, pyb.Pin.OUT_PP) or g = pyb.Pin(mypin, pyb.Pin.OUT_PP, Pin.PULL_UP)

Setting up the pin's modes

A Pin can act in one of the following modes.

  • Pin.IN - configure the pin for input
  • Pin.OUT_PP - configure the pin for output, with push-pull control
  • Pin.OUT_OD - configure the pin for output, with open-drain control
  • Pin.AF_PP - configure the pin for alternate function, pull-pull
  • Pin.AF_OD - configure the pin for alternate function, open-drain
  • Pin.ANALOG - configure the pin for analog.

You would use Push-pull control to do ... and Open-drain to ...

A Pin can have the following pullup settings:

  • Pin.PULL_NONE - no pull up or down resistors - This is the default
  • Pin.PULL_UP - enable the pull-up resistor
  • Pin.PULL_DOWN - enable the pull-down resistor