Search code examples
pythontimerfid

How to break out of a While True loop in Python


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...".


Solution

  • 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