pimylifeup / MFRC522-python

Library utilized for Pi My Life Up's guide on setting up an RFID RC522 reader.
https://pimylifeup.com/raspberry-pi-rfid-rc522/
GNU Lesser General Public License v3.0
193 stars 173 forks source link

High CPU usage on idle state #9

Open senadir opened 5 years ago

senadir commented 5 years ago

https://github.com/pimylifeup/MFRC522-python/blob/970e903c994ff4c5f30bc7d5f22dd31ca0b1da91/mfrc522/MFRC522.py#L216-L220

so CPU usage is really high, about 105% on idle state, the raspberry shutdown after a while and we have to restart the code again.

I tracked the problem the line 216 in MFRC522, I've added a simple sleep of 10 milliseconds and it seemed to lower the CPU usage a bit (about 45%); it still cause an issue and the reader stops randomly.

for the record, I didn't hook up the IRQ pin (i was following a tutorial that referred this code and they didn't hook it up), could this be the case? I could test since I've run out of pins in my IoT device.

agentflippy5 commented 5 years ago

I'm not familiar enough with the project to implement this, but long term it would probably be good to use event listeners like what they were talking about here: https://github.com/MiczFlor/RPi-Jukebox-RFID/issues/275

In the meantime, my pull request almost entirely reduces the processor load. It's not the best solution but it works

I also have not attached the IRQ pin

WhiteLionATX commented 4 years ago

Same problem here with high CPU usage.

tmaf9011 commented 4 years ago

The ultimate solution here is to just upgrade to an interrupt method.. but if you're like me and already have it setup and don't currently feel like switching around pins or adding the IRQ pin to your project then follow these steps:

Add a simple sleep in the while loop like shown in one of the "fix its" above : n = self.Read_MFRC522(self.CommIrqReq)

You only need a time.sleep(0.05) delay unless you want to go further, but on a Raspberry Pi 4, this already greatly reduces CPU usage. With a time.sleep(.1) it has a noticeable delay in the scan.

The additional step that nobody else has mentioned yet here is to go 1 line above that while True: loop to the i = 2000 and change it to i = 5. Realistically, anything from i = 2 - i = 2000 will work (for ID scans that is, I havn't tested any text-based read data with this. I also havn't tested any writing data with this...).

From my findings... i needs to loop through 0 before it will pickup the RFID chip. If you add a delay, it may detect the reader once the i becomes 0, or maybe not because the rfid chip is too far away at that point. Regardless, I don't have an explanation of why this has to loop through 0.

Removing the large i value and adding a very short time.sleep drastically fixes the CPU usage until you can upgrade to the interrupt system in the comments mentioned above.