-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathturtle_controller.py
More file actions
47 lines (37 loc) · 1.29 KB
/
turtle_controller.py
File metadata and controls
47 lines (37 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env python3
import rospy
from turtlesim.msg import Pose
from geometry_msgs.msg import Twist
from turtlesim.srv import SetPen #importing service
previous_x=0
def call_set_pen_service(r,g,b,width,off): #function to call the service
try:
set_pen=rospy.ServiceProxy("/turtle1/set_pen",SetPen) #creating a service client
set_pen(r,g,b,width,off)
#rospy.loginfo(response)
except rospy.ServiceException as e:
rospy.logwarn(e)
def pose_callback(pose: Pose):
cmd= Twist()
if pose.x>9.0 or pose.x<2.0 or pose.y>9.0 or pose.y<2.0:
cmd.linear.x=1.0
cmd.angular.z=1.4
else:
cmd.linear.x=5.0
cmd.angular.z=0.0
pub.publish(cmd)
global previous_x
if pose.x>=5.5 and previous_x<5.5:
rospy.loginfo("set color to red")
call_set_pen_service(255,0,0,3,0)
elif pose.x<5.5 and previous_x>=5.5:
rospy.loginfo("set color to green")
call_set_pen_service(0,255,0,3,0)
previous_x=pose.x
if __name__=='__main__':
rospy.init_node("turtle_controller")
rospy.wait_for_service("/turtle1/set_pen")
pub=rospy.Publisher("/turtle1/cmd_vel",Twist,queue_size=10)
sub= rospy.Subscriber("/turtle1/pose",Pose,callback=pose_callback)
rospy.loginfo("Node has been started")
rospy.spin()