RaspberryPi Relais + RF-ID-Card Code

Python auf Einplatinencomputer wie Raspberry Pi, Banana Pi / Python für Micro-Controller
Antworten
Anton91
User
Beiträge: 9
Registriert: Dienstag 18. August 2020, 11:04

Guten Tag zusammen,

Ich habe mein Relais und die RFid Modul angeschlossen und konnte beides ansteuern mit den einzelnen .py.

Jetzt versuche ich eine neue Datei zu erstellen Turoffner.py. Ich will, nach dem er die ID erfolgreich gelesen hat, das dass Relais klickt.

Relais code:

Code: Alles auswählen

GPIO.setmode(GPIO.BCM) # GPIO Nummern statt Board Nummern
RELAIS_1_GPIO = 2
GPIO.setup(RELAIS_1_GPIO, GPIO.OUT) # GPIO Modus zuweisen
GPIO.output(RELAIS_1_GPIO, GPIO.LOW) # aus ground
#GPIO.output(RELAIS_1_GPIO, GPIO.HIGH) # an
time.sleep(1)
Turoffnercode(ich weiß nicht wo ich die Relaissteuerung reinschreiben soll) nachdem er die ID erkannt hat soll das relais klicken einmal.

Code: Alles auswählen

#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#    Copyright 2014,2018 Mario Gomez <mario.gomez@teubi.co>
#
#    This file is part of MFRC522-Python
#    MFRC522-Python is a simple Python implementation for
#    the MFRC522 NFC Card Reader for the Raspberry Pi.
#
#    MFRC522-Python is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    MFRC522-Python is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with MFRC522-Python.  If not, see <http://www.gnu.org/licenses/>.
#

import RPi.GPIO as GPIO
import MFRC522
import signal
import time
            
continue_reading = True

# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
    global continue_reading
    print "Ctrl+C captured, ending read."
    continue_reading = False
    GPIO.cleanup()

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# Welcome message
print "Welcome to the MFRC522 data read example"
print "Press Ctrl-C to stop."

# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:

    
    # Scan for cards    
    (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

    # If a card is found
    if status == MIFAREReader.MI_OK:
        print "Card detected"
    
    # Get the UID of the card
    (status,uid) = MIFAREReader.MFRC522_Anticoll()

    # If we have the UID, continue
    if status == MIFAREReader.MI_OK:
        
        # Print UID
        print "Card read UID: %s,%s,%s,%s" % (uid[0], uid[1], uid[2], uid[3])
    
        # This is the default key for authentication
        key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
        
        # Select the scanned tag
        MIFAREReader.MFRC522_SelectTag(uid)

        # Authenticate
        status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)
        
        
        # Check if authenticated
        if status == MIFAREReader.MI_OK:
            data = MIFAREReader.MFRC522_Read(8)
            print "data = "+str(data)
            text = "".join(chr(x) for x in data)
            # Zeilenumbruch ausgeben			
            print "\n"
            print ">>>>>>>>> Username = "+text
            print "\n"
            MIFAREReader.MFRC522_StopCrypto1()
            
           
        else:
            print "Authentication error"


Sirius3
User
Beiträge: 18265
Registriert: Sonntag 21. Oktober 2012, 17:20

Es ist müßig, immer wieder den selben Schrott von der Homepage zu reparieren.

Code: Alles auswählen

#!/usr/bin/env python3
from RPi import GPIO
import MFRC522
import time

# This is the default key for authentication
AUTHENTICATION_KEY = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
            
