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 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