簡體   English   中英

如何從Python 3中的無限循環線程獲取實時返回值

[英]how to get a realtime return value from an infinite loop thread in Python 3

我試圖創建一個不斷從我的機器人的傳感器讀取的線程,因此我可以在不同的運行情況下為電動機使用輸出的“轉向”值,以便能夠在旋轉,按時等條件下運行電動機。已經找到了類似的東西( Python從無限循環線程返回值 ),但這沒有幫助,因為它僅在我中斷循環時(即:斷開傳感器連接)打印出這些值。 這是我的代碼:

from sensor_and_motor_startup import *
import threading
import queue

DEFAULT_SPEED = 60

# PID Values --These are subjective and need to be tuned to the robot and mat
# Kp must be augmented or decreased until the robot follows the line smoothly --Higher Kp = Stronger corrections
# Same with Ki, after Kp is done --- note, Ki is not used in this case (error accumulation)
# Kd to 1, and move up or done until smooth, after Kp and Ki
# This process can take a VERY long time to fine-tune
K_PROPORTIONAL = 0.2
K_INTEGRAL = 0
K_DERIVATIVE = 0


class OneSensorLineFollower:
    target = 24
    error = 0
    last_error = 0
    derivative = 0
    integral = 0

    def __init__(self, color_sensor):
        self.__color_sensor = color_sensor

    def follower(self, side_of_line=None, kp=K_PROPORTIONAL):
        if side_of_line is None:
            side_of_line = self.SideOfLine.left
        else:
            side_of_line = self.SideOfLine.right
        self.error = self.target - (self.__color_sensor.value(3) / 2)
        self.integral = self.error + self.integral
        self.derivative = self.error - self.last_error
        motor_steering = ((self.error * kp) + (self.integral * K_INTEGRAL) + (self.derivative * K_DERIVATIVE
                                                                                          )) * float(side_of_line)
        self.last_error = self.error
        return motor_steering

    class SideOfLine:
        left = 1
        right = -1


def hisp_center_corrector(out_que):
    while True:
        follow = OneSensorLineFollower(left_side_sensor)
        steering = follow.follower(kp=0.15)
        out_que.put(steering)
        sleep(0.1)


def low_speed_follower(speed=DEFAULT_SPEED, rotations=5):
    follower = OneSensorLineFollower(center_sensor)
    steer_pair.on_for_rotations(follower.follower(kp=0.3), speed, rotations)


que = queue.Queue()
t = threading.Thread(target=hisp_center_corrector, args=(que,))
t.start()
t.join()
while True:
    value = que.get()
    print(value)

您正在調用.join() ,這會使您的主線程等待該線程完成。

以守護進程身份啟動您的線程,不要加入它:

threading.Thread(target=hisp_center_corrector, args=(que,), daemon=True).start()

否則,您的value = que.get()代碼將不會運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM