I run a Python script on my RPi that manages all the sensors on the board and communicates with another machine using TCP sockets. The project gained in complexity and my script now has 5 threads running at all times (one for networking, one for processing camera images, etc.).
I noticed that while my distance sensor (HC-SR04) is working well with a minimal test script (C.F. below), it starts giving wrong values (values lower than expected) when I run the same code in my real program and when all threads are working.
Distance sensor snippet:
import time from gpiozero import DistanceSensor ECHO = 19 TRIG = 26 sensor = DistanceSensor(ECHO, TRIG, max_distance=4.5) while True: print("Distance to nearest object is", sensor.distance, "m") time.sleep(1)
If I run only 4 threads or if I put a
time.sleep() in my infinite loops (each thread runs an infinite loop), the sensor gives the right values again.
How can this be explained? My hypotheses:
- The CPU "eats up" all the current when the infinite loops are running and the RPi cannot feed enough current to the sensor?
gpiozerolibrary runs some code in another thread behind the scene that needs to run pretty fast, and since there are a lot of work already going on it can't run as fast as needed?
What do you think? What should I do?