Issue
Hello stackoverflow community!
I am writing a python script to repeatedly retrieve a value from a PiHat sensor. I found this answer on stack overflow href="https://stackoverflow.com/questions/10813195/run-a-python-function-every-second">Run a python function every second but I run into the following error after it completes one loop: ValueError: sleep length must be non-negative
Here is the code
from sense_hat import SenseHat
import time
start_time = time.time()
interval = 1
sense = SenseHat()
# humidity = sense.get_humidity() *move this to loop
for i in range(20):
humidity = sense.get_humidity()
sense.clear()
print(humidity)
time.sleep(start_time + i*interval - time.time())
# f()
*edited the above code to fetch sensor values in the loop in case anyone wants to run similar code. Otherwise, it will just display the same value repeatedly I have kept everything else the same for reference and so you can see where I went wrong. Also commented out f().
No one seemed to have mentioned the issue on the thread I found it on. I have run data science projects with python but not many traditional programs so I apologize if the formatting is off.
Basically, could you explain why it does this and maybe some possible solutions to make it work. If you can explain why, it would really help my understanding of python. The sample code I found this on is very old and possibly an outdated method? I am running this on a raspberry Pi 4 b so it is possibly not executing fast enough?
I appreciate the help
Solution
As mentioned in the comments, in the first iteration of the for-loop, "i" is 0. You should take into account that the calculated value may become negative (hence the ValueError: sleep length must be non-negative
).
You can use max(0, start_time + i*interval - time.time())
or change the range to range(1,21)
to prevent this from happening.
As far as the differences between Pycharm and on the Raspberry, it might have to do with the clock precision of the two machines (different time yield by time.time()
)
Answered By - rikyeah Answer Checked By - Marie Seifert (WPSolving Admin)