ROS(drone포함)

[rospy 튜토리얼] catkin + rospy 사용법(1/2)

728x90

아니 rospy로 line following 하는 동영상이 급 비공개가 되는 바람에 다른 튜토리얼을 검색했다.

튜토리얼 깃주소는 아래 출처에. 정말 상세히 써놓으셨다.

 

패키지 생성

$ cd ~/catkin_ws/src

$ catkin_create_pkg rospy_tutorial geometry_msgs rospy

 

package.xml 파일과 CMakeList.txt 파일 편집

package.xml파일에는 아래의 내용이 있어야 한다.

<buildtool_depend>catkin</buildtool_depend>

CMakeList.txt파일에는 최소한 아래의 내용이 있어야함.

cmake_minimum_required(VERSION 2.8.3)
project(rospy_tutorial)

find_package(catkin REQUIRED COMPONENTS std_msgs rospy)
catkin_package()

 

튜토리얼에는 script폴더를 만들어서 수행한다고 하는데 저는 src폴더에서 했습니다

 

$ gedit move_turtlesim.py

#!/usr/bin/env python
# 위 첫 행은 이 스크립트 파일의 해석기의 위치를 지정하는 셔뱅(Shebang)이다. 파이썬으로 ROS 노드를 작성하는 
# 경우, 반드시 첫 행에 이 셔뱅(Shebang)을 적어 주어야만 한다.

import rospy                # roscpp 코드의 "#include <ros.h>"에 해당하는 구문
import geometry_msgs.msg    # ROS 메세지 중 geometry_msg 모듈 import
                            # roscpp 코드라면 "#include <geometry_msgs/Twist.h>"에 해당
def move_turtle():          # move_turtle() 함수 사용자 정의 시작
    
    # 노드명 "move_turtlesim" 노드 초기화. roscpp의 'ros::init(argc, argv, "move_turtlesim");'
    rospy.init_node("move_turtlesim")
    
    # 토픽명:"turtle1/cmd_vel", 토픽타입:geometry_msgs.msg.Twist 인 퍼블리셔 'pub' 선언
    pb = rospy.Publisher("turtle1/cmd_vel", geometry_msgs.msg.Twist, queue_size=10)
    
    # geometry_msgs 메세지 중 Twist 메세지 객체 "tw" 선언
    tw  = geometry_msgs.msg.Twist()
    
    # tw메세지 객체 맴버 "linear.x"를 0.25(m/sec)로, "angular.z"를 0.25(rad/sec)로 설정
    tw.linear.x = tw.angular.z = 0.25
    
    # tw 메세지 퍼블리쉬
    pb.publish(tw)

# 실행 중인 이 모듈의 __name__ 변수 값이 '__main__'이면 다음 내용 실행
if __name__ == '__main__':
    # rospy가 종료되지 않았으면 반복할 루프. roscpp의 "while(ros::ok())"에 해당.
    while not rospy.is_shutdown():
        move_turtle()		# 앞 서 정의한 move_turtle()함수 호출

설명이 너무 잘되어있다. 진짜 너무 감사하다.

 

스크립트를 확인한다.

$ ls *.py -al
-rw-rw-r-- 1 user user  453  9월 21 10:55 move_turtlesim.py

작성한 스크립트에 실행 속성을 부여

$ chmod +x move_turtlesim.py

결과 확인

$ ls *.py -al
-rwxrwxr-x 1 user user  453  9월 21 10:55 move_turtlesim.py

폴더의 속성이 변경된 것을 볼 수 있다.

 

(폴더 속성에 대한 개념 정리 블로그)

https://sswpgm.tistory.com/11

 

[유닉스/리눅스 기초]파일 속성 및 접근 권한

<파일의 속성> 파일 속성 값 출력 : ls -l ex: -rw-r--r-- 1 user1 staff 13 Jun 17 11:29 test.txt - : 파일종류(일반파일 : -, 디렉토리 : d) rw-r--r-- : 파일 접근 권한 1 : 하드링크 수 user1 : 파일 소유자..

sswpgm.tistory.com