def handle_rfid(mifare_reader):
    # Scan for cards    
    (status, tag_type) = mifare_reader.MFRC522_Request(mifare_reader.PICC_REQIDL)
    if status != mifare_reader.MI_OK:
        return
    print("Card detected")
    # Get the UID of the card
    (status, uid) = mifare_reader.MFRC522_Anticoll()
    if status != mifare_reader.MI_OK:
        return
    print("Card read UID: %s,%s,%s,%s" % (uid[0], uid[1], uid[2], uid[3]))

    # Select the scanned tag
    mifare_reader.MFRC522_SelectTag(uid)

    # Authenticate
    status = mifare_reader.MFRC522_Auth(mifare_reader.PICC_AUTHENT1A, 8, AUTHENTICATION_KEY, uid)
        
    # Check if authenticated
    if status != mifare_reader.MI_OK:
        print("Authentication error")
        return
            
    data = mifare_reader.MFRC522_Read(8)
    print("data = %s" % data)
    mifare_reader.MFRC522_StopCrypto1()

def main():
    try:
        mifare_reader = MFRC522.MFRC522()
        while True:
            handle_rfid(mifare_reader):
    finally:
        GPIO.cleanup()

if __name__ == '__main__':
    main()
Wenn Du den Code mal durcharbeitest, sollte ziemlich klar sein, an welcher Stelle die Karte erfolgreich gelesen wurde.
Benutzeravatar
__blackjack__
User
Beiträge: 14030
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@Anton91: Python 2 bitte nicht mehr verwenden. Das hat keine Zukunft.

`time` wird importiert aber nirgends verwendet.

``as`` beim Importieren ist zum Umbenennen — `GPIO` wird aber gar nicht umbenannt.

Auf Modulebene sollte nur Code stehen der Konstanten, Funktionen, und Klassen definiert. Das Hauptprogramm steht üblicherweise in einer Funktion die `main()` heisst.

Das mit dem Signal-Handler für SIGINT ist unnötig kompliziert weil Python dieses Signal bereits behandelt und in eine Ausnahme umwandelt. Es ist sogar fehlerhaft, denn das `GPIO.cleanup()` darf nicht nur ausgeführt werden wenn der Benutzer Strg+C drückt, sondern muss *immer* am Programmende ausgeführt werden.

Namen werden in Python klein_mit_unterstrichen geschrieben. Ausnahmen sind Konstanten (KOMPLETT_GROSS) und Klassen (MixedCase).

Der Code in der Hauptschleife ist fehlerhaft. Wenn eine Karte erkannt wird, dann wird eine entsprechende Meldung ausgegeben. Danach folgt dann Code der mit der Karte kommuniziert, der aber nicht mehr von der Bedingung abhängt das eine Karte erkannt wurde. Da wird also auch versucht mit nicht korrekt erkannten Karten zu kommunizieren.

Sehr viele von den Kommentaren sind überflüssig weil sie nur das absolut offensichtliche beschreiben was da bereits im Code steht.

Was da mit den gelesenen Bytes von der Karte gemacht wird ist eine recht umständliche Art und Weise Bytes zu einer Zeichenkette der Kodierung ISO-8859-1 zu dekodieren.

Das ganze mal überarbeitet (ungetestet):

Code: Alles auswählen

#!/usr/bin/env python3
#
#    Copyright 2014,2018 Mario Gomez <mario.gomez@teubi.co>
#
#    This file is part of MFRC522-Python
#    MFRC522-Python is a simple Python implementation for
#    the MFRC522 NFC Card Reader for the Raspberry Pi.
#
#    MFRC522-Python is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    MFRC522-Python is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with MFRC522-Python.  If not, see <http://www.gnu.org/licenses/>.
#
import MFRC522
from RPi import GPIO


