ROS与python之时间教程

Time and Duration(时间和持续时间)

ROS中也有内置的时间和持续的原始类型

在rospy中由rospy.Time和rospy.Duration实现
主要参数有:

int32 secs  //秒
int32 nsecs    //纳秒

获取当前时间的命令

rospy.Time.now()
rospy.get_rostime()  //这两个是获取当前时间
seconds = rospy.get_time()  //获取浮点型的秒数

创建时间实例

rospy.Time(secs=0,nsecs=0)

epoch = rospy.Time()   # secs=nsecs=0
t = rospy.Time(10)   # t.secs=10
t = rospy.Time(12345,6789)  

使用rospy.Time.from_sec(float_secs)

t = rospy.Time.from_sec(123456.789)

在时间和持续时间的情况下转换为秒以及纳秒

t = rospy.Time.from_sec(time.time())
seconds = t.to_sec()    #floating
nanoseconds = t.to_nsec  

d = rospy.Duration.from_sec(60.1) #a minute and change
seconds = d.to_sec()    #floating
nanoseconds = d.to_nsec()

持续时间的算数运算

two_hours = rospy.Duration(60 60) + rospy.Duration(60 60)
one_hour = rospy.Duration(2 60 60) - rospy.Duration(60 60)
tomorrow = rospy.Time.now() + rospy.Duration(24 60 60)

Sleeping and Rates(睡眠和速率)

rospy.sleep(duration),duration可以是rospy.Duration

# sleep for 10 seconds
rospy.sleep(10.)

# sleep for duration
d = rospy.Duration(10,0)
rospy.sleep(d)

rospy.sleep()如果出现错误,会抛出rospy.ROSInterruptException
rospy.Rate(hz),可以保持一定的速率来进行循环

r = rospy.Rate(10)  # 10Hz
while not rospy.is_shutdown():
	pub.publish("hello")
	r.sleep()

函数定义:rospy.Timer(period,callback,oneshot=False)
period,调用回调函数的时间间隔,如rospy.Duration(0.1)即为10分之1秒
callback,回调函数的定义
oneshot,定时器,是否多次执行。false即一直执行、

def my_callback(event):
	print 'Timer called at' + str(event.current_real)

rospy.Timer(rospy.Duration(2),my_callback)

Timer实例会每秒调用my_callback

你可能感兴趣的:(ros)