本文共 2114 字,大约阅读时间需要 7 分钟。
摘自:
2019-05-20 10:54:25 6915
分类专栏:
版权
一、Ubuntu下的串口助手cutecom
1.安装cutecom并打开:
sudo apt-get install cutecomsudo cutecom
2.查看电脑链接的串口信息(名称):
dmesg | grep ttyS*
二、使用ROS提供的serial包实现串口通信
1.首先,下载serial软件包:
sudo apt-get install ros-kinetic-serial #ros为Kinect版本
2.进入下载的软件包的位置
roscd serial
若是安装成功会看到:
$:/opt/ros/kinetic/share/serial
3.新建catkin_ws
见我另外一篇博客
4.在src目录中编写串口通信的代码
//serial_port.cpp#include#include #include int main(int argc, char** argv){ ros::init(argc, argv, "serial_port"); //创建句柄(虽然后面没用到这个句柄,但如果不创建,运行时进程会出错) ros::NodeHandle n; //创建一个serial类 serial::Serial sp; //创建timeout serial::Timeout to = serial::Timeout::simpleTimeout(100); //设置要打开的串口名称 sp.setPort("/dev/ttyUSB0"); //设置串口通信的波特率 sp.setBaudrate(115200); //串口设置timeout sp.setTimeout(to); try { //打开串口 sp.open(); } catch(serial::IOException& e) { ROS_ERROR_STREAM("Unable to open port."); return -1; } //判断串口是否打开成功 if(sp.isOpen()) { ROS_INFO_STREAM("/dev/ttyUSB0 is opened."); } else { return -1; } ros::Rate loop_rate(500); while(ros::ok()) { //获取缓冲区内的字节数 size_t n = sp.available(); if(n!=0) { uint8_t buffer[1024]; //读出数据 n = sp.read(buffer, n); for(int i=0; i
连接串口设备,通过第一部分给出的查看电脑连接串口号,更改上述程序中的ser.setPort("/dev/ttyUSB0");
5.更改CMakeList.txt文件,添加如下两行:
add_executable(serial_port src/serial_port.cpp)add_dependencies(serial_port ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})target_link_libraries(serial_port ${catkin_LIBRARIES})
6.权限问题
运行roscore,运行节点看是否能打开串口。如果提示Unable to open port,是由于权限不够引起的,进行如下操作
创建文件:(若使用的是ttyACM将ttyusb替换即可)sudo gedit /etc/udev/rules.d/70-ttyusb.rules
在打开的文件中添加
KERNEL=="ttyUSB[0-9]*", MODE="0666"
转载地址:http://gxlni.baihongyu.com/