python - 如何从 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()
代码将无法运行。
推荐阅读
- sql - 将 2 个字符串列(如年和月)合并为日期格式列
- javascript - 无法使用 javascript 删除第一个表格行
- javascript - 无法在嵌套数组中打印数据
- c++ - 简单的随机数生成器无限循环
- c# - 如何在 .Net Core 3.1 WPF 应用程序中调试 XAML 热重载?
- ruby-on-rails - 为什么 RSpec/Capybara 使用 public_send 提供的连字符值抛出错误?
- ajax - 用 AJAX 替换 iFrame 嵌入式 Web 应用程序的示例 Javascript 代码(请不要使用 jQuery)
- c# - 如何将 XAML 元素设置为默认为当年?
- regex - 使用 vi 编辑器将数字替换为 csv 文件中的双引号
- rust - 将 async/await 与旧的 `Future 一起使用
- ` 类型