24.API - Pins

As of release 1.1, the GPIO Zero library can be roughly divided into twothings: pins and the devices that are connected to them. The majority of thedocumentation focuses on devices as pins are below the level that most usersare concerned with. However, some users may wish to take advantage of thecapabilities of alternative GPIO implementations or (in future) use GPIOextender chips. This is the purpose of the pins portion of the library.

When you construct a device, you pass in a pin specification. This is passed toa pinFactory which turns it into aPin implementation. Thedefault factory can be queried (and changed) withDevice.pin_factory.However, all classes (even internal devices) accept apin_factory keywordargument to their constructors permitting the factory to be overridden on aper-device basis (the reason for allowing per-device factories is made apparentin theConfiguring Remote GPIO chapter).

This is illustrated in the following flow-chart:

_images/device_pin_flowchart.svg

The default factory is constructed when the first device is initialised; if nodefault factory can be constructed (e.g. because no GPIO implementations areinstalled, or all of them fail to load for whatever reason), aBadPinFactory exception will be raised at construction time.

After importing gpiozero, until constructing a gpiozero device, the pin factoryisNone, but at the point of first construction the default pin factorywill come into effect:

pi@raspberrypi:~ $python3Python 3.7.3 (default, Apr  3 2019, 05:39:12)[GCC 8.2.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> from gpiozero import Device, LED>>> print(Device.pin_factory)None>>> led = LED(2)>>> Device.pin_factory<gpiozero.pins.rpigpio.RPiGPIOFactory object at 0xb667ae30>>>> led.pin_factory<gpiozero.pins.rpigpio.RPiGPIOFactory object at 0xb6323530>

As above, on a Raspberry Pi with the RPi.GPIO library installed, (assuming noenvironment variables are set), the default pin factory will beRPiGPIOFactory.

On a PC (with no pin libraries installed and no environment variables set),importing will work but attempting to create a device will raiseBadPinFactory:

ben@magicman:~ $python3Python 3.6.8 (default, Aug 20 2019, 17:12:48)[GCC 8.3.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> from gpiozero import Device, LED>>> print(Device.pin_factory)None>>> led = LED(2)...BadPinFactory: Unable to load any default pin factory!

24.1.Changing the pin factory

The default pin factory can be replaced by specifying a value for theGPIOZERO_PIN_FACTORY environment variable. For example:

pi@raspberrypi:~ $GPIOZERO_PIN_FACTORY=nativepython3Python 3.7.3 (default, Apr  3 2019, 05:39:12)[GCC 8.2.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> from gpiozero import Device>>> Device._default_pin_factory()<gpiozero.pins.native.NativeFactory object at 0x762c26b0>

To set theGPIOZERO_PIN_FACTORY for the rest of your session you canexport this value:

pi@raspberrypi:~ $exportGPIOZERO_PIN_FACTORY=nativepi@raspberrypi:~ $python3Python 3.7.3 (default, Apr  3 2019, 05:39:12)[GCC 8.2.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> import gpiozero>>> Device._default_pin_factory()<gpiozero.pins.native.NativeFactory object at 0x762c26b0>>>> quit()pi@raspberrypi:~ $python3Python 3.7.3 (default, Apr  3 2019, 05:39:12)[GCC 8.2.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> import gpiozero>>> Device._default_pin_factory()<gpiozero.pins.native.NativeFactory object at 0x762c26b0>

If you add theexport command to your~/.bashrc file, you’llset the default pin factory for all future sessions too.

If the environment variable is set, the corresponding pin factory will be used,otherwise each of the four GPIO pin factories will be attempted to be used inturn.

The following values, and the correspondingFactory andPinclasses are listed in the table below. Factories are listed in the order thatthey are tried by default.

Name

Factory class

Pin class

rpigpio

gpiozero.pins.rpigpio.RPiGPIOFactory

gpiozero.pins.rpigpio.RPiGPIOPin

lgpio

gpiozero.pins.lgpio.LGPIOFactory

gpiozero.pins.lgpio.LGPIOPin

pigpio

gpiozero.pins.pigpio.PiGPIOFactory

gpiozero.pins.pigpio.PiGPIOPin

native

gpiozero.pins.native.NativeFactory

gpiozero.pins.native.NativePin

If you need to change the default pin factory from within a script, either setDevice.pin_factory to the new factory instance to use:

fromgpiozero.pins.nativeimportNativeFactoryfromgpiozeroimportDevice,LEDDevice.pin_factory=NativeFactory()# These will now implicitly use NativePin instead of RPiGPIOPinled1=LED(16)led2=LED(17)

Or use thepin_factory keyword parameter mentioned above:

fromgpiozero.pins.nativeimportNativeFactoryfromgpiozeroimportLEDmy_factory=NativeFactory()# This will use NativePin instead of RPiGPIOPin for led1# but led2 will continue to use RPiGPIOPinled1=LED(16,pin_factory=my_factory)led2=LED(17)

Certain factories may take default information from additional sources.For example, to default to creating pins withgpiozero.pins.pigpio.PiGPIOPin on a remote pi called “remote-pi”you can set thePIGPIO_ADDR environment variable when running yourscript:

$GPIOZERO_PIN_FACTORY=pigpioPIGPIO_ADDR=remote-pipython3my_script.py

Like theGPIOZERO_PIN_FACTORY value, these can be exported from your~/.bashrc script too.

Warning

The astute and mischievous reader may note that it is possible to mixfactories, e.g. usingRPiGPIOFactory forone pin, andNativeFactory for another. Thisis unsupported, and if it results in your script crashing, your componentsfailing, or your Raspberry Pi turning into an actual raspberry pie, youhave only yourself to blame.

Sensible uses of multiple pin factories are given inConfiguring Remote GPIO.

24.2.Mock pins

There’s also aMockFactory which generates entirelyfake pins. This was originally intended for GPIO Zero developers who wish towrite tests for devices without having to have the physical device wired in totheir Pi. However, they have also proven useful in developing GPIO Zero scriptswithout having a Pi to hand. This pin factory will never be loaded by default;it must be explicitly specified, either by setting an environment variable orsetting the pin factory within the script. For example:

pi@raspberrypi:~ $GPIOZERO_PIN_FACTORY=mockpython3

or:

fromgpiozeroimportDevice,LEDfromgpiozero.pins.mockimportMockFactoryDevice.pin_factory=MockFactory()led=LED(2)

You can create device objects and inspect their value changing as you’d expect:

pi@raspberrypi:~ $ GPIOZERO_PIN_FACTORY=mock python3Python 3.7.3 (default, Apr  3 2019, 05:39:12)[GCC 8.2.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>>fromgpiozeroimportLED>>>led=LED(2)>>>led.value0>>>led.on()>>>led.value1

You can even control pin state changes to simulate device behaviour:

>>>fromgpiozeroimportLED,Button# Construct a couple of devices attached to mock pins 16 and 17, and link the devices>>>led=LED(17)>>>btn=Button(16)>>>led.source=btn# Initailly the button isn't "pressed" so the LED should be off>>>led.value0# Drive the pin low (this is what would happen electrically when the button is pressed)>>>btn.pin.drive_low()# The LED is now on>>>led.value1>>>btn.pin.drive_high()# The button is now "released", so the LED should be off again>>>led.value0

Several sub-classes of mock pins exist for emulating various other things(pins that do/don’t support PWM, pins that are connected together, pins thatdrive high after a delay, etc), for example, you have to useMockPWMPin to be able to use devices requiring PWM:

pi@raspberrypi:~ $GPIOZERO_PIN_FACTORY=mockGPIOZERO_MOCK_PIN_CLASS=mockpwmpinpython3

or:

fromgpiozeroimportDevice,LEDfromgpiozero.pins.mockimportMockFactory,MockPWMPinDevice.pin_factory=MockFactory(pin_class=MockPWMPin)led=LED(2)

Interested users are invited to read theGPIO Zero test suite for furtherexamples of usage.

24.3.Base classes

classgpiozero.Factory[source]

Generates pins and SPI interfaces for devices. This is an abstractbase class for pin factories. Descendentsmust override the followingmethods:

Descendentsmay override the following methods, if applicable:

close()[source]

Closes the pin factory. This is expected to clean up all resourcesmanipulated by the factory. It it typically called at scripttermination.

pin(name)[source]

Creates an instance of aPin descendent representing thespecified pin.

Warning

Descendents must ensure that pin instances representing the samehardware are identical; i.e. two separate invocations ofpin() for the same pin specification must return the sameobject.

release_all(reserver)[source]

Releases all pin reservations taken out byreserver. Seerelease_pins() for further information).

release_pins(reserver,*names)[source]

Releases the reservation ofreserver against pinnames. This istypically called duringclose() to clean upreservations taken during construction. Releasing a reservation that isnot currently held will be silently ignored (to permit clean-up afterfailed / partial construction).

reserve_pins(requester,*names)[source]

Called to indicate that the device reserves the right to use thespecified pinnames. This should be done during device construction.If pins are reserved, you must ensure that the reservation is releasedby eventually calledrelease_pins().

spi(**spi_args)[source]

Returns an instance of anSPI interface, for the specified SPIport anddevice, or for the specified pins (clock_pin,mosi_pin,miso_pin, andselect_pin). Only one of the schemes canbe used; attempting to mixport anddevice with pin numbers willraiseSPIBadArgs.

ticks()[source]

Return the current ticks, according to the factory. The reference pointis undefined and thus the result of this method is only meaningful whencompared to another value returned by this method.

The format of the time is also arbitrary, as is whether the time wrapsafter a certain duration. Ticks should only be compared using theticks_diff() method.

ticks_diff(later,earlier)[source]

Return the time in seconds between twoticks() results. Thearguments are specified in the same order as they would be in theformulalater -earlier but the result is guaranteed to be inseconds, and to be positive even if the ticks “wrapped” between callstoticks().

propertyboard_info

Returns aBoardInfo instance (or derivative) representing theboard that instances generated by this factory will be attached to.

classgpiozero.Pin[source]

Abstract base class representing a pin attached to some form of controller,be it GPIO, SPI, ADC, etc.

Descendents should override property getters and setters to accuratelyrepresent the capabilities of pins. Descendentsmust override thefollowing methods:

  • _get_info()

  • _get_function()

  • _set_function()

  • _get_state()

Descendentsmay additionally override the following methods, ifapplicable:

close()[source]

Cleans up the resources allocated to the pin. After this method iscalled, thisPin instance may no longer be used to query orcontrol the pin’s state.

input_with_pull(pull)[source]

Sets the pin’s function to “input” and specifies an initial pull-upfor the pin. By default this is equivalent to performing:

pin.function='input'pin.pull=pull

However, descendents may override this order to provide the smallestpossible delay between configuring the pin for input and pulling thepin up/down (which can be important for avoiding “blips” in someconfigurations).

output_with_state(state)[source]

Sets the pin’s function to “output” and specifies an initial statefor the pin. By default this is equivalent to performing:

pin.function='output'pin.state=state

However, descendents may override this in order to provide the smallestpossible delay between configuring the pin for output and specifying aninitial value (which can be important for avoiding “blips” inactive-low configurations).

propertybounce

The amount of bounce detection (elimination) currently in use by edgedetection, measured in seconds. If bounce detection is not currently inuse, this isNone.

For example, ifedges is currently “rising”,bounce iscurrently 5/1000 (5ms), then the waveform below will only firewhen_changed on two occasions despite there being three risingedges:

TIME 0...1...2...3...4...5...6...7...8...9...10..11..12 msbounce elimination   |===================| |==============HIGH - - - - >       ,--. ,--------------. ,--.                     |  | |              | |  |                     |  | |              | |  |LOW  ----------------'  `-'              `-'  `-----------                     :                     :                     :                     :               when_changed          when_changed                   fires                 fires

If the pin does not support edge detection, attempts to set thisproperty will raisePinEdgeDetectUnsupported. If the pinsupports edge detection, the class must implement bounce detection,even if only in software.

propertyedges

The edge that will trigger execution of the function or bound methodassigned towhen_changed. This can be one of the strings“both” (the default), “rising”, “falling”, or “none”:

HIGH - - - - >           ,--------------.                         |              |                         |              |LOW  --------------------'              `--------------                         :              :                         :              :Fires when_changed     "both"         "both"when edges is ...     "rising"       "falling"

If the pin does not support edge detection, attempts to set thisproperty will raisePinEdgeDetectUnsupported.

propertyfrequency

The frequency (in Hz) for the pin’s PWM implementation, orNoneif PWM is not currently in use. This value always defaults toNone and may be changed with certain pin types to activate ordeactivate PWM.

If the pin does not support PWM,PinPWMUnsupported will beraised when attempting to set this to a value other thanNone.

propertyfunction

The function of the pin. This property is a string indicating thecurrent function or purpose of the pin. Typically this is the string“input” or “output”. However, in some circumstances it can be otherstrings indicating non-GPIO related functionality.

With certain pin types (e.g. GPIO pins), this attribute can be changedto configure the function of a pin. If an invalid function isspecified, for this attribute,PinInvalidFunction will beraised.

propertyinfo

Returns thePinInfo associated with the pin. This can be usedto determine physical properties of the pin, including its location onthe header, fixed pulls, and the various specs that can be used toidentify it.

propertypull

The pull-up state of the pin represented as a string. This is typicallyone of the strings “up”, “down”, or “floating” but additional valuesmay be supported by the underlying hardware.

If the pin does not support changing pull-up state (for example becauseof a fixed pull-up resistor), attempts to set this property will raisePinFixedPull. If the specified value is not supported by theunderlying hardware,PinInvalidPull is raised.

propertystate

The state of the pin. This is 0 for low, and 1 for high. As a low levelview of the pin, no swapping is performed in the case of pull ups (seepull for more information):

HIGH - - - - >       ,----------------------                     |                     |LOW  ----------------'

Descendents which implement analog, or analog-like capabilities canreturn values between 0 and 1. For example, pins implementing PWM(wherefrequency is notNone) return a value between0.0 and 1.0 representing the current PWM duty cycle.

If a pin is currently configured for input, and an attempt is made toset this attribute,PinSetInput will be raised. If an invalidvalue is specified for this attribute,PinInvalidState will beraised.

propertywhen_changed

A function or bound method to be called when the pin’s state changes(more specifically when the edge specified byedges is detectedon the pin). The function or bound method must accept two parameters:the first will report the ticks (fromFactory.ticks()) whenthe pin’s state changed, and the second will report the pin’s currentstate.

Warning

Depending on hardware support, the state isnot guaranteed to beaccurate. For instance, many GPIO implementations will providean interrupt indicating when a pin’s state changed but not what itchanged to. In this case the pin driver simply reads the pin’scurrent state to supply this parameter, but the pin’s state mayhave changedsince the interrupt. Exercise appropriate cautionwhen relying upon this parameter.

If the pin does not support edge detection, attempts to set thisproperty will raisePinEdgeDetectUnsupported.

classgpiozero.SPI(*args,**kwargs)[source]

Abstract interface forSerial Peripheral Interface (SPI)implementations. Descendentsmust override the following methods:

Descendentsmay override the following methods, if applicable:

  • read()

  • write()

  • _set_clock_mode()

  • _get_lsb_first()

  • _set_lsb_first()

  • _get_select_high()

  • _set_select_high()

  • _get_bits_per_word()

  • _set_bits_per_word()

read(n)[source]

Readn words of data from the SPI interface, returning them as asequence of unsigned ints, each no larger than the configuredbits_per_word of the interface.

This method is typically used with read-only devices that featurehalf-duplex communication. Seetransfer() for full duplexcommunication.

transfer(data)[source]

Writedata to the SPI interface.data must be a sequence ofunsigned integer words each of which will fit within the configuredbits_per_word of the interface. The method returns the sequenceof words read from the interface while writing occurred (full duplexcommunication).

The length of the sequence returned dictates the number of words ofdata written to the interface. Each word in the returned sequencewill be an unsigned integer no larger than the configuredbits_per_word of the interface.

write(data)[source]

Writedata to the SPI interface.data must be a sequence ofunsigned integer words each of which will fit within the configuredbits_per_word of the interface. The method returns the numberof words written to the interface (which may be less than or equal tothe length ofdata).

This method is typically used with write-only devices that featurehalf-duplex communication. Seetransfer() for full duplexcommunication.

propertybits_per_word

Controls the number of bits that make up a word, and thus where theword boundaries appear in the data stream, and the maximum value of aword. Defaults to 8 meaning that words are effectively bytes.

Several implementations do not support non-byte-sized words.

propertyclock_mode

Presents a value representing theclock_polarity andclock_phase attributes combined according to the followingtable:

mode

polarity (CPOL)

phase (CPHA)

0

False

False

1

False

True

2

True

False

3

True

True

Adjusting this value adjusts both theclock_polarity andclock_phase attributes simultaneously.

propertyclock_phase

The phase of the SPI clock pin. If this isFalse (the default),data will be read from the MISO pin when the clock pin activates.Setting this toTrue will cause data to be read from the MISOpin when the clock pin deactivates. On many data sheets this isdocumented as the CPHA value. Whether the clock edge is rising orfalling when the clock is considered activated is controlled by theclock_polarity attribute (corresponding to CPOL).

The following diagram indicates when data is read whenclock_polarity isFalse, andclock_phase isFalse (the default), equivalent to CPHA 0:

    ,---.   ,---.   ,---.   ,---.   ,---.   ,---.   ,---.CLK |   |   |   |   |   |   |   |   |   |   |   |   |   |    |   |   |   |   |   |   |   |   |   |   |   |   |   |----'   `---'   `---'   `---'   `---'   `---'   `---'   `-------    :       :       :       :       :       :       :MISO---.   ,---.   ,---.   ,---.   ,---.   ,---.   ,---.  /     \ /     \ /     \ /     \ /     \ /     \ /     \-{  Bit  X  Bit  X  Bit  X  Bit  X  Bit  X  Bit  X  Bit  }------  \     / \     / \     / \     / \     / \     / \     /   `---'   `---'   `---'   `---'   `---'   `---'   `---'

The following diagram indicates when data is read whenclock_polarity isFalse, butclock_phase isTrue, equivalent to CPHA 1:

    ,---.   ,---.   ,---.   ,---.   ,---.   ,---.   ,---.CLK |   |   |   |   |   |   |   |   |   |   |   |   |   |    |   |   |   |   |   |   |   |   |   |   |   |   |   |----'   `---'   `---'   `---'   `---'   `---'   `---'   `-------        :       :       :       :       :       :       :MISO   ,---.   ,---.   ,---.   ,---.   ,---.   ,---.   ,---.      /     \ /     \ /     \ /     \ /     \ /     \ /     \-----{  Bit  X  Bit  X  Bit  X  Bit  X  Bit  X  Bit  X  Bit  }--      \     / \     / \     / \     / \     / \     / \     /       `---'   `---'   `---'   `---'   `---'   `---'   `---'
propertyclock_polarity

The polarity of the SPI clock pin. If this isFalse (thedefault), the clock pin will idle low, and pulse high. Setting this toTrue will cause the clock pin to idle high, and pulse low. Onmany data sheets this is documented as the CPOL value.

The following diagram illustrates the waveform whenclock_polarity isFalse (the default), equivalent toCPOL 0:

       on      on      on      on      on      on      on      ,---.   ,---.   ,---.   ,---.   ,---.   ,---.   ,---.CLK   |   |   |   |   |   |   |   |   |   |   |   |   |   |      |   |   |   |   |   |   |   |   |   |   |   |   |   |------'   `---'   `---'   `---'   `---'   `---'   `---'   `------idle       off     off     off     off     off     off       idle

The following diagram illustrates the waveform whenclock_polarity isTrue, equivalent to CPOL 1:

idle       off     off     off     off     off     off       idle------.   ,---.   ,---.   ,---.   ,---.   ,---.   ,---.   ,------      |   |   |   |   |   |   |   |   |   |   |   |   |   |CLK   |   |   |   |   |   |   |   |   |   |   |   |   |   |      `---'   `---'   `---'   `---'   `---'   `---'   `---'       on      on      on      on      on      on      on
propertylsb_first

Controls whether words are read and written LSB in (Least SignificantBit first) order. The default isFalse indicating that wordsare read and written in MSB (Most Significant Bit first) order.Effectively, this controls theBit endianness of the connection.

The following diagram shows the a word containing the number 5 (binary0101) transmitted on MISO withbits_per_word set to 4, andclock_mode set to 0, whenlsb_first isFalse(the default):

    ,---.   ,---.   ,---.   ,---.CLK |   |   |   |   |   |   |   |    |   |   |   |   |   |   |   |----'   `---'   `---'   `---'   `-----    :     ,-------. :     ,-------.MISO:     | :     | :     | :     |    :     | :     | :     | :     |----------' :     `-------' :     `----    :       :       :       :   MSB                     LSB

And now withlsb_first set toTrue (and all otherparameters the same):

    ,---.   ,---.   ,---.   ,---.CLK |   |   |   |   |   |   |   |    |   |   |   |   |   |   |   |----'   `---'   `---'   `---'   `-----  ,-------. :     ,-------. :MISO:     | :     | :     | :  | :     | :     | :     | :--' :     `-------' :     `-----------    :       :       :       :   LSB                     MSB
propertyrate

Controls the speed of the SPI interface in Hz (or baud).

Note that most software SPI implementations ignore this property, andwill raiseSPIFixedRate if an attempt is made to set it, as theyhave no rate control (they simply bit-bang as fast as possible becausetypically this isn’t very fast anyway, and introducing measures tolimit the rate would simply slow them down to the point of beinguseless).

propertyselect_high

IfFalse (the default), the chip select line is consideredactive when it is pulled low. When set toTrue, the chip selectline is considered active when it is driven high.

The following diagram shows the waveform of the chip select line, andthe clock whenclock_polarity isFalse, andselect_high isFalse (the default):

---.                                                     ,------__ |                                                     |CS |      chip is selected, and will react to clock      |  idle   `-----------------------------------------------------'    ,---.   ,---.   ,---.   ,---.   ,---.   ,---.   ,---.CLK |   |   |   |   |   |   |   |   |   |   |   |   |   |    |   |   |   |   |   |   |   |   |   |   |   |   |   |----'   `---'   `---'   `---'   `---'   `---'   `---'   `-------

And whenselect_high isTrue:

   ,-----------------------------------------------------.CS |      chip is selected, and will react to clock      |  idle   |                                                     |---'                                                     `------    ,---.   ,---.   ,---.   ,---.   ,---.   ,---.   ,---.CLK |   |   |   |   |   |   |   |   |   |   |   |   |   |    |   |   |   |   |   |   |   |   |   |   |   |   |   |----'   `---'   `---'   `---'   `---'   `---'   `---'   `-------
classgpiozero.pins.pi.PiFactory[source]

ExtendsFactory. Abstract base class representinghardware attached to a Raspberry Pi. This forms the base ofLocalPiFactory.

close()[source]

Closes the pin factory. This is expected to clean up all resourcesmanipulated by the factory. It it typically called at scripttermination.

pin(name)[source]

Creates an instance of aPin descendent representing thespecified pin.

Warning

Descendents must ensure that pin instances representing the samehardware are identical; i.e. two separate invocations ofpin() for the same pin specification must return the sameobject.

spi(**spi_args)[source]

Returns an SPI interface, for the specified SPIport anddevice, orfor the specified pins (clock_pin,mosi_pin,miso_pin, andselect_pin). Only one of the schemes can be used; attempting to mixport anddevice with pin numbers will raiseSPIBadArgs.

If the pins specified match the hardware SPI pins (clock on GPIO11,MOSI on GPIO10, MISO on GPIO9, and chip select on GPIO8 or GPIO7), andthe spidev module can be imported, a hardware based interface (usingspidev) will be returned. Otherwise, a software based interface will bereturned which will use simple bit-banging to communicate.

Both interfaces have the same API, support clock polarity and phaseattributes, and can handle half and full duplex communications, but thehardware interface is significantly faster (though for many simplerdevices this doesn’t matter).

classgpiozero.pins.pi.PiPin(factory,info)[source]

ExtendsPin. Abstract base class representing amulti-function GPIO pin attached to a Raspberry Pi. Descendentsmustoverride the following methods:

  • _get_function()

  • _set_function()

  • _get_state()

  • _call_when_changed()

  • _enable_event_detect()

  • _disable_event_detect()

Descendentsmay additionally override the following methods, ifapplicable:

  • close()

  • output_with_state()

  • input_with_pull()

  • _set_state()

  • _get_frequency()

  • _set_frequency()

  • _get_pull()

  • _set_pull()

  • _get_bounce()

  • _set_bounce()

  • _get_edges()

  • _set_edges()

propertyinfo

Returns thePinInfo associated with the pin. This can be usedto determine physical properties of the pin, including its location onthe header, fixed pulls, and the various specs that can be used toidentify it.

classgpiozero.pins.local.LocalPiFactory[source]

ExtendsPiFactory. Abstract base classrepresenting pins attached locally to a Pi. This forms the base class forlocal-only pin interfaces (RPiGPIOPin,LGPIOPin, andNativePin).

staticticks()[source]

Return the current ticks, according to the factory. The reference pointis undefined and thus the result of this method is only meaningful whencompared to another value returned by this method.

The format of the time is also arbitrary, as is whether the time wrapsafter a certain duration. Ticks should only be compared using theticks_diff() method.

staticticks_diff(later,earlier)[source]

Return the time in seconds between twoticks() results. Thearguments are specified in the same order as they would be in theformulalater -earlier but the result is guaranteed to be inseconds, and to be positive even if the ticks “wrapped” between callstoticks().

classgpiozero.pins.local.LocalPiPin(factory,info)[source]

ExtendsPiPin. Abstract base class representinga multi-function GPIO pin attached to the local Raspberry Pi.

24.4.RPi.GPIO

classgpiozero.pins.rpigpio.RPiGPIOFactory[source]

ExtendsLocalPiFactory. Uses theRPi.GPIOlibrary to interface to the Pi’s GPIO pins. This is the default pinimplementation if the RPi.GPIO library is installed. Supports all featuresincluding PWM (via software).

Because this is the default pin implementation you can use it simply byspecifying an integer number for the pin in most operations, e.g.:

fromgpiozeroimportLEDled=LED(12)

However, you can also construct RPi.GPIO pins manually if you wish:

fromgpiozero.pins.rpigpioimportRPiGPIOFactoryfromgpiozeroimportLEDfactory=RPiGPIOFactory()led=LED(12,pin_factory=factory)
classgpiozero.pins.rpigpio.RPiGPIOPin(factory,info)[source]

ExtendsLocalPiPin. Pin implementation fortheRPi.GPIO library. SeeRPiGPIOFactory for more information.

24.5.lgpio

classgpiozero.pins.lgpio.LGPIOFactory(chip=None)[source]

ExtendsLocalPiFactory. Uses thelgpiolibrary to interface to the local computer’s GPIO pins. The lgpio librarysimply talks to Linux gpiochip devices; it is not specific to the RaspberryPi although this class is currently constructed under the assumption thatit is running on a Raspberry Pi.

You can construct lgpio pins manually like so:

fromgpiozero.pins.lgpioimportLGPIOFactoryfromgpiozeroimportLEDfactory=LGPIOFactory(chip=0)led=LED(12,pin_factory=factory)

Thechip parameter to the factory constructor specifies which gpiochipdevice to attempt to open. It defaults to 0 and thus doesn’t normally needto be specified (the example above only includes it for completeness).

The lgpio library relies on access to the/dev/gpiochip* devices.If you run into issues, please check that your user has read/write accessto the specific gpiochip device you are attempting to open (0 by default).

classgpiozero.pins.lgpio.LGPIOPin(factory,info)[source]

ExtendsLocalPiPin. Pin implementation forthelgpio library. SeeLGPIOFactory for more information.

24.6.PiGPIO

classgpiozero.pins.pigpio.PiGPIOFactory(host=None,port=None)[source]

ExtendsPiFactory. Uses thepigpio library tointerface to the Pi’s GPIO pins. The pigpio library relies on a daemon(pigpiod) to be running as root to provide access to the GPIOpins, and communicates with this daemon over a network socket.

While this does mean only the daemon itself should control the pins, thearchitecture does have several advantages:

  • Pins can be remote controlled from another machine (the othermachine doesn’t even have to be a Raspberry Pi; it simply needs thepigpio client library installed on it)

  • The daemon supports hardware PWM via the DMA controller

  • Your script itself doesn’t require root privileges; it just needs tobe able to communicate with the daemon

You can construct pigpio pins manually like so:

fromgpiozero.pins.pigpioimportPiGPIOFactoryfromgpiozeroimportLEDfactory=PiGPIOFactory()led=LED(12,pin_factory=factory)

This is particularly useful for controlling pins on a remote machine. Toaccomplish this simply specify the host (and optionally port) whenconstructing the pin:

fromgpiozero.pins.pigpioimportPiGPIOFactoryfromgpiozeroimportLEDfactory=PiGPIOFactory(host='192.168.0.2')led=LED(12,pin_factory=factory)

Note

In some circumstances, especially when playing with PWM, it does appearto be possible to get the daemon into “unusual” states. We would bemost interested to hear any bug reports relating to this (it may be abug in our pin implementation). A workaround for now is simply torestart thepigpiod daemon.

classgpiozero.pins.pigpio.PiGPIOPin(factory,info)[source]

ExtendsPiPin. Pin implementation for thepigpio library. SeePiGPIOFactory for more information.

24.7.Native

classgpiozero.pins.native.NativeFactory[source]

ExtendsLocalPiFactory. Uses a built-in purePython implementation to interface to the Pi’s GPIO pins. This is thedefault pin implementation if no third-party libraries are discovered.

Warning

This implementation doesnot currently support PWM. Attempting touse any class which requests PWM will raise an exception.

You can construct native pin instances manually like so:

fromgpiozero.pins.nativeimportNativeFactoryfromgpiozeroimportLEDfactory=NativeFactory()led=LED(12,pin_factory=factory)
classgpiozero.pins.native.NativePin(factory,info)[source]

ExtendsLocalPiPin. Native pinimplementation. SeeNativeFactory for more information.

classgpiozero.pins.native.Native2835Pin(factory,info)[source]

ExtendsNativePin for Pi hardware prior to the Pi 4 (Pi 0, 1, 2,3, and 3+).

classgpiozero.pins.native.Native2711Pin(factory,info)[source]

ExtendsNativePin for Pi 4 hardware (Pi 4, CM4, Pi 400 at the timeof writing).

24.8.Mock

classgpiozero.pins.mock.MockFactory(revision=None,pin_class=None)[source]

Factory for generating mock pins.

Therevision parameter specifies what revision of Pi the mock factorypretends to be (this affects the result of theFactory.board_infoattribute as well as where pull-ups are assumed to be).

Thepin_class attribute specifies which mock pin class will be generatedby thepin() method by default. This can be changed afterconstruction by modifying thepin_class attribute.

pin_class

This attribute stores theMockPin class (or descendant) thatwill be used when constructing pins with thepin() method (ifnopin_class parameter is used to override it). It defaults onconstruction to the value of thepin_class parameter in theconstructor, orMockPin if that is unspecified.

pin(name,pin_class=None,**kwargs)[source]

The pin method forMockFactory additionally takes apin_class attribute which can be used to override the class’pin_class attribute. Any additional keyword arguments will bepassed along to the pin constructor (useful with things likeMockConnectedPin which expect to be constructed with anotherpin).

reset()[source]

Clears the pins and reservations sets. This is primarily useful intest suites to ensure the pin factory is back in a “clean” state beforethe next set of tests are run.

staticticks()[source]

Return the current ticks, according to the factory. The reference pointis undefined and thus the result of this method is only meaningful whencompared to another value returned by this method.

The format of the time is also arbitrary, as is whether the time wrapsafter a certain duration. Ticks should only be compared using theticks_diff() method.

staticticks_diff(later,earlier)[source]

Return the time in seconds between twoticks() results. Thearguments are specified in the same order as they would be in theformulalater -earlier but the result is guaranteed to be inseconds, and to be positive even if the ticks “wrapped” between callstoticks().

classgpiozero.pins.mock.MockPin(factory,info)[source]

A mock pin used primarily for testing. This class doesnot support PWM.

classgpiozero.pins.mock.MockPWMPin(factory,info)[source]

This derivative ofMockPin adds PWM support.

classgpiozero.pins.mock.MockConnectedPin(factory,info,input_pin=None)[source]

This derivative ofMockPin emulates a pin connected to anothermock pin. This is used in the “real pins” portion of the test suite tocheck that one pin can influence another.

classgpiozero.pins.mock.MockChargingPin(factory,info,charge_time=0.01)[source]

This derivative ofMockPin emulates a pin which, when set toinput, waits a predetermined length of time and then drives itself high(as if attached to, e.g. a typical circuit using an LDR and a capacitorto time the charging rate).

classgpiozero.pins.mock.MockTriggerPin(factory,info,echo_pin=None,echo_time=0.04)[source]

This derivative ofMockPin is intended to be used with anotherMockPin to emulate a distance sensor. Setecho_pin to thecorresponding pin instance. When this pin is driven high it will triggerthe echo pin to drive high for the echo time.

classgpiozero.pins.mock.MockSPIDevice(clock_pin,mosi_pin=None,miso_pin=None,select_pin=None,*,clock_polarity=False,clock_phase=False,lsb_first=False,bits_per_word=8,select_high=False,pin_factory=None)[source]

This class is used to testSPIDevice implementations. It can beused to mock up the slave side of simple SPI devices, e.g. the MCP3xxxseries of ADCs.

Descendants should override theon_start() and/oron_bit()methods to respond to SPI interface events. Therx_word() andtx_word() methods can be used facilitate communications within thesemethods. Such descendents can then be passed as thespi_class parameterof theMockFactory constructor to have instances attached to anySPI interface requested by anSPIDevice.