samedi 25 avril 2020

Python if clause with two possibilities to fulfill (NFC or Button getting pressed)

So I need an if-statement where an NFC-Card is scanned or the button is pressed. Problem is when I tired it really simple with if read.checkNFC() == 1 or button.getButtonPressed() == 0 than it only works with the NFC and the button is completly ignored. After a bit of search I found this python will different threads end at the same time as the first one to finish tougth it would work well no the same problem but different now only the button works and the NFC works only sometimes but then the whole program is laggy for some reason.

The NFC Code

#!/usr/bin/env python

import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

reader = SimpleMFRC522()

def gettext():
    id, text = reader.read()
    return text

def checkNFC():
          righttext = "Alohomora"
          testtext = gettext()
          if testtext.strip() == righttext:
              return 1
          else:
              return 0

The Button Code

#!/usr/bin/env python

import RPi.GPIO as GPIO

buttonPin = 12

def setup():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def getButtonPressed():
    while GPIO.input(buttonPin)==GPIO.HIGH:
          continue
    else:
          return 0

I actually already have given up and reseted the code to the only NFC form so I don't have the one where I tried it with the queue but it has been something like that

#!/usr/bin/env python

import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

reader = SimpleMFRC522()

def gettext():
    id, text = reader.read()
    return text

def checkNFC(worker_queue, stop_event):
  while not stop_event.is_set():
          righttext = "Alohomora"
          testtext = gettext()
          if not stop_event.is_set():
              if testtext.strip() == righttext:
                  worker_queue.put(1)
              else:
                  worker_queue.put(0)
#!/usr/bin/env python

import RPi.GPIO as GPIO

buttonPin = 12

def setup():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def getButtonPressed(worker_queue, stop_event):
  while not stop_event.is_set():
      while GPIO.input(buttonPin)==GPIO.HIGH:
            continue
      else:
            if not stop_event.is_set():
                   worker_queue.put(2)
#!/usr/bin/env python

[...]

worker_queue = Queue.Queue()

stop_event = threading.Event()

threads = []
threads.append(threading.Thread(target=read.checkNFC, args=(worker_queue, stop_event)))
threads.append(threading.Thread(target=button.getButtonPressed, args=(worker_queue, stop_event)))

for thread in threads:
    thread.start()

first_finished = worker_queue.get()

stop_event.set()

if first_finished == 0:
   [...]
elif first_finished == 1:
   [...]
elif first_finished == 2:
   [...]

Should have been something like that

Aucun commentaire:

Enregistrer un commentaire