I am trying to switch on and off the LED based on a set set_car_id returning some value within a time interval. If the set returns some value, i want the LED to be brighter for 8 seconds. In the code shown below, once the set returns a value, the LED is switched on for 8 seconds. But, if the set returns a value at 5 second (within the 8 sec), then the LED won't be switched on till next 13 sec, it will be on for 3 more seconds and then suddenly switches off. I am showing only smaller part of the code. Any suggestions to solve?
last_bright_time = None
last_dim_time = None
new_action = -1
def LED_control(set_car_id):
global last_bright_time
global last_dim_time
curr_time = time.time()
should_remain_bright = False
should_remain_dim = False
if (new_action == 0): #new_action ==0 corresponds to set_car_id returning some value
if last_bright_time == None:
last_bright_time = time.time()
if (curr_time - last_bright_time) < 8:
should_remain_bright = True
if ((len(set_car_id) > 0) or should_remain_bright = True):
car_light(1) # function to bright the LED
last_dim_time = None
else:
car_light(0) # function to dim the LED
last_bright_time = None
Try this:
import time
while True:
brighten()
time.sleep(8)
dim()
time.sleep(8)
If you want something more precise:
import time
def sleep():
time_start = time.time()
while time.time() < time_start + 8000:
pass
while True:
brighten()
sleep()
dim()
sleep()
In the pieces of code above, you have to define the brighten and dim functions.
Related
im trying to start and end the while loop with a time difference.
At first Im getting the current time with date time.now
in my def I want to create a time difference. This should be 10 seconds.
The function should give a False, if the seconds were expired and the current time is equal to the previous time (current time + 10s). Otherwise it should give me a True return.
After this im setting the "Zeit" variable to True, so the while loop can start.
In the while loop im starting the "fkt_Zeit", to change the "Zeit" condition at the while loop to False, after the 10 seconds expire.
So that's my plan, but its not working. The "Zeit" variable never changes to False.
Can you please help me finding my mistake?
And sorry for my bad english...
akt_zeit = datetime.now()
timedelta = timedelta(seconds=10)
def fkt_Zeit(akt_zeit, timedelta):
off_time = akt_zeit + timedelta
while(True):
if(akt_zeit < off_time):
return True
else:
return False
Zeit = True
while(Zeit == True):
Zeit = fkt_Zeit(akt_zeit, timedelta)
In this code
while(Zeit == True):
Zeit = fkt_Zeit(akt_zeit, timedelta)
you call the function fkt_zeit, but notice that the time delta is computed inside this function. That means that every time you call fkt_zeit you reset the time needed for fkt_zeit to return false. That's why your function is never returning false. I'd suggest moving the off_time computation outside of the fkt_zeit function. For example:
def fkt_Zeit(akt_zeit, timedelta):
while(True):
if(akt_zeit < off_time):
return True
else:
return False
Zeit = True
off_time = akt_zeit + timedelta # so the off_time doesn't keep resetting
while(Zeit == True):
Zeit = fkt_Zeit(akt_zeit, timedelta)
Hope this helps.
I have python script below, which checks whether ping is success, If it success within 100 Seconds it will return True. If ping is failed it should return False but it is not returning False and when ping is success it is returning True.
Can anyone fix below code why it is not return False
Code:
def ping(self,hostname):
time_check = datetime.now()
data = ""
while not "Success" in data:
time.sleep(1)
data = self.pingCheck("ping 10.10.10.1 count 5")
if (datetime.now()-time_check).seconds > 100:
return False
return True
The code below will work for you:
import time
def ping(self, hostname, try_for=100):
t_end = time.time() + try_for
is_succeed = False
while time.time() < t_end or is_succeed:
time.sleep(1)
data = self.pingCheck("ping 10.10.10.1 count 5")
is_succeed = "Success" in data
return is_succeed
I've defined wait time as parameter called try_for, which default value is set to 100, but you can pass any other amount of seconds which you want spend waiting for host availability.
I'm using this code as a template (KILLING IT section)
https://stackoverflow.com/a/36962624/9274778
So I've solved this for now... changed the code to the following
import random
from time import sleep
def worker(i,ListOfData):
print "%d started" % i
#MyCalculations with ListOfData
x = ListOfData * Calcs
if x > 0.95:
return ListOfDataRow, True
else:
return ListOfDataRow, False
callback running only in main
def quit(arg):
if arg[1] == True:
p.terminate() # kill all pool workers
if __name__ == "__main__":
import multiprocessing as mp
Loops = len(ListOfData) / 25
Start = 0
End = 25
pool = mp.Pool()
for y in range(0,Loops)
results = [pool.apply(worker, args=(i,ListOfData[x]),callback = quit)
for y in range(0,len(ListofData))]
for c in results:
if c[1] == True
break
Start = Start + 25
End = End +25
So I chunk my data frame (assume for now my ListOfData is always divisible by 25) and send it off to the multiprocessing. I've found for my PC performance groups of 25 works best. If the 1st set doesn't return a TRUE, then I go to the next chunk.
I couldn't use the async method as it ran all at different times and sometimes I'd get a TRUE back that was further down the list (not what I wanted).
Below is the code i ran on the Intel Galileo Gen2. I'm just wondering why when the object come really close to the ultrasonic sensor the program stops and complain about that the variable sig "local variable 'sig' referenced before assignment"?
import mraa
import time
trig = mraa.Gpio(0)
echo = mraa.Gpio(1)
trig.dir(mraa.DIR_OUT)
echo.dir(mraa.DIR_IN)
def distance(measure='cm'):
trig.write(0)
time.sleep(0.2)
trig.write(1)
time.sleep(0.00001)
trig.write(0)
while echo.read() == 0:
nosig = time.time()
while echo.read() == 1:
sig = time.time()
# et = Elapsed Time
et = sig - nosig
if measure == 'cm':
distance = et * 17150
elif measure == 'in':
distance = et / 0.000148
else:
print('improper choice of measurement!!')
distance = None
return distance
while True:
print(distance('cm'))
Your problem is that the spike produced by your sensor is too short to be noticed, as the sampling-frequency of your while echo.read() is limited.
This then never defines the variable sig.
To overcome this, define sig = None when entering the function, and then later test for it being None - then you know you can't use your measurement.
If you want to sample with higher frequency, you need to use a language that is faster than Python, e.g. C++.
The problem is:
while echo.read() == 0:
nosig = time.time()
while echo.read() == 1:
sig = time.time()
if the first condition is met and has not returned to 1 by the time the next line is read then sig will never get a value.
I am trying to create a stopwatch that starts and stops through the user pressing the enter. Once to start and again to stop. The start works perfectly but the stopping section is not working. I've tried creating a variable called stop that is like so:
stop = input("stop?")
But it's still not working.
import time
def Watch():
a = 0
hours = 0
while a < 1:
for minutes in range(0, 60):
for seconds in range(0, 60):
time.sleep(1)
print(hours,":", minutes,":", seconds)
hours = hours + 1
def whiles():
if start == "":
Watch()
if start == "":
return Watch()
def whiltr():
while Watch == True:
stop = input("Stop?")
#Ask the user to start/stop stopwatch
print ("To calculate your speed, we must first find out the time that you have taken to drive from sensor a to sensor b, consequetively for six drivers.")
start = input("Start?")
start = input("Stop")
whiles()
Perhaps all you need is something simple like:
import time
input('Start')
start = time.time()
input('Stop')
end = time.time()
print('{} seconds elapsed'.format(end-start))
Should probably use the time function instead of
def Watch():