我正在建造一个小型机器人,我正在尝试创建两种不同的模式:
第一个是使用操纵杆进行手动控制,使用
/joy
节点。
第二种是自动模式,它检测黑线并在其上行驶。
我的问题是我想在按下按钮时退出此模式。这是程序的简化基本函数:
def callback(data):
rospy.loginfo(rospy.get_caller_id() + "motor variables: %s, %s, %s", data.axes[2], data.buttons[2], data.buttons[3]
if data.buttons[2] == 1:
automode = 1
if data.buttons[3] == 1:
automode = 0
if automode == 1:
manual(data)
if automode == 0:
automatic(data)
def automatic(data):
while True:
# This is the function that works,
# but the problem arises when I want to exit it:
if cv2.waitKey(1) & data.buttons[3] == 1:
break
原本是
cv2.waitKey(1) & 0xff == ord('q')
,但由于需要通过控制器来访问,所以我无法使用它。
基本问题是 data.buttons[3] == 1
在 while 循环中无法访问,但我不知道如何更改我的代码,以便在按下正确的按钮时它实际上会发生变化。
有人知道如何解决这个问题吗?
我在谷歌上搜索了使用全局变量的可能性,但根据我的理解,它只是保存条目,并且不会“切换”到回调函数来查找按钮按下。
您应该在这里使用全局变量。只要您不拆除订阅者,回调函数将始终运行和更新。在下面的示例中,它看起来像这样:
button_pressed = 0
def callback(data):
global button_pressed
button_pressed = data.axes[3]