0

I have two simple scripts, which work individually. One simply lights an LED, the other reads RFID. Now I want to put them together, but seem to fail.

Once this runs, I can't read RFID anymore until I restart my Raspberry. Both functions work as intended, if I comment out the respectively other code (LED and RFID).

#!/usr/bin/env python

import time
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

# RFID setup
reader = SimpleMFRC522() #GPIO.setmode(GPIO.BOARD)

# LED setup
rl=37
gl=35
bl=33
freq=100
GPIO.setup(rl, GPIO.OUT)
GPIO.setup(gl, GPIO.OUT)
GPIO.setup(bl, GPIO.OUT)

r=GPIO.PWM(rl,freq)
g=GPIO.PWM(gl,freq)
b=GPIO.PWM(bl,freq)
r.start(0)
g.start(0)
b.start(0)

GPIO.cleanup()

# Set LED to R, G, B for TIME seconds
def led(rv,gv,bv,t):
    r.ChangeDutyCycle(rv)
    g.ChangeDutyCycle(gv)
    b.ChangeDutyCycle(bv)
    time.sleep(t)
    r.ChangeDutyCycle(0)
    g.ChangeDutyCycle(0)
    b.ChangeDutyCycle(0)


while True:
    try:
        print("Reading..")
        id, text = reader.read()
        print(id)
        print(text)
        if text == "test":
            print('READ TEST. LED GREEN NOW.')
            led(0,2,0,1)
        else:
            print('DIDN\'T READ TEST. LED RED NOW.')
            led(2,0,0,1)
        time.sleep(1)

    finally:
        print('Loop done.')
        GPIO.cleanup()

In an endless loop, I read RFID, if the text "test" is read, the LED is green, if not it's red.

Why does the LED and RFID function interfere so badly? How can I change the code to achieve the desired functionality?

1 Answers1

1

Remove your GPIO.cleanup() lines, this would normally only be called before you exit a program.

https://sourceforge.net/p/raspberry-gpio-python/wiki/BasicUsage/

Cleanup

At the end any program, it is good practice to clean up any resources you might have used. This is no different with RPi.GPIO. By returning all channels you have used back to inputs with no pull up/down, you can avoid accidental damage to your RPi by shorting out the pins. Note that this will only clean up GPIO channels that your script has used. Note that GPIO.cleanup() also clears the pin numbering system in use.

To clean up at the end of your script:

GPIO.cleanup()

It is possible that don't want to clean up every channel leaving some set up when your program exits. You can clean up individual channels, a list or a tuple of channels:

GPIO.cleanup(channel)

GPIO.cleanup( (channel1, channel2) )

GPIO.cleanup( [channel1, channel2] )

CoderMike
  • 6,982
  • 1
  • 10
  • 15