counting code giving me 0 instead of a value - python

this is my code:
from threading import Timer
timeout = 5
t = Timer(timeout, print, ['Sorry, times up'])
t.start()
count_push1 = + 1
print("Please push the button to count up.You have 5 seconds.")
while True:
if bool(push_button1.read()):
press_count = + 1
print(press_count)
sleep(0.2)
break
else:
print('You pressed', press_count, 'times.')
break
break
I want the user to have 5 seconds.In that 5 seconds, the user will click a button, and timer will reset to 5 seconds.If button is not clicked in 5 seconds,it shows the total number of times user pressed the button.I tried but when I run the code,the code automatically ends.Someone help please

You have the order of the operators wrong. In your while loop, you need to change the counter to count_push1 += 1
At the top where you define the variable as being 1, I would remove the the + for readability.
Edit: count_push1 += 1 is short for count_push1 = count_push1 + 1

Related

(Python) How to listen to keyboard while doing other things in a while loop

Here is my code.
import keyboard
while num <= total_num_list-1:
show_num = num + 1
duration_in_min = 1:30
t = 1
while t <= duration:
if keyboard.is_pressed("n"):
break
time.sleep(1)
time_in_min = time.strftime('%M:%S', time.gmtime(t))
print(f"{time_in_min}/{duration_in_min}")
t += 1
num += 1
This code is working for now, but it needs me to hold the "n" key to break the loop because of the delay. What I want is it to have a immediate respond to my key press. What modules can I use or what should I do to make it work?
I am a beginner, sorry if there is any mistakes.

A timer that restarts on a trigger Python - how to restart?

Bit of a newbie so bear with:
I am trying to make a crude 60s timer that is reset and starts again on the rising edge of a trigger (ie when a gate goes high). The problem I have is that it won't reset and restart unless the timer has completed (ie reached zero). How do I interrupt the while loop and get it to start again?
Here is my code:
import keyboard
import time
t=60
last = False
current = False
while True:
current = keyboard.is_pressed('space') # triggered when space bar is pressed
if last == 0 and current == 1:
while t>=0:
print(t)
t-=1
time.sleep(1)
last = current # reset
Try this:
import time
import keyboard
x=60
while True:
try:
if keyboard.is_pressed('space'):
x=60
print(f"Timer reset to {x}")
elif keyboard.is_pressed('space'):
break
else:
print(f"{x} seconds left")
time.sleep(1)
x-=1
except Exception:
pass
This is my suggestion. The problem is, that time.sleep is blocking, so when it's sleeping you cannot break it by pressing escape. You will have to spam the escape button, but it works.
import keyboard
import time
t=60
last = False
current = False
while True:
current = keyboard.is_pressed('space') # triggered when space bar is pressed
if last == 0 and current == 1:
while t>=0:
if keyboard.is_pressed('escape'):
t = 60
last = False
current = False
print("Timer stopped.")
break
print(t)
t-=1
time.sleep(1)
last = current # reset
Sample output/test:
60
59
58
57
56
60
59
58
57
56
60
59
60
59
58
To suggest a solution without break:
import keyboard
import time
last = 0
current = 0
while True:
t=60
current = keyboard.is_pressed('space') # triggered when space bar is pressed
if last == 0 and current == 1:
current = 0
while t>=0 and current == 0:
print(t)
t-=1
time.sleep(1)
current = keyboard.is_pressed('space')
last = current # reset
Not sure how you want to manage long presses here. If the spacebar stays pressed for more than one second, the timer will reset several times in (technically) one keypress.

Adding a timer to the while loop