def main():
    try:
        print("Welcome to the MFRC522 data read example")
        print("Press Ctrl-C to stop.")
        rfid_reader = MFRC522.MFRC522()
        while True:
            status, _ = rfid_reader.MFRC522_Request(rfid_reader.PICC_REQIDL)
            if status == rfid_reader.MI_OK:
                print("Card detected")
                status, uid = rfid_reader.MFRC522_Anticoll()
                if status == rfid_reader.MI_OK:
                    print("Card UID:", ",".join(map(str, uid)))
                    rfid_reader.MFRC522_SelectTag(uid)
                    status = rfid_reader.MFRC522_Auth(
                        rfid_reader.PICC_AUTHENT1A,
                        8,
                        [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
                        uid,
                    )
                    if status == rfid_reader.MI_OK:
                        text = rfid_reader.MFRC522_Read(8).decode("iso-8859-1")
                        print(f"\n>>>>>>>>> Username = {text}\n")
                        rfid_reader.MFRC522_StopCrypto1()
                    else:
                        print("Authentication error")
    except KeyboardInterrupt:
        print("Ctrl+C captured, ending read.")
    finally:
        GPIO.cleanup()


if __name__ == "__main__":
    main()
„A life is like a garden. Perfect moments can be had, but not preserved, except in memory. LLAP” — Leonard Nimoy's last tweet.
Anton91
User
Beiträge: 9
Registriert: Dienstag 18. August 2020, 11:04

Code: Alles auswählen

#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#    Copyright 2014,2018 Mario Gomez <mario.gomez@teubi.co>
#
#    This file is part of MFRC522-Python
#    MFRC522-Python is a simple Python implementation for
#    the MFRC522 NFC Card Reader for the Raspberry Pi.
#
#    MFRC522-Python is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    MFRC522-Python is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with MFRC522-Python.  If not, see <http://www.gnu.org/licenses/>.
#

import RPi.GPIO as GPIO
import MFRC522
import signal
import time

GPIO.setmode(GPIO.BOARD) # GPIO Nummern statt Board Nummern
MEIN_ERSTES_RELAIS_NUMMER = 3 #
GPIO.setup(MEIN_ERSTES_RELAIS_NUMMER, GPIO.OUT) # GPIO Modus zuweisen

continue_reading = True

 


# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
    global continue_reading
    print "Ctrl+C captured, ending read."
    continue_reading = False
    GPIO.cleanup()

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# Welcome message
print "Welcome to the MFRC522 data read example"
print "Press Ctrl-C to stop."

# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:
    
    # Scan for cards    
    (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

    # If a card is found
    if status == MIFAREReader.MI_OK:
        print "Card detected"
        GPIO.output(MEIN_ERSTES_RELAIS_NUMMER, GPIO.LOW) # aus ground
        #GPIO.output(RELAIS_1_GPIO, GPIO.HIGH) # an
        time.sleep(1)
        GPIO.output(MEIN_ERSTES_RELAIS_NUMMER, GPIO.HIGH) #
    # Get the UID of the card
    (status,uid) = MIFAREReader.MFRC522_Anticoll()
    

    # If we have the UID, continue
    if status == MIFAREReader.MI_OK:
       

        # Print UID
        print "Card read UID: %s,%s,%s,%s" % (uid[0], uid[1], uid[2], uid[3])
    
        # This is the default key for authentication
        key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
        
        # Select the scanned tag
        MIFAREReader.MFRC522_SelectTag(uid)

        # Authenticate
        status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)

        # Check if authenticated
        if status == MIFAREReader.MI_OK:
            data = MIFAREReader.MFRC522_Read(8)
            print "data = "+str(data)
            text = "".join(chr(x) for x in data)
            # Zeilenumbruch ausgeben			
            print "\n"
            print ">>>>>>>>> Username = "+text
            print "\n"
            MIFAREReader.MFRC522_StopCrypto1()
        else:
            
            print "Authentication error"
         
     
        
So funktioniert es danke !
Benutzeravatar
__blackjack__
User
Beiträge: 14030
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@Anton91: Das kommt sehr auf Deine Definition von ”funktioniert” an. Da die Datei Türöffner heisst, würde ich mal sagen Einbrecher werden sich freuen. 😉
„A life is like a garden. Perfect moments can be had, but not preserved, except in memory. LLAP” — Leonard Nimoy's last tweet.
Antworten