ros2+UBUNTU读取STM32发送过来的数据(C++)

ATTENTION:一般ros2上位机访问STM32不是使用串口,即使树莓派有串口,我也不会用的,因为那还要去学习其他的语言,一般就是ros2---------ubs转串口-------STM32串口。

这个USB转串口,我们已经安装了CH340驱动了,所以就可以使用C++里面的IO库去直接打开,读取USB口的内容。这个IO库指的就是#include<fstream>或者#include<iostream>这些常用IO库,很高兴不用再多去学习其他的库。

cpp 复制代码
std::string str; 
fstream f; 
f.open("/dev/ttyS0"); 
while (f >> str)
{
   cout << str;
}

以下内容都是转载的,那个谁使用的环境为Ubuntu,在windows系统中使用需要对应把ttyUSB转换为COM口.

cpp 复制代码
/*boost*/
#include<boost/asio.hpp>
#include<boost/bind.hpp>


boost::asio::io_service io;
boost::asio::serial_port sp(io, serial_port);
sp.set_option( boost::asio::serial_port::baud_rate(baud_rate));
sp.set_option( boost::asio::serial_port::flow_control( boost::asio::serial_port::flow_control::none ) );
sp.set_option( boost::asio::serial_port::parity( boost::asio::serial_port::parity::none ) );
sp.set_option( boost::asio::serial_port::stop_bits( boost::asio::serial_port::stop_bits::one ) );
sp.set_option( boost::asio::serial_port::character_size( 8 ) );

// 读取数据
char read_once[1]={'\0'};
boost::asio::read(sp,boost::asio::buffer(read_once));

// 写出数据
boost::asio::write(sp,boost::asio::buffer(buff,buff_len));

windows下的c++串口读取c++ 读取window下的USB输入数据 及 linux下的USB读取 - 大G霸 - 博客园 (cnblogs.com)

在windows下读取USB的做法就是使用 window.h文件。

使用CSerialPort类的 windows.h读取方式。这里附上SerialPort.h

+ View Code

对应的SerialPort.cpp

+ View Code

最后,我们的main程序。

复制代码
#include "stdafx.h"

#include <windows.h>
#include <iostream>
#include <string>
#include "SerialPort.h"

using namespace std;

int port;
CSerialPort mySerialPort;

void PortOpen() {
    cout << "Please insert your port number : " << endl;
    cin >> port;

    if (!mySerialPort.InitPort(port, 9600, 'N', 8, 1, EV_RXCHAR))
    {
        std::cout << "initPort fail !" << std::endl;
        PortOpen();
    }
    else
    {
        std::cout << "initPort success !" << std::endl;
    }
}

int main()
{
    PortOpen();
    if (!mySerialPort.OpenListenThread()){
        std::cout << "OpenListenThread fail !" << std::endl;
    }
    else {
        std::cout << "OpenListenThread success !" << std::endl;
    }

    while (1) 
    {
            UINT BytesInQue = mySerialPort.GetBytesInCOM();
    }

    Sleep(1000);
    return 0;
}

运行结果如下

相关推荐
虾球xz几秒前
CppCon 2015 学习:Give me fifteen minutes and I’ll change your view of GDB
开发语言·c++·学习
钓鱼的肝25 分钟前
题单:归并排序
c++·算法
随意0231 小时前
STL 6分配器
开发语言·c++
jndingxin2 小时前
c++ 面试题(1)-----深度优先搜索(DFS)实现
c++·算法·深度优先
hlpinghcg2 小时前
CanFestival移植到STM32G4
stm32·canopen
Watink Cpper2 小时前
[灵感源于算法] 算法问题的优雅解法
linux·开发语言·数据结构·c++·算法·leetcode
老一岁2 小时前
C++ 类与对象的基本概念和使用
java·开发语言·c++
随意0232 小时前
STL 3算法
开发语言·c++·算法
偷懒下载原神2 小时前
《C++ 继承》
开发语言·c++
随意0232 小时前
STL 4函数对象
开发语言·c++