I try to insert stopwatch in my python code. Code read data from API, and if is value bigger then "3" switch relay to ON ( raspberry Pi3 ). This is read every XXX minutes. I want print time how long it's relay on or off.
while True:
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
.
.
.
.
.
.
if highest > 3:
print("RELAY ON")
print st
print # time how long it's on
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
else:
print("RELAY OFF")
print st
print # time how long it's off
GPIO.cleanup()
time.sleep(60)
I try with this code, but I do not know where to insert it.
import time
start = time.time()
time.sleep(10)
end = time.time()
total = end-start
print total
Thankyou for help!
Let's look only at the timing logic. When you turn the relay on, you mark that start time. The "time on" measurement continues until you turn the relay off. Then the "time off" timer starts, continuing until you turn it on again.
I suspect that you're a little confused because the start and stop events are in different code blocks. First, let's measure the "relay on" time. I'll make a flag relay_is_on
to notice when the relay state changes.
When the state changes, we'll take action: print the status change, reset the flag, and mark the start or stop time.
relay_is_on = False
while True:
if highest > 3:
if not relay_is_on:
# Relay is just turning on;
# process changes
print("RELAY ON")
relay_is_on = True
relay_on_start = time.time()
else:
if relay_is_on:
# Relay is just turning off;
# process changes
print("RELAY OFF")
relay_is_on = False
relay_on_end = time.time()
relay_on_interval = relay_on_end - relay_on_start
From here, you can do whatever you need to accumulate or report the relay-on intervals. Also, if you need to similarly handle relay-off times, you simply add a few lines in the converse logic.
Can you continue from here?