摘自:https://blog.csdn.net/hengheng_51/article/details/79760096
ROS環境下序列槽通信
笑看零一 2018-03-31 13:53:37 8140 收藏 22
分類專欄: 機器人 ros學習 文章标簽: ROS 序列槽通信
版權
1. 環境:
- 作業系統: Ubuntu 14.04
- ROS版本: ROS Indigo
2. 步驟:
2.1 下載下傳安裝ROS對應版本的工具包(此處為indigo版)
- 輸入以下指令安裝:
sudo apt-get-install ros-indigo-serial
- 1
- 重新開機終端,輸入以下指令可以檢測到serial包的路徑說明已經安裝好:(路徑為 opt/ros/indigo/share/serial)
roscd serial
- 1
2.2 使用ros自帶的serial包,編寫節點
- 節點程式如下:
#include <ros/ros.h>
#include <serial/serial.h> //ROS已經内置了的序列槽包
#include <std_msgs/String.h>
#include <std_msgs/Empty.h>
serial::Serial ser; //聲明序列槽對象
//回調函數
void write_callback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO_STREAM("Writing to serial port" <<msg->data);
ser.write(msg->data); //發送序列槽資料
}
int main (int argc, char** argv)
{
//初始化節點
ros::init(argc, argv, "serial_example_node");
//聲明節點句柄
ros::NodeHandle nh;
//訂閱主題,并配置回調函數
ros::Subscriber write_sub = nh.subscribe("write", 1000, write_callback);
//釋出主題
ros::Publisher read_pub = nh.advertise<std_msgs::String>("read", 1000);
try
{
//設定序列槽屬性,并打開序列槽
ser.setPort("/dev/ttyUSB0");
ser.setBaudrate(115200);
serial::Timeout to = serial::Timeout::simpleTimeout(1000);
ser.setTimeout(to);
ser.open();
}
catch (serial::IOException& e)
{
ROS_ERROR_STREAM("Unable to open port ");
return -1;
}
//檢測序列槽是否已經打開,并給出提示資訊
if(ser.isOpen())
{
ROS_INFO_STREAM("Serial Port initialized");
}
else
{
return -1;
}
//指定循環的頻率
ros::Rate loop_rate(50);
while(ros::ok())
{
if(ser.available()){
ROS_INFO_STREAM("Reading from serial port\n");
std_msgs::String result;
result.data = ser.read(ser.available());
ROS_INFO_STREAM("Read: " << result.data);
read_pub.publish(result);
}
//處理ROS的資訊,比如訂閱消息,并調用回調函數
ros::spinOnce();
loop_rate.sleep();
}
}
- 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
3. 遇到問題
-如果出現如下錯誤,則是因為權限不夠引起的
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >'
what(): open: Permission denied
Aborted (core dumped)
- 1
- 2
- 3
-通過改變權限就能解決這個問題:
sudo chmod 666 /dev/ttyUSB0