I have a two functions that need to run constantly, but due to the fact they affect real world objects, there are certain constraints. I can’t run the functions faster or slower or else the display begins to look choppy or the stepper tries to damage parts or itself.
import concurrent.futures as cf
import multiprocessing as mp
import threading as th
from gpiozero import OutputDevice as Opin
from time import sleep
stepdir = Opin(20)
steppul = Opin(21)
# This function is so fast, it is hard to measure the time it takes
def read():
"""
This function reads a series of sensors through GPIO and accessory boards.
"""
val1 = measured_value1
val2 = measured_value2
...
output = (val1, val2, ...)
return output
# This function rarely takes more than a thousandth of a second
def display(parseme):
"""
This function takes a series of values and parses them so they can be displayed on the correct gauge.
"""
val1 = parseme[0]
val2 = parseme[1]
...
# These are functions imported from another file of mine
gauge_pos1(val1)
sleep(0.0001)
gauge_pos2(val2)
sleep(0.0001)
...
# This function takes up to a hundredth of a second. Fast in its own right, but a hundredth
# is an eternity to a display that works in a few ten-thousandths
def adjust_stepper(pos, delta):
"""
This function is fed a stepper position value and a delta value that determines if the
stepper needs to be moved and in what direction it needs to move.
"""
if delta > 0.25:
stepdir.on()
steppul.on()
sleep(0.005)
steppul.off()
sleep(0.005)
pos += 1
elif delta < 0.25:
stepdir.off()
steppul.on()
sleep(0.005)
steppul.off()
sleep(0.005)
pos -= 1
return pos
while True:
# First, I must measure
measures = read()
# Next, I must display
display(measures)
#Finally, I must adjust the stepper
adjust_stepper(pos, delta)
I need to be constantly measuring inputs and displaying certain inputs, regardless of whether or not the adjust_stepper function is currently running the stepper. Right now, the measurements do run constantly, but the display stops because I can’t restart the display function to run with the new inputs until the stepper is done moving and that function finishes.
I still haven’t figured out what mix of concurrent.futures, threading, and multiprocessing will give the desired result. Should I be adding, removing, or reorganizing steps in this process?
So far, I’ve tried adding threading and multiprocessing, but the use of join() to make sure I don’t try and give conflicting commands to the gauges or stepper leads me to the same problem. Now the functions can run at the same time, but I still can’t update the display until the stepper is done moving due to join().
Bryon Meredith is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.