Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 4844

Beginners • Using threading.Event to control my GPIO Pins

$
0
0
Hi,

Can somebody please help me understand how to apply threading to my Raspberry Pi Project?

I am using Raspberry Pi 4 with the latest Raspberry Pi OS.

I have a button and an MFRC522 RFID reader connected to my Pi.

My goal is like this:

On the first click, I wanted to enable the RFID and have it scan RFID tags.

On the second click, I wanted to toggle or stop it from reading RFID tags.

Here is my code.

Code:

import threadingfrom gpiozero import Buttonfrom mfrc522 import SimpleMFRC522from signal import pauseimport RPi.GPIO as GPIOimport timeGPIO.setwarnings(False)button = Button(5, bounce_time=0.2)  reader = SimpleMFRC522()# Event object to control RFID readingrfid_reading_event = threading.Event()# Function to toggle RFID readingdef toggle_rfid_reading():    while True:        rfid_reading_event.wait()  # Wait for the event to be set        id, _ = reader.read()        print(f"RFID Tag ID: {id}")        time.sleep(2)# Start the RFID reading threadrfid_reading_thread = threading.Thread(target=toggle_rfid_reading)rfid_reading_thread.start()# Variable to track the RFID reading stateis_rfid_reading = False# Callback function for button pressdef button_pressed():    global is_rfid_reading    print("Button pressed")    if is_rfid_reading:        print("Clearing event")        rfid_reading_event.clear()  # Clear the event to stop RFID reading        is_rfid_reading = False    else:        print("Setting event")        rfid_reading_event.set()  # Set the event to start RFID reading        is_rfid_reading = Truepause()
However, the code is not working as I am expecting. On a second click, I still am able to scan one RFID before my

RFID scanner is disabled. Please see my logs below.

Code:

# On the first click of the buttonButton pressedSetting event# Scan several RFIDRFID Tag ID: 11616204003RFID Tag ID: 11616204003# Click the button againButton pressedClearing event# I still was able to scan an RFID but after this one, the RFID was not activated anymoreRFID Tag ID: 11616204003
I am confused but could somebody enlighten me on this as this is the first time I have used the threading on my Raspberry Pi Project?

PS. If this is not the appropriate forum, kindly move it please.

P.S. I posted this same question on the reddit page but was not able to receive any help so I am trying my luck here https://www.reddit.com/r/raspberry_pi/c ... gpio_pins/

Statistics: Posted by mark.estrada.jr — Fri Apr 05, 2024 1:34 am



Viewing all articles
Browse latest Browse all 4844

Trending Articles