GithubHelp home page GithubHelp logo

python-sysfs-gpio's Introduction

Linux SysFS GPIO access via Python

This package offer Python classes to work with GPIO on Linux.

System Requirements

As this package relies on modern techniques provided by Linux kernel, so your kernel version should support at least EPoll and SysFS interfaces.

Package Requirements

This package is based on Twisted main loop. To build the package you will also need setuptools.

How to use it

  1. Download this repository
    git clone https://github.com/derekstavis/python-sysfs-gpio.git
  1. Inside it, issue:
    sudo python setup.py install
  1. On your code:
    # Import Twisted mainloop
    
    from twisted.internet import reactor
    
    # Import this package objects
    
    from sysfs.gpio import Controller, OUTPUT, INPUT, RISING
    
    # Refer to your chip GPIO numbers and set them this way
    
    Controller.available_pins = [1, 2, 3, 4]
    
    # Allocate a pin as Output signal
    
    pin = Controller.alloc_pin(1, OUTPUT)
    pin.set()   # Sets pin to high logic level
    pin.reset() # Sets pin to low logic level
    pin.read()  # Reads pin logic level
    
    # Allocate a pin as simple Input signal
    
    pin = Controller.alloc_pin(1, INPUT)
    pin.read()  # Reads pin logic level
    
    # Allocate a pin as level triggered Input signal
    
    def pin_changed(number, state):
        print("Pin '%d' changed to %d state" % (number, state))
    
    pin = Controller.alloc_pin(1, INPUT, pin_changed, RISING)
    pin.read()  # Reads pin logic level
  1. Don't forget to start reactor loop!
    reactor.run()

Contributing

If you think that there's work that can be done to make this module better (and that's the only certainty), fork this repo, make some changes and create a pull request. I will be glad to accept it! :)

python-sysfs-gpio's People

Contributors

derekstavis avatar gdeback avatar nocko avatar zpfvo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-sysfs-gpio's Issues

Maybe remove Twisted dependency?

Hi,
this not a real issue rather than a question of design. I really like the interface you created for the gpio interface, but i think it is unnecessary to have the Twisted dependency.

Some people are are maybe using threads in a different way, for others its ok to wait for a pin change blocking.
I just forked and removed everything related to twisted and now call
events = Controller._poll_queue.poll(EPOLL_TIMEOUT)
Controller._poll_queue_event(events)
in my main loop which works nice. Everything is handled in a pin callback function.
At least it would be nice to have a public method to do a blocking read.

Either way,
nice module! Thanks for your work!

Question: Example Usage with While Loop

I'm attempting to use this excellent library in a project where I'm attempting to turn on an LED when an interrupt is triggered, but I have a feeling I'm missing something basic. This is the first time I've heard of Twisted Reactor, so I'm wondering if that has something to do with my misunderstanding of what I thought was relatively straightforward.

I have a while loop which reads a light sensor every second. The light sensor (I2C device) is programmed to trigger an interrupt when the value reads below a certain threshold. I have the interrupt pin of the sensor connected to GPIO 65 of my SBC. I then have an LED hooked up to GPIO 64 of my SBC. Something like this:

import time
from twisted.internet import reactor
from sysfs.gpio import Controller, OUTPUT, INPUT, RISING

Controller.available_pins = [64, 65]
led_en = Controller.alloc_pin(64, OUTPUT)

def pin_changed(pin, state):
    print("Pin changed to %d state" % state)
    if state:
        led_en.set()   # Sets pin to high logic level
    else:
        led_en.reset()

intt = Controller.alloc_pin(65, INPUT, pin_changed, RISING)

reactor.run()

while True:

    # Enable sensor light interrupts
    # Read and store sensor light value via I2C
    # Print sensor light value to console for debugging
    print("Testing!")
    sleep(.5)

Anyways, so I'm expecting my while loop to execute, but it never does. Instead, I get "Pin changed to 0 state", from the pin_changed() callback and then nothing!

$ sudo python test-gpio-interrupt.py 
SysfsGPIO: alloc_pin(64, out, None, None, 0)
SysfsGPIO: alloc_pin(65, in, <function pin_changed at 0x76468830>, rising, 0)
Pin changed to 0 state

