#!/usr/bin/env python import rospy from bzrobot_msgs.msg import bzr_WheelLinearVels #from threading import Thread from time import sleep class RS232MotorComm(): def callback(self, data): print ‘****************************************start callback‘ self.flg=0 sleep(0.05) rospy.loginfo("speed %f %f",data.leftWheelLinearVel, data.rightWheelLinearVel) self.flg=1 def motor_listener(self): self.flg=1 rospy.init_node(‘rs232_motor_comm‘, anonymous=True) rospy.Subscriber("control_wheel_linear_vel", bzr_WheelLinearVels, self.callback) #sleep(1) r = rospy.Rate(10) # 10hz while self.flg==1:#not rospy.is_shutdown():#True: print‘where‘ r.sleep() #time must enough for callback,or it will out while loop print‘after sleep 1s‘ if __name__ == ‘__main__‘: motor_controller = RS232MotorComm() print‘the1‘ motor_controller.motor_listener() #rospy.spin() print‘end‘
1.关于rospy.spin()调用多次callback
程序若无rospy.spin(),也无上面黄色部分,则订阅一次发布消息会调用多次callback。
2.当接收到订阅消息时,ballback在r.sleep()时间空隙的时候调用,所以callback的执行时间不能超过r.sleep()提供的间隙时间,例如在callback里设置sleep(1),则会消耗完r.sleep(),然后运行print ‘after sleep 1s‘,此时flg=0,因此跳出while循环,结束程序。
直接用sleep()代替rospy.Rate和r.sleep(),也是可以的。
3.最好使用:
while not rospy.is_shutdown(): #True:
if self.flg==1: #encoder_list[0]=‘e‘:
时间: 2024-11-10 23:07:59