The program I made is like monkey typer and I want to implement a timer into my code but I don't know-how. If I make another while loop it runs separately all I want to do is have a timer running at the same time as you are inputting the words. Where do I implement the timer() the while loop? New while loop?
# imports
from words import words
import random
import time
# variables
score = 0
max_score = 10
def timer(length):
while True:
print(length)
length = length - 1
time.sleep(1)
if timer == 0:
print('Game completed \nFinal score, ', score)
break
while True:
random_word = random.choice(words)
print('\n', random_word)
user = input(':')
# if correct
if user == random_word:
score = score + 1
print('Correct!\n', 'Score,', score)
# if incorrect
if user != random_word:
print('Incorrect!\n', 'Score,', score)
score = score - 1
if score < 0:
score = 0
# made by Jack Winton
You could try using multithreading or multiprocessing to create a timer, have one thread or process working on the code and another thread running the timer. Another option is to use time = time.time() then once the loop is finished add an end = time.time() and then do overall_time = start - end but I think you are trying to do a countdown, not a timer.

How do I iterate through a countdown timer while checking for user input simultaneously?

I am trying to code a chess timer in which there are two timers counting down alternatingly. Only one timer runs at a time, and when a certain input is given by the user, which I am using keyboard.is_pressed("some_key") for, one timer pauses and the other begins counting down and vice versa. My problem is that to countdown by intervals of 1 second, I am using time.sleep(1) and the program will not receive user input during this time, so unless the user gives input on exactly the 1 second mark, nothing happens. How can I make the countdown process and the checking for user input process run at the same time?
Here is the code:
import time
import keyboard
def timers(t1, t2):
pause = True
while t1 or t2:
if pause:
while pause:
mins1 = t1 // 60
secs1 = t1 % 60
timer1 = '{:02d}:{:02d}'.format(mins1, secs1)
print("Timer1: ", timer1)
time.sleep(1)
t1 -= 1
if keyboard.is_pressed("w"):
pause = False
break
else:
continue
else:
while not pause:
mins2 = t2 // 60
secs2 = t2 % 60
timer2 = '{:02d}:{:02d}'.format(mins2, secs2)
print("Timer2: ", timer2)
time.sleep(1)
t2 -= 1
if keyboard.is_pressed("w"):
pause = True
break
print("Beep")
tWhite = int(input("Enter the time in seconds for White: "))
tBlack = int(input("Enter the time in seconds for Black: "))
timers(tWhite, tBlack)

Implementing max amount of time for user input through buttons in python/raspberry pi

I'm struggling to find a way to implement a timelimit in the nested while-loop. I want the user to have a set amount of time to press the button(15 seconds for example). The program should break out of the nested loop once a maximum of three presses has been reached(which works) or once the timelimit has been surpassed. This is a piece of code for an autonomoust RC car. Thanks in advance.
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
button1 = 26
GPIO.setup(button1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
print("Where do you want to go? Press once to go to the right, twice to go left or three times to go straight"
"Wait one second inbetween clicks and 10 seconds to finish the process.")
while 1:
clickCounter = 0
while 1: # Keeps track of clicks.
if GPIO.input(button1) == 0:
clickCounter += 1
print("Amount of clicks: ", clickCounter)
time.sleep(1)
if clickCounter == 3 or x: # Loop breaks if amount of clicks is 3 or if the time is up.
break
# Different outcomes based on the amount of clicks.
if clickCounter == 0:
print("Press the button 1-3 times.")
elif clickCounter == 1:
print("We're going to the right.")
clickCounter = 0
break
elif clickCounter == 2:
print("We're going to the left.")
clickCounter = 0
break
elif clickCounter == 3:
print("We're going straight.")
clickCounter = 0
break
You could calculate elapsed time (from the start of the loop) and exit the loop when time is up.
while 1:
# Mark time at start of loop
start_time = time.time()
clickCounter = 0
while 1: # Keeps track of clicks.
if GPIO.input(button1) == 0:
clickCounter += 1
print("Amount of clicks: ", clickCounter)
time.sleep(1) # I assume this is here for debounce
# Calc time since start of loop
elapsed_time = time.time() - start_time
if clickCounter == 3 or elapsed_time >= 15: # Loop breaks if amount of clicks is 3 or if the time is up.
break
# Different outcomes based on the amount of clicks.
....

Categories