빌드 실행 (cm)

$ cd ~/catkin_ws

$ catkin_make

 

빌드 성공시 ~/catkin_ws/devel/setup.bash 파일의 변경사항을 source 명령으로 반영

$ source ./devel/setup.bash

 

 

실행.

roscore

rosrun turtlesim turtlesim_node

rosrun rospy_tutorial move_turtlesim.py

계속도는 친구.

*나의 시행착오

어제 유튜브를 보고 따라하면서 Twist를 따로 import하면 되는걸 왜 저렇게 하지? 라는 생각이 들어 내식대로 변경해봤다.ㅋㅋㅋㅋ

#!/usr/bin/env python

import rospy
import geometry_msgs.msg
from geometry_msgs.msg import Twist

def move_turtle():
    rospy.init_node("move_turtlesim")
    pb = rospy.Publisher("turtle1/cmd_vel", Twist, queue_size=10)
    Twist.linear.x = Twist.angular.z=0.25
    pb.publish(Twist)

if __name__=="__main__":
    try:
        while not rospy.is_shutdown():
            move_turtle()
    except rospy.ROSInterruptException:
        pass

이러니까 linear에 x가 없다며 문제가 발생하였고, 튜토리얼의 코드로 다시 바꾸고 나서야 정확하게 실행이 되었다.

 

감사하게도 다른 코드로도 작성해 주셨다.

#!/usr/bin/env python

import rospy
import geometry_msgs.msg

try:
    while not rospy.is_shutdown():
        rospy.init_node("move_turtle")
        pb = rospy.Publisher("turtle1/cmd_vel", geometry_msgs.msg.Twist, queue_size=10)
        tw  = geometry_msgs.msg.Twist()
        tw.linear.x = tw.angular.z = 0.25
        pb.publish(tw)
            
except rospy.ROSInterruptException:
    pass
5.2 main함수를 이용한 파이썬 스크립트
move_turtlesim_2.py

#!/usr/bin/env python

import rospy
import geometry_msgs.msg

if __name__ == '__main__':
    try:
        while not rospy.is_shutdown():
            rospy.init_node("move_turtle")
            pb = rospy.Publisher("turtle1/cmd_vel", geometry_msgs.msg.Twist, queue_size=10)
            tw  = geometry_msgs.msg.Twist()
            tw.linear.x = tw.angular.z = 0.25
            pb.publish(tw)
            
    except rospy.ROSInterruptException:
        pass
#!/usr/bin/env python

import rospy
import geometry_msgs.msg

def move_turtle():
    rospy.init_node("move_turtle")
    pb = rospy.Publisher("turtle1/cmd_vel", geometry_msgs.msg.Twist, queue_size=10)
    tw  = geometry_msgs.msg.Twist()
    tw.linear.x = tw.angular.z = 0.25
    pb.publish(tw)
   
if __name__ == '__main__':
    try:
        while not rospy.is_shutdown():
            move_turtle()
            
    except rospy.ROSInterruptException:
        pass
#!/usr/bin/env python

import rospy
import geometry_msgs.msg

class MoveTurtle():

    def __init__(self):
        rospy.init_node("move_turtle")
        self.pb= rospy.Publisher("turtle1/cmd_vel",geometry_msgs.msg.Twist,queue_size=10)
        self.tw = geometry_msgs.msg.Twist()
   
    def move_turtle(self):
        self.tw.linear.x = self.tw.angular.z = 0.25
        self.pb.publish(self.tw)

if __name__ == '__main__':
    try:
        x = MoveTurtle()
        while not rospy.is_shutdown():
            x.move_turtle
    except rospy.ROSInterruptException:
        pass

 

 

 

 

출처 - https://github.com/greattoe/ros_tutorial_kr/blob/master/ros1_tutorial/rospy/rospy_1_How2UsePythonWithCatkin_1.md

 

GitHub - greattoe/ros_tutorial_kr: ROS Tutorial which translated into Korean

ROS Tutorial which translated into Korean. Contribute to greattoe/ros_tutorial_kr development by creating an account on GitHub.

github.com

 

728x90