ROS中使用串口

一. 移植c++ boost 库:

1.Boost官网 下载Boost

2.解压后,进入目录: cd boost_1_6_0,

执行:
$ ./bootstrap.sh --prefix=path/to/installation/prefix
prefix 的值是你希望安装boost的路径, 不开启此参数的话默认安装在 /usr/local 下.

Note: 家目录不要用 ~ 表示, 编译脚本不识别 ~, 会在当前目前新建一个名为 '~' 的目录.

执行:
$ ./b2 install
这条命令把boost的头文件文件夹 include/ 安装在prefix定义的目录中, 并且会编译所有的boost模块, 并将编译好的库文件夹 lib/ 也放在prefix定义的目录中.
 如果成功编译的的话, prefix目录即 /home/xzz/boost_1_56_0目录应当包含有 include/ 和 lib/ 两个文件夹.

二. 测试

1.ros工作空间/包/src/ 创建boost_bode.cpp文件:

#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>

using namespace std;
using namespace boost::asio;

int main(int argc, char* argv[])
{
        io_service iosev;
        //节点文件
        serial_port sp(iosev, "/dev/ttyUSB0");
        // 设置参数
        sp.set_option(serial_port::baud_rate(115200));
        sp.set_option(serial_port::flow_control(serial_port::flow_control::none));
        sp.set_option(serial_port::parity(serial_port::parity::none));
        sp.set_option(serial_port::stop_bits(serial_port::stop_bits::one));
        sp.set_option(serial_port::character_size(8));
        // 向串口写数据
        write(sp, buffer("Hello world", 12));

        // 向串口读数据
        char buf[1];
        read(sp, buffer(buf));
    printf("buf[0] = %c\n",buf[0]);

        iosev.run();
        return 0;
}
ASIO不仅支持网络通信,还能支持串口通信。

ASIO提供了boost::asio::serial_port类,它的set_option(const SettableSerialPortOption& option)方法用于设置串口参数:

serial_port::baud_rate 波特率,构造参数为unsigned int
serial_port::parity 奇偶校验,构造参数为serial_port::parity::type,enum类型,可以是none, odd, even。
serial_port::flow_control流量控制,构造参数为serial_port::flow_control::type,enum类型,可以是none software hardware
serial_port::stop_bits 停止位,构造参数为serial_port::stop_bits::type,enum类型,可以是one onepointfive two
serial_port::character_size 字符大小,构造参数为unsigned in

2.添加编译选项:
在 工作空间/src/包/ CMakeLists.txt 文件中添加:
add_executable(boost_node src/boost_node.cpp)
target_link_libraries(boost_node ${catkin_LIBRARIES})

3.编译:
进入工作空间:
执行:
catkin_make

备注:如果出现错误提示:

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)

权限不够:执行:sudo chmod 666 /dev/ttyUSB0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值