Filament-Scale-Enhanced
Filament-Scale-Enhanced copied to clipboard
time.sleep behaviour for microsecond sleeps has changed in Python 3
https://github.com/techman83/Filament-Scale-Enhanced/blob/ab7daf40741c778a462da1b94fdf3f0809f58d83/filament_scale_enhanced/hx711.py#L87-L91
This line will behave differently under Python 3.5+. In older versions this will behave like time.sleep(0) and sleep for between 0.5 and 14 usec. In Python 3.5+ it will sleep for 60 to 100 usec (ie the minimum non-zero sleep). See https://github.com/pimoroni/blinkt/issues/72 for details.
Since the delay is only while PD_SCK is low it should not cause spurious resets but I wanted to point it out anyway.
Interesting, I wonder what it should be? I'd like to refactor a bunch of this to make it a bit easier to add test cases.
I just noticed that this is trying to sleep 10 usec, so it won't behave differently in 2 vs 3. It will sleep 60+ usec on both however. It isn't really possible to sleep less than that in Python - time.sleep(0) returns "instantly" and the delay is just due to Python being not very fast.
HX711 datasheet says the minimum clock time is 0.2 usec, so just calling time.sleep(0)
(or basically any Python function) should be long enough. However leaving the current sleep won't hurt, as long as you never change it to sleep while the clock is high.
Here is the relevant cpython code from 2.7:
https://github.com/python/cpython/blob/v2.7.18/Modules/timemodule.c#L1041-L1044
The number of microseconds is converted to a long, so it has to be equal or greater than 1 usec.
In modern Python it is rounded up instead of down: https://github.com/python/cpython/blob/main/Modules/timemodule.c#L2072
I've never had to really care that much about tight timing, so that's really neat. Though I note that python can't time down to the microsecond level, at best it'll be in the realm of millisecond accuracy. And I'm guessing we're talking about the output settling time here, which has 2 values:
time (ms) | |
---|---|
RATE = 0 | 400 |
RATE = DVDD | 50 |
So we're either not waiting long enough or really not waiting long enough. It's probably largely academic at this point, but I might change it to ensure that it's actually doing what is intended.
I hadn't considered the effect of the settling time, although that only applies when the chip is powered down. Sleeping for 50 to 400 milliseconds is not a problem though.
The tricky one is the PD_CLK timing (page 5, T3 and T4) - measured in microseconds not milliseconds.
Yeah, likely an academic problem at this point. It works as is, so I'm inclined to leave it for now.