#!/usr/bin/env pythonimport rospyfrom bzrobot_msgs.msg import bzr_WheelLinearVels#from threading import Threadfrom time import sleepclass 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. About rospy. Spin () Multiple callback calls
If the program does not have rospy. Spin () or the yellow part above, multiple callback calls will be called when a message is subscribed.
2. when a subscribed message is received, ballback is in the R. call when sleep () time gap, so the callback execution time cannot exceed R. the gap time provided by sleep (). For example, setting sleep (1) in callback consumes R. sleep (), and then run print 'after sleep 1S '. At this time, flg = 0, so the while loop jumps out and ends the program.
You can also directly use sleep () instead of rospy. Rate and R. Sleep.
3. It is best to use:
While not rospy. is_shutdown (): # True:
If self. flg = 1: # encoder_list [0] = 'E ':
1. About calling callback for multiple times without rospy. Spin () 2. Statements following subscrib and callback function running sequence