I then have to Ctrl + C to end the process.

I would've expected the code in the while loop to execute. I must be having a lapse of common sense and I'm hoping you can help.

Cannot stop reactor.run() gracefully

Test code:

#!/usr/bin/python
import sys
import signal
from twisted.internet import reactor
from sysfs.gpio import Controller, OUTPUT, INPUT, RISING

port = 6

''' This works '''
def signal_handler(signal, frame):
	Controller.dealloc_pin(port)
 	print('You pressed Ctrl+C!')
 	reactor.stop()
 	
 ''' This will cause an error '''
def pin_changed(number, state):
	Controller.dealloc_pin(port)
	print("Pin '%d' changed to %d state" % (number, state))
	reactor.stop()
 
signal.signal(signal.SIGINT, signal_handler)
 
Controller.available_pins = [port]
pin = Controller.alloc_pin(port, INPUT, pin_changed, RISING)
pin.read()  # Reads pin logic level

reactor.run()

Result:

root@orangepipc2:~# python /tmp/test_sysfs-gpio.py
SysfsGPIO: alloc_pin(6, in, <function pin_changed at 0xffffba0b82a8>, rising, 0)
^CSysfsGPIO: dealloc_pin(6)
You pressed Ctrl+C!
root@orangepipc2:~# python /tmp/test_sysfs-gpio.py
SysfsGPIO: alloc_pin(6, in, <function pin_changed at 0xffffab9652a8>, rising, 0)
SysfsGPIO: dealloc_pin(6)
Pin '6' changed to 1 state
Unhandled Error
Traceback (most recent call last):
  File "/tmp/test_sysfs-gpio.py", line 27, in <module>
    reactor.run()
  File "/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py", line 1243, in run
    self.mainLoop()
  File "/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py", line 1252, in mainLoop
    self.runUntilCurrent()
--- <exception caught here> ---
  File "/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py", line 851, in runUntilCurrent
    f(*a, **kw)
  File "build/bdist.linux-aarch64/egg/sysfs/gpio.py", line 400, in _poll_queue_event

exceptions.RuntimeError: dictionary changed size during iteration

root@orangepipc2:~#

Did I miss anything ?

Input changed callback has 2 arguments(gpio_num,state) but in examples there is only state so when its fired "pin_changed() takes exactly 1 argument (2 given)" error

In here there is gpio num and gpio state parameters
in gpio.py line 190

def changed(self, state):
if callable(self._callback):
self._callback(self.number, state)

but in examples:
def pin_changed(state):
print("Pin changed to %d state" % state)

should be:
def pin_changed(number,state):
print("Pin %d changed to %d state")%(number,state)

Enhancement: Debounce input pins

Hi,
i'm using this library in one of our products. I just came back from an EMC test and we sometimes had a problem with a toggling pin when our board was exposed to electromagnetic radiation.

We could solve the problem easily by checking if the state of the pin stayed the same for a short period of time.
I implemented this debounce logic in the callback function but i thought if this was a nice feature to be embedded in the library itself.

If you think this might be a nice idea, i will prepare a pull request to add this functionality as soon as i have some time (sry very busy atm). I think it would be nice if one activate debounce separately for the pins and also set different deboucne times.

Greetings!

Python 3.4 fix for Controller __new__

Was getting this error with Python 3:
...sysfs/gpio.py", line 239, in new
instance = super(controller, cls).new(cls, args, kw)
TypeError: object() takes no parameters

Modified to:
instance = super(controller, cls).new(cls)
This works with Python 3.4

Missing active_low attribute

Hi

I am currently working with a GPIO chip controller (the chip is of type 'ICH', sorry I don't know much about the hardware) - one of the attributes of pins on this chip is active_low, which determines whether the logic of activating the pin is inverted, i.e. if active_low = 0 then basically for pin values 1 = high and 0 = low, but if active_low = 1 then this is inverted to become 1 = low and 0 = high.

I cannot see this being indicated in the Pin class constructor or the Controller class you have written. I would like to add this via a PR. Is that OK?

SM

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.