-1

I have some issues with time.sleep() management in Python. I would like to use some values in a second part of the script, but they have to be delayed 300 ms one from another and I want to delay only that part of the script and not all the rest. These values are the X coordinates of an object detected by a camera. The script is something like this:

while True:
       if condition is True:
             print(xvalues)
             time.sleep(0.3)
       
       if another_condition is True:
             #do other stuff and:
             np.savetxt('Xvalues.txt', xvalues)
 

In the second part of the script (#do other stuff), I will write G-code lines with the X-coordinate detected and send them to a CNC machine. If I write a time.sleep() in that position of the script, everything in the while loop will be delayed.
How can I extract some values sampled 300ms a time without influencing the rest of the script?

Ruggero
  • 427
  • 2
  • 10
  • 2
    Sounds like you need multithreading. But without more detail about your application, it's really hard to give any useful advise. – ahans Oct 14 '21 at 07:55
  • 1
    Threading: https://stackoverflow.com/questions/92928/time-sleep-sleeps-thread-or-process – Ari Cooper-Davis Oct 14 '21 at 07:55
  • @ahans In the second "if" statement I have to send some G-code commands to a CNC machine, and every G-code line must have the X-coordinate detected 300ms a time. If I write a time.sleep() in that position, the machine will be delayed as well. I'll edit my post – Ruggero Oct 14 '21 at 08:01

2 Answers2

0
from threading import Thread


class sleeper(Thread):
    if condition is True:
        print(xvalues)
        time.sleep(0.3)

class worker(Thread):
    if another_condition is True:
        #do other stuff and:
        np.savetxt('Xvalues.txt', xvalues)

def run():
    sleeper().start()
    worker().start()
Julio Porto
  • 113
  • 8
0

You can include the 300ms checking as part of handling condition.

The first time you detect condition, get and remember the current time in a variable.

The next time condition is true again, check that it's more than 300ms from the last time the condition was true.

Something like this:

last_condition_time=None
while True:
       if condition is True:
          if not last_condition_time or more_than_300ms_ago(last_condition_time):
             print(xvalues)
             last_condition_time = get_current_time()
       
       if another_condition is True:
             #do other stuff and:
             np.savetxt('Xvalues.txt', xvalues)
 
One.Punch.Leon
  • 602
  • 3
  • 10