Using RFID reader and ultrasonic distance sensor at the same time

When I try to use the RFID RC522 reader at the same time as the ultrasonic distance sensor (HC-SR04), the Python script running the RFID code freezes. I can run them individually and both work fine but when I try to run them together using separate terminals and also using the “&” command (eg “python3 ultrasonic.py&”) they start OK but as soon as I try to read an RFID tag that RFID process freezes until I CTRL-C, while the ultrasonic distance sensor continues to report measurements?

You’ll likely have to post your code for somebody to see what’s what.

OK, here is the code (from the brilliant monkmakes.com) that reads from the RFID reader:
#!/usr/bin/env python

import RPi.GPIO as GPIO
import SimpleMFRC522
import os

reader = SimpleMFRC522.SimpleMFRC522()

print("Hold a tag near the reader")

try:
    while True:
        id, text = reader.read()
        print(id)
        print(text)
        print("done! Hold a tag near the reader")

finally:
    print("cleaning up")
    GPIO.cleanup()

Nice and easy, the code for the ultrasonic distance sensor (from freenove.com) follows:

#!/usr/bin/env python
########################################################################
# Filename    : UltrasonicRanging.py
# Description : Get distance from UltrasonicRanging.
# Author      : freenove
# modification: 2016/07/15
########################################################################
import RPi.GPIO as GPIO
import time

trigPin = 16
echoPin = 20
MAX_DISTANCE = 220          #define the maximum measured distance
timeOut = MAX_DISTANCE*60   #calculate timeout according to the maximum measured distance

def pulseIn(pin,level,timeOut): # function pulseIn: obtain pulse time of a pin
    t0 = time.time()
    while(GPIO.input(pin) != level):
        if((time.time() - t0) > timeOut*0.000001):
            return 0;
    t0 = time.time()
    while(GPIO.input(pin) == level):
        if((time.time() - t0) > timeOut*0.000001):
            return 0;
    pulseTime = (time.time() - t0)*1000000
    return pulseTime
    
def getSonar():     #get the measurement results of ultrasonic module,with unit: cm
    GPIO.output(trigPin,GPIO.HIGH)      #make trigPin send 10us high level 
    time.sleep(0.00001)     #10us
    GPIO.output(trigPin,GPIO.LOW)
    pingTime = pulseIn(echoPin,GPIO.HIGH,timeOut)   #read plus time of echoPin
    distance = pingTime * 340.0 / 2.0 / 10000.0     # the sound speed is 340m/s, and calculate distance
    return distance
    
def setup():
    print ("Program is starting...")
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(trigPin, GPIO.OUT)   #
    GPIO.setup(echoPin, GPIO.IN)    #

def loop():
    GPIO.setup(11,GPIO.IN)
    while(True):
        distance = getSonar()
        print ("The distance is : %.2f cm"%(distance))
        time.sleep(2)
        
if __name__ == '__main__':     #program start from here
    setup()
    try:
        loop()
    except KeyboardInterrupt:  #when 'Ctrl+C' is pressed, the program will exit
        GPIO.cleanup()         #release resource

Both work fine independently but when you run them together, the ultrasonic one carries on while the RFID code freezes?

I’m far from being an expert on this but I notice both files use GPIO and both have a GPIO.cleanup().
Actually, why do you have “import RPi.GPIO as GPIO” and “GPIO.cleanup()” in the RFID reader file? I don’t see any other reference to GPIO PINs being used in that file. I’d remark them out with a # and see what happens. Like I said though, I’m no expert where Python is concerned.

Oops, apologies for the looong delay in replying! Good spot about using GPIO in both scripts when it is only needed in one. Unfortunately this didn’t make anything better and I have since started looking at threads and events to see if this will help with having both running at the same time. Time for some more experimenting…

Do these two devices share any pins on the GPIO?

Hi, I don’t believe so. The RFID uses GPIO 16 and GPIO 20 (plus power and GND) while the ultrasonic uses GPIO 8,9,10,11,25 (plus power and GND)…

What ever the conflict is, isn’t jumping out at me. And I don’t have either device to play with. I will be getting an ultrasonic sensor at some point though. Wish I could be more help. One option may be to try and roll them both into one python file? It may not be easy, but it could also get you an error message to tip you off to what’s happening.