#!/usr/bin/env python3.5 # Copyright 2017 Digital # # This file is part of DigiLib. # # DigiLib is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # DigiLib is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with DigiLib. If not, see . lgpio = logging.getLogger(__name__) try: import RPi.gpio as _gpio OUT = _gpio.OUT IN = _gpio.IN BCM = _gpio.BCM except ImportError: lgpio.debug("failed to import RPi.gpio") _gpio = None OUT = "out" IN = "in" BCM = "bcm" _pins_for_cleanup = set() def cleanup(self,*args): """ Calls _gpio.cleanup for every pin used. The module automatically registers this function to the `atexit` handler, so the user doesn't need to call it. """ lgpio.debug("cleanup! ({})".format(args)) if _gpio: # _gpio.cleanup wants a list or tuple, but _pins_for_cleanup is # a set. we have to convert it first. _gpio.cleanup(list(_pins_for_cleanup)) def write(self,pins,state): """ sets pin `pin` to `state`. Parameters ---------- pins: list or int the pins which will be written to. state: int or float what will be written to the pins. float is only for analog pins. """ lgpio.debug("setting pin(s) {} to value {}" .format(pins,state)) if type(pins) is int: pins = [pins] _pins_for_cleanup.update(pins) if _gpio: _gpio.output(pins,state) def read(self,pins): """ sets pin `pin` to `state`. Parameters ---------- pins: list or int the pins which will be read from. Returns ------- value: list the values read from the gpio pins in the same order as `pins`. if RPi.GPIO could not be imported, -1 is used instead of the pins actual value. """ values = [] for p in pins: if _gpio: values.append(_gpio.input(p)) else: values.append(-1) lgpio.debug("reading pins {}: {}".format( pins,values)) return values def configure(): """ Sets the gpio numbering mode to broadcom. """ lgpio.debug("setting pin numbering to broadcom") atexit.register(cleanup) if _gpio: _gpio.setmode(_gpio.BCM) def setup(self,pins,value): """ wrapper for ``gpio.setup()``. used to configure pins as input or output Parameters ---------- pins: list the pins which will be configured. value: `IN` or `OUT` wether the pins will be configured as input or output. """ lgpio.debug("setting pin(s) {} to {}".format(pins,value)) if _gpio: _gpio.setup(pins,value) #