Timer with Audio release - python

I created a timer with a specific condition, when it runs out, it should release an Audio.
My Input :
import time
import playsound
run = raw_input("Start? > ")
mins = 0
# Only run if the user types in "start"
if run == "start":
# Loop until we reach 2 minutes running
while mins != 2:
print ">>>>>>>>>>>>>>>>>>>>>", mins
if mins ==2:
playsound.playsound('C:\Audio.mp3', True)
time.sleep(60)
# Increment the minute total
mins += 1
But sadly it doesn't release anything

Would it not be easier to use the time.sleep() function that you are already using in your script to play the sound after two minutes?
Something like the below:
import time
import playsound
time.sleep(120)
playsound.playsound("C:\Audio.mp3", True)

Related

python script to automate call and play voice recording during calls

Python script that will make a phone call to a specified phone number at a specified time using an Android device and play a voice recording during the call. my code didn't work failed transaction ?
import os
import datetime
def makeCall(number):
os.system(f"am start -a android.intent.action.CALL -d tel:{number}")
def playRecording():
os.system("am start -a android.intent.action.VIEW -d file:///sdcard/recordings/recording.mp3")
def checkTime(hour, minute):
currentTime = datetime.datetime.now()
if currentTime.hour == hour and currentTime.minute == minute:
return True
else:
return False
number = "1234567890" # Replace with your desired phone number
hour = 12 # Replace with the hour (in 24-hour format) at which you want the call to be made
minute = 0 # Replace with the minute at which you want the call to be made
while True:
if checkTime(hour, minute):
makeCall(number)
playRecording()
break # Exit the loop once the call has been made
else:
continue # Check the time again after a short delay
tried to run on my android phone can identify any mistakes and help me to fix it

Can not get my if statement to trigger using pytz timing for an alarm system

Using pytz to get a time. When the time is equal to a variable (string time), I want text to be printed (eventually a sound to be played). The time is iterating, but I can not get the statement to print when there is a match.
#imports
import time
from datetime import datetime
import pytz
#current time
def clocktime():
while True:
tz_syd = pytz.timezone("Australia/Sydney")
Sydney_Time = datetime.now(tz_syd).strftime("%H:%M:%S")
time.sleep(1)
#iterator to check for time match
def alarmsystem(clocktime):
TestCaseA = "20:52:16"
TestCaseB = "20:53:29"
while True:
if clocktime == TestCaseB:
print("Time B Triggered")
elif clocktime == TestCaseA:
print("Time A Triggered")
print(alarmsystem(clocktime()))
Any help greatly appreciated!
Your function clocktime() never stops running. Nor does it return or share anything about the time with alarmsystem().
When you write alarmsystem(clocktime()), the code will run and do clocktime() first. When ever clocktime() is done (never) it will send the return value (None in you case) to the function alarmsystem().
I assume what you want is that clocktime() runs continuously in the background, and the function alarmsystem() will trigger when that timer hits a certain time.
For this you need to have clocktime() run in a different thread.
If all your program needs to do is trigger on a certain time you can use the following code:
def alarmsystem():
TestCaseA = "20:52:16"
TestCaseB = "20:53:29"
while True:
tz_syd = pytz.timezone("Australia/Sydney")
clocktime = datetime.now(tz_syd).strftime("%H:%M:%S")
if clocktime == TestCaseB:
print("Time B Triggered")
elif clocktime == TestCaseA:
print("Time A Triggered")

Break a Input when the Time is up

I am making a project where users are asked to enter multiple input within a stipulated time.
This is what I Tried:
import time
import threading
def timer():
global sec
sec =21
while sec != 0:
sec -= 1
time.sleep(1)
print("Seconds left:",sec)
print("\nTime Over")
def ask_words():
while sec >0:
#Ask Question#
timer = threading.Thread(target = timer)
timer.start()
ask_words()
Output:
This is the output
Problem: After the time is up I can add the last input after which the code is getting completed because the code(input) is executed after which the sec variable is becoming Zero so the program is waiting for the user to enter something. I don't know how to fix it.

Logging rainfall with Python

