[Robotics] Collabot 현업(2) [ROSpy publisher 만들어 보기]
현재 키높이 정보를 받아서 Publish 하는 코드를 짜야하지만
임시로 다음과 같이 200이하의 키가 인식되어서 publish 되는 코드를 짰다고 가정을 하였다
방법 1 (추천)
#!/usr/bin/env python
import rospy
from std_msgs.msg import Float32
from random import randint
#randint(start , stop ) start 이상 stop 이하 난 수 발생
def height_publisher():
pub = rospy.Publisher('height', Float32, queue_size=10)
rospy.init_node('height_publisher', anonymous=True)
rate = rospy.Rate(100) # 100hz
while not rospy.is_shutdown(): #-> c++에서 ros.ok() 느낌
rand_height = randint(70,200) #70cm ~ 200cm 사이의 사람의 키가 인식되었다고 가정
hello_str = str(rand_height)+"%s" % rospy.get_time()
rospy.loginfo(hello_str)
pub.publish(rand_height)
rate.sleep() #100hz가 될때 까지 쉬기
if __name__ == '__main__':
try:
height_publisher()
except rospy.ROSInterruptException:
pass
여기서 부터 새로 워크스페이스 부터 만들려고 하기 때문에
새로운 폴더 test_ros 디렉토리를 만들어 주고 환경설정을 진행하였다
여기서 문제가 발생하는데 왜 그런지는 아직 해결을 못했다
기존에 앞에서 말했던 방식대로 workspace와 package를 만들어보면
다음과 같은 오류가 나온다 자세히 과정을 적어보면
#디렉토리 만들기
mkdir -p catkin_ws2/src
cd catkin_ws2/src
#패키지 만들기
catkin_create_pkg height_pkg rospy std_msgs
cd height_pkg
ls
#CMakeLists.txt package.xml src <-파이썬이므로 include 없다
cd src
#소스코드 복붙하기
nano height_publish_example.py
#CMakelists.txt 수정
cd ../
#아래의 CMakeList.txt 부분 붙이기
nano CMakeLists.txt
#workspace 디렉토리로 이동
cd ../../
catkin_make
<CMakeLists.txt>
## Your package locations should be listed before other locations
include_directories(
# include
${catkin_INCLUDE_DIRS}
)
add_executable(height_publish_node src/height_publish_example.py)
target_link_libraries(height_publish_node ${catkin_LIBRARIES})
방법 2
예전에 다른 방법으로 package를 만들었어서 그것을 이용해 봤다
#workspace 만들기
mkdir -p ~/catkin_ws3/src
cd ~/catkin_ws3/src
catkin_init_workspace
#컨파일
cd ../
catkin_make
ls
#build devel src -> build , devel이 생긴 것을 볼 수 있다
#패키지 경로를 갱신해 주고
source devel/setup.bash
#ROS_PACKAGE_PATH에 갱신되었는지 확인
export |grep ROS
#패키지 만들기 -> 반드시 catkin_ws/src/ 에 만들어야 한다
cd src
roscreate-pkg height_pkg
#패키지에 접근 & 소스크드 만들기
roscd height_pkg
mkdir src
cd src
#위에 소스코드 그대로 복사
nano height_publish_example.py
#실행권한 부여
chmod +x height_publish_example.py
#새터미널
roscore
#기존 터미널
rosrun height_pkg height_publish_example.py
이렇게 하면 패키지 안에 CMakeLists.txt 도
GNU nano 4.8 CMakeLists.txt
cmake_minimum_required(VERSION 2.4.6)
include($ENV{ROS_ROOT}/core/rosbuild/rosbuild.cmake)
# Set the build type. Options are:
# Coverage : w/ debug symbols, w/o optimization, w/ code-coverage
# Debug : w/ debug symbols, w/o optimization
# Release : w/o debug symbols, w/ optimization
# RelWithDebInfo : w/ debug symbols, w/ optimization
# MinSizeRel : w/o debug symbols, w/ optimization, stripped binaries
#set(ROS_BUILD_TYPE RelWithDebInfo)
rosbuild_init()
#set the default path for built executables to the "bin" directory
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
#set the default path for built libraries to the "lib" directory
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)
#uncomment if you have defined messages
#rosbuild_genmsg()
#uncomment if you have defined services
#rosbuild_gensrv()
#common commands for building c++ executables and libraries
#rosbuild_add_library(${PROJECT_NAME} src/example.cpp)
#target_link_libraries(${PROJECT_NAME} another_library)
#rosbuild_add_boost_directories()
#rosbuild_link_boost(${PROJECT_NAME} thread)
#rosbuild_add_executable(example examples/example.cpp)
#target_link_libraries(example ${PROJECT_NAME})
깔끔하고 돌아가긴 한다.. 차이가 뭘까?
catkin_create_pkg vs roscreate-pkg
아래 공식문서에 질문을 참고하자
https://answers.ros.org/question/234311/catkin_create_pkg-or-roscreate-pkg/
catkin_create_pkg or roscreate-pkg? - ROS Answers: Open Source Q&A Forum
catkin_create_pkg or roscreate-pkg? edit Hello, I need to modify hector_slam for my situation. So i learned that i need to create/build a new package. So i want to create just like existing hector_slam package and modify it like i want. For creating new he
answers.ros.org
요약을 하자면 roscreate는 옛날 방식이고 catkin_create_pkg 가 요즘 방식이므로 catkin 쓰라고 한다
근데 왜 안되는데 ㅠㅠㅠ
Error shooting
이 상황에서 시작하겠다 (물론 블로그 끝에 해결할 수 있을지 모르겠음 -0> 언젠간 되겠지 라는 마인드)
에러 메세지를 보자
CMake Error: Cannot determine link language for target "height_publish_node".
CMake Error: CMake can not determine linker language for target: height_publish_node -- Generating done CMake Generate step failed. Build files cannot be regenerated correctly. Invoking "cmake" failed
이건 초등학생이 봐도 CMake가 문제가 있는 것이다
가장 첫번째로 공식 문서를 보자
http://wiki.ros.org/rospy_tutorials/Tutorials/Makefile
rospy_tutorials/Tutorials/Makefile - ROS Wiki
catkin rosbuild Note: This tutorial assumes that you have completed the previous tutorials: ROS tutorials. Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, t
wiki.ros.org
<package.xml 관련>
http://wiki.ros.org/ko/ROS/Tutorials/CreatingPackage
ko/ROS/Tutorials/CreatingPackage - ROS Wiki
roscreate 사용하기 본격적으로 패키지를 만들기 전에 roscreate-pkg 명령행 도구의 사용법을 알아봅시다. 모든 ROS 패키지들은 manifests, CMakeLists.txt, mainpage.dox, Makefiles 등 비슷한 파일들이 공통으로 들
wiki.ros.org
<CMakeLists.txt 관련>
http://wiki.ros.org/ko/ROS/Tutorials/BuildingPackages
ko/ROS/Tutorials/BuildingPackages - ROS Wiki
패키지 빌드 모든 시스템 의존성이 설치되었으면, 이제 우리가 만든 패키지를 빌드할 때 입니다. rosmake 사용하기 rosmake는 make 명령과는 조금 다른, ROS만의 특별한 마술을 수행합니다. 만약 rosmake
wiki.ros.org
먼어 CMake 프로젝트 에 대해서 설명을 한다
Catkin_make는
catkin을 이용한 도구로 서 cmake 와 make 가 합쳐진 도구하고 생각하면 된다
catkin_make 는 src 폴더를 찾아서 빌드릴 한다고 한다
(별로 도움은 안되었다)
1. package.xml 에 다음 문장이 있는지 확인
<buildtool_depend>catkin</buildtool_depend>
<build_depend>rospy</build_depend>
<build_depend>std_msgs</build_depend>
있다
2 CMakeLists.txt 에 다음 문장이 있는지 확인
cmake_minimum_required(VERSION 2.8.3)
project(my_pkg)
find_package(catkin REQUIRED COMPONENTS message_generation rospy ...)
catkin_package()
충격인것은 그냥 무시하고 했더니
source devel/setup.bash
#새 터미널
roscore
#기존 터미널
rosrun height_pkg height_publish_example.py
돌아간다.... 일단 무시하도록 하자
나중에 이것때문에 문제 되면 그때 해결할래 ...
잘 publish되고 있나 확인하면
rostopic list
rostopic info /height
rostopic echo /height
height topic이 잘 날라가고 있고
echo 해보면
잘 던져지고 있다
이제 Subscriber를 만들어 보자
<참고자료>
[ROS] 패키지 빌드와 노드 작성
ROS에서의 패키지 빌드와 노드 작성, 실행 과정
velog.io