vsergeev / python-periphery

A pure Python 2/3 library for peripheral I/O (GPIO, LED, PWM, SPI, I2C, MMIO, Serial) in Linux.
MIT License
519 stars 139 forks source link

Callback on interupt and adc #46

Closed nickehallgren closed 3 years ago

nickehallgren commented 3 years ago

Hi!

Maybe I'm missing something but I've been using libmraa (on 4.4 kernel) but since I now want to use 5.x I'm looking for a replacement. Your project looks nice but I have a few questions, in mraa I used a callback for an interrupt like this:

import mraa
import time

def callback(userdata):
    print ("interrupt triggered with userdata=", userdata)

pin = mraa.Gpio(23)
pin.dir(mraa.DIR_IN)
pin.isr(mraa.EDGE_BOTH, callback, None)

while(True):
    time.sleep(5)
    print("5s loop")
    # simply wait for interrupt

but if I understand correctly I now need to poll in the while loop, correct?

import sys, time
from periphery import GPIO

gpio_in = GPIO("/dev/gpiochip1", 24, "in", edge="both")

try:
  while True:
    if gpio_in.poll(0.1):
      print(gpio_in.read_event())
except KeyboardInterrupt:
  gpio_in.close()
  sys.exit(130)

I also need to read the ADC pin (Rock Pi S), is that something you might implement in the future?

Thanks for your great work!

vsergeev commented 3 years ago

Yeah, you can certainly poll it like that. If your program ends up using an event loop to service multiple inputs, you can use the GPIO's underlying file descriptor (gpio_in.fd) with one of the facilities in select, e.g. epoll() or poll(), or in an asyncio environment with loop.add_reader(). Just remember to consume the event with gpio_in.read_event() after the GPIO file descriptor fires.

ADC support would probably come from sysfs IIO, issue #19.

vsergeev commented 3 years ago

Closing this one for now. Let me know if you have any other questions. ADC support / sysfs IIO discussion can continue in #19.