Hi
I would like to read one of the sonars included in Magni Robot. I saw that not all the time I receive the correct data from the sonar. Here is my code:
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from geometry_msgs.msg import Pose
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Range
import math
import RPi.GPIO as GPIO
import time
from std_srvs.srv import Empty
def move(velocity_publisher, sensor_publisher, speed, distance, is_forward):
velocity_message = Twist()
sensor_message = Range()
global x
global y
global sens
x0=x
y0=y
if (is_forward)
velocity_message.linear.x = abs(speed)
else:
velocity_message.linear.x = -abs(speed)
distance_moved = 0.0
loop_rate = rospy.Rate(10)
while True:
rospy.loginfo(“Robot moves forwards”)
velocity_publisher.publish(velocity_message)
rospy.loginfo('Sensor 3: ')
sensor_publisher.publish(sensor_message)
loop_rate.sleep()
distance_moved = abs(math.sqrt(((x-x0) ** 2) + ((y-y0) ** 2)))
print(‘Print Distance Moved’,distance_moved)
print(‘X coordinate’,x)
print(‘Sensor 3 range’, sens)
if (distance_moved > distance):
rospy.loginfo(“reached”)
break
velocity_message.linear.x = 0
velocity_publisher.publish(velocity_message)
def poseCallback(pose_message):
global x
global y, yaw
x = pose_message.pose.pose.position.x
y = pose_message.pose.pose.position.y
yaw = pose_message.pose.pose.orientation.w
if name == ‘main’:
try:
rospy.init_node(‘turtlesim_motion_pose’, anonymous=True)
cmd_vel_topic = ‘/cmd_vel’
velocity_publisher = rospy.Publisher(cmd_vel_topic, Twist, queu$
position_topic = ‘/odom’
pose_subscriber = rospy.Subscriber(position_topic, Odometry, po$
sensor3_topic = ‘/pi_sonar/sonar_3’
sensor_publisher = rospy.Publisher(sensor3_topic, Range, queue_$
sensor_range3 = rospy.Subscriber(sensor3_topic, Range, sensorCa$
time.sleep(2)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.output(11, GPIO.LOW)
move(velocity_publisher, sensor_publisher, 0.2, 1, True)
GPIO.output(11, GPIO.HIGH)
time.sleep(5)
GPIO.output(11, GPIO.LOW)
move(velocity_publisher, sensor_publisher, 0.2, 1, False)
GPIO.output(11, GPIO.HIGH)
time.sleep(5)
GPIO.output(11, GPIO.LOW)
except rospy.ROSInterruptException:
rospy.loginfo(‘node_terminated.’)
Blockquote
Here is the result: