-2

I am reading cards in Python using an RFID Reader and I want to detect how long a card has been detected for in seconds, minutes and hours.

The program begins to run once a card has been detected and starts the count but the problem is that the code does not break when the card has been removed but instead it continues counting even if the card is not being detected.

The code is attached below:

import time as tm
import serial
import readCard


def getActivity():
    # tm.sleep(3)
    while True:
        card = readCard.readCard()
        cards = card

        if card != '':
            seconds = 0
            minutes = 0
            hours = 0

            while True:

                print(str(hours).zfill(2) + ":"
                + str(minutes).zfill(2) + ":" 
                + str(seconds).zfill(2))

                seconds = seconds + 1
                tm.sleep(1)
                if seconds == 60:
                    seconds = 0
                    minutes = minutes + 1
                if minutes == 60:
                    minutes = 0
                    hours = hours + 1
               
        else:
            print('No Card Detected...')

getActivity()
 

The output is as follows:

00:00:00
00:00:01
00:00:02
00:00:03
00:00:04
00:00:05

I expect the time to start counting if the card is being detected and once the card has been removed, the program should begin to print out "No Card Detected...".

1 Answers1

0

You will never leave from second while True. You must read the card every second and check if the card has been removed. Add the code below to the second while True. I think that will may solve your problem and after removing the card, program break from while.

if readCard.readCard() == '':
  break
Fanteria
  • 62
  • 1
  • 4
  • or you can change from `while true` to `while readCard.readCard()`. – Dronakuul Nov 13 '22 at 08:28
  • @Dronakuul, I have tried both suggestions and they have worked. I would also like it to start the count from zero once the card has been placed back. This is the output it is currently giving: 00:00:00 00:00:01 00:00:02 00:00:03 No Card detected... No Card detected... No Card detected... No Card detected... No Card detected... 00:00:04 00:00:05 No Card detected... No Card detected... No Card detected.. – Elijah Chileshe Nov 13 '22 at 10:05
  • That is really strange. I would not expect this, since one you are in the outer loop you can only come back by resetting the seconds. – Dronakuul Nov 14 '22 at 19:08