-
Notifications
You must be signed in to change notification settings - Fork 84
/
r2moverotate.py
209 lines (179 loc) · 7.48 KB
/
r2moverotate.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# Copyright 2016 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# adapted from https://github.com/Shashika007/teleop_twist_keyboard_ros2/blob/foxy/teleop_twist_keyboard_trio/teleop_keyboard.py
import rclpy
from rclpy.node import Node
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist
import math
import cmath
import numpy as np
# constants
rotatechange = 0.1
speedchange = 0.05
# code from https://automaticaddison.com/how-to-convert-a-quaternion-into-euler-angles-in-python/
def euler_from_quaternion(x, y, z, w):
"""
Convert a quaternion into euler angles (roll, pitch, yaw)
roll is rotation around x in radians (counterclockwise)
pitch is rotation around y in radians (counterclockwise)
yaw is rotation around z in radians (counterclockwise)
"""
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + y * y)
roll_x = math.atan2(t0, t1)
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
pitch_y = math.asin(t2)
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 - 2.0 * (y * y + z * z)
yaw_z = math.atan2(t3, t4)
return roll_x, pitch_y, yaw_z # in radians
# function to check if keyboard input is a number as
# isnumeric does not handle negative numbers
def isnumber(value):
try:
int(value)
return True
except ValueError:
return False
# class for moving and rotating robot
class Mover(Node):
def __init__(self):
super().__init__('moverotate')
self.publisher_ = self.create_publisher(Twist,'cmd_vel',10)
# self.get_logger().info('Created publisher')
self.subscription = self.create_subscription(
Odometry,
'odom',
self.odom_callback,
10)
# self.get_logger().info('Created subscriber')
self.subscription # prevent unused variable warning
# initialize variables
self.roll = 0
self.pitch = 0
self.yaw = 0
# function to set the class variables using the odometry information
def odom_callback(self, msg):
# self.get_logger().info(msg)
# self.get_logger().info('In odom_callback')
orientation_quat = msg.pose.pose.orientation
self.roll, self.pitch, self.yaw = euler_from_quaternion(orientation_quat.x, orientation_quat.y, orientation_quat.z, orientation_quat.w)
# function to rotate the TurtleBot
def rotatebot(self, rot_angle):
# self.get_logger().info('In rotatebot')
# create Twist object
twist = Twist()
# get current yaw angle
current_yaw = self.yaw
# log the info
self.get_logger().info('Current: %f' % math.degrees(current_yaw))
# we are going to use complex numbers to avoid problems when the angles go from
# 360 to 0, or from -180 to 180
c_yaw = complex(math.cos(current_yaw),math.sin(current_yaw))
# calculate desired yaw
target_yaw = current_yaw + math.radians(rot_angle)
# convert to complex notation
c_target_yaw = complex(math.cos(target_yaw),math.sin(target_yaw))
self.get_logger().info('Desired: %f' % math.degrees(cmath.phase(c_target_yaw)))
# divide the two complex numbers to get the change in direction
c_change = c_target_yaw / c_yaw
# get the sign of the imaginary component to figure out which way we have to turn
c_change_dir = np.sign(c_change.imag)
# set linear speed to zero so the TurtleBot rotates on the spot
twist.linear.x = 0.0
# set the direction to rotate
twist.angular.z = c_change_dir * speedchange
# start rotation
self.publisher_.publish(twist)
# we will use the c_dir_diff variable to see if we can stop rotating
c_dir_diff = c_change_dir
# self.get_logger().info('c_change_dir: %f c_dir_diff: %f' % (c_change_dir, c_dir_diff))
# if the rotation direction was 1.0, then we will want to stop when the c_dir_diff
# becomes -1.0, and vice versa
while(c_change_dir * c_dir_diff > 0):
# allow the callback functions to run
rclpy.spin_once(self)
current_yaw = self.yaw
# convert the current yaw to complex form
c_yaw = complex(math.cos(current_yaw),math.sin(current_yaw))
self.get_logger().info('Current Yaw: %f' % math.degrees(current_yaw))
# get difference in angle between current and target
c_change = c_target_yaw / c_yaw
# get the sign to see if we can stop
c_dir_diff = np.sign(c_change.imag)
# self.get_logger().info('c_change_dir: %f c_dir_diff: %f' % (c_change_dir, c_dir_diff))
self.get_logger().info('End Yaw: %f' % math.degrees(current_yaw))
# set the rotation speed to 0
twist.angular.z = 0.0
# stop the rotation
self.publisher_.publish(twist)
# function to read keyboard input
def readKey(self):
twist = Twist()
try:
while True:
# get keyboard input
cmd_char = str(input("Keys w/x/a/d -/+int s: "))
# use our own function isnumber as isnumeric
# does not handle negative numbers
if isnumber(cmd_char):
# rotate by specified angle
self.rotatebot(int(cmd_char))
else:
# check which key was entered
if cmd_char == 's':
# stop moving
twist.linear.x = 0.0
twist.angular.z = 0.0
elif cmd_char == 'w':
# move forward
twist.linear.x += speedchange
twist.angular.z = 0.0
elif cmd_char == 'x':
# move backward
twist.linear.x -= speedchange
twist.angular.z = 0.0
elif cmd_char == 'a':
# turn counter-clockwise
twist.linear.x = 0.0
twist.angular.z += rotatechange
elif cmd_char == 'd':
# turn clockwise
twist.linear.x = 0.0
twist.angular.z -= rotatechange
# start the movement
self.publisher_.publish(twist)
except Exception as e:
print(e)
# Ctrl-c detected
finally:
# stop moving
twist.linear.x = 0.0
twist.angular.z = 0.0
self.publisher_.publish(twist)
def main(args=None):
rclpy.init(args=args)
mover = Mover()
mover.readKey()
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
mover.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()