Search code examples
pythonraspberry-pisubprocessgpio

How to run Raspberry Pi GPIO input buttons asynchronously?


import RPi.GPIO as GPIO
import time
import os
import subprocess
GPIO.setmode(GPIO.BCM)

GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
        input_state=GPIO.input(18)
        input_state1=GPIO.input(17)
        if input_state==False:
                print('Scan Button Pressed')
                subprocess.call(['./ocr.sh'])
        if input_state1==False:
                print('Read Button Pressed')
                subprocess.call(['aplay','temp1.wav'])

If input 17 is sensed temp.wav will play, while the audio file is playing input 18 cannot be checked. How to check for such a thing in between of a running process?


Solution

  • I am using a service called pigpiod and rinnung this service on my raspberry pi. I have python library installed for pigpiod service (daemon).
    and my code to detect the button state is something like

    !/usr/bin/env python
    import pigpio
    import time
    import datetime
    
    if __name__ == "__main__":
        def cbf(gpio, level):
            if(pi.read(gpio)!=0):
                i = datetime.datetime.now()
                date = i.strftime("%Y-%m-%d %H:%M:%S")
                print "gpio "+str(gpio)+"button gpio gave 1"
    
                print date
            if(pi.read(gpio)==0):
                i = datetime.datetime.now()
                date = i.strftime("%Y-%m-%d %H:%M:%S")
                print "gpio "+str(gpio)+"button gpio gave 0"
    
                print date
        pi = pigpio.pi()
        pi.set_mode(23, pigpio.INPUT)
        while True:
            cbf(23, pigpio.EITHER_EDGE)
    

    Run the python script and press the button. You will get different value as 0 and 1.

    So basically I am using PIGPIO and Python to detect button press as well as circuit close or open on a specific GPIO of the raspberry PI.

    To start the pigpio daemon

    sudo pigpiod
    

    To stop the pigpio daemon

    sudo killall pigpiod
    

    github

    git clone https://github.com/joan2937/pigpio
    

    Python Library

    sudo apt-get update
    sudo apt-get install pigpio python-pigpio python3-pigpio
    

    NOTE: I am NOT using RPi.GPIO or GPIO service available on Raspberry. All I have used pigpio for my temperature sensor, RFID card readers etc.