First post and I am at a dead end with this problem.
(some background)
I have a raspberry PiZero which I am developing a weather station with, so far it logs temp, humidity and pressure as well as sending the data to the windy.com API. Recently I added a tipping bucket rain gauge.
This has 2 wires which connect to the GPIO, when the bucket tips it momentarily competes the circuit, essentially a button press!
The goal here is to count the tips every hour, then reset. before resetting, send this data to log file + Windy API. This is the part I am struggling with.
I am pretty good with python but I am at a true writers block moment, here is a small program I cobbled together from snippets which counts the tips for testing
/usr/bin/python3
import requests
from gpiozero import Button
import time
rain_sensor = Button(27)
bucket_size = 0.2794
count = 0
def bucket_tipped():
global count
count = count + 1
print(count * bucket_size)
def reset_rainfall():
global count
count = 0
#display and log results
def timed_loop():
reset_rainfall
timeout = time.monotonic() + 3600 # 1 hour from now
while True:
if time.monotonic() > timeout: # break if timeout time is reached
rain_sensor.when_pressed = bucket_tipped
time.sleep(1) # Short sleep so loop can be interupted
continue
print count
# close the log file and exit nicely
GPIO.cleanup()
It looks like you are continuously setting your rain to 0 in your while True: loop.
Edit:
Try something like this for your loop.
def timed_loop():
rain = 0
timeout = time.monotonic() + 3600 # 1 hour from now
while True:
if time.monotonic() > timeout: # break if timeout time is reached
# You place your code here that you want to run every hour.
# After that the loop restarts
rain = 1
time.sleep(1) # Short sleep so loop can be interupted
continue
Edit 3:
With the following code you can record button presses over a specified amount of time.
import time
def bucket_tip_counter():
recording_time_timeout = 3600 # Amount of seconds you want to have the timer run
recording_time = time.monotonic() + recording_time_timeout
button_timeout = 1 # This timeout is here so the button doesnt trigger the count more then once for each trigger
# You have to modify this to your needs. If the button stays activated for a few seconds you need to set the timer accordingly.
count = 0 # Sets the counter to 0 at the start
button = 0 # Here you need to replace the 0 with the GPIO pin that returns True if the button is pressed
while True: # starts the loop
if button: # if button gets pressed/bucket tipped
count += 1 # up count by one
time.sleep(button_timeout) # wait specified timeout to make sure button isnt pressed anymore
if time.monotonic() > recording_time: # If the recording_time is reached the loop triggers this if condition
print(count) # print count
# Here you can also place code that you want to run when the hour is over
# Note that the counter wont start back up until that code is finished.
count = 0 # set count back to 0
recording_time = time.monotonic() + recording_time_timeout # Set a new timer so the hour can start anew
continue # restart the loop
time.sleep(1) # small sleep to stop CPU hogging.

Pygame + python: 1 part of code has pygame.wait while rest of code runs

I am making a game in which u have to carry move objects from one place to another. I can move my character to the zone in which I need to put something. I want the player to wait in the zone for 5 secs before the object is placed there, however, if i do this you cannot move anymore if u decide u dont want to place the object in the zone as the whole script would be paused.
Is there a way to make one part of the script wait while the rest of it runs?
Every game needs one clock to keep the game loop in sync and to control timing. Pygame has a pygame.time.Clock object with a tick() method. Here's what a game loop could look like to get the behaviour you want (not complete code, just an example).
clock = pygame.time.Clock()
wait_time = 0
have_visited_zone = False
waiting_for_block_placement = False
# Game loop.
while True:
# Get the time (in milliseconds) since last loop (and lock framerate at 60 FPS).
dt = clock.tick(60)
# Move the player.
player.position += player.velocity * dt
# Player enters the zone for the first time.
if player.rect.colliderect(zone.rect) and not have_visited_zone:
have_visited_zone = True # Remember to set this to True!
waiting_for_block_placement = True # We're now waiting.
wait_time = 5000 # We'll wait 5000 milliseconds.
# Check if we're currently waiting for the block-placing action.
if waiting_for_block_placement:
wait_time -= dt # Decrease the time if we're waiting.
if wait_time <= 0: # If the time has gone to 0 (or past 0)
waiting_for_block_placement = False # stop waiting
place_block() # and place the block.
Example with threading:
from threading import Thread
def threaded_function(arg):
# check if it's been 5 seconds or user has left
thread = Thread(target = threaded_function, args = (10, ))
if user is in zone:
thread.start()
# continue normal code
Another potential solution is to check the time the user went into the zone and continuously check the current time to see if it's been 5 seconds
Time check example:
import time
entered = false
while true:
if user has entered zone:
entered_time = time.time()
entered = true
if entered and time.time() - entered_time >= 5: # i believe time.time() is in seconds not milliseconds
# it has been 5 seconds
if user has left:
entered=false
#other game code

Categories

Resources