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;
}

运行结果如下

相关推荐
Jacen.L1 分钟前
SIGABRT (6) 中止信号详解
c++
习惯就好zz13 分钟前
在 Ubuntu 18.04 旧系统上部署新版 GitHub Actions Runner 的终极方案
linux·ubuntu·github·cicd·action
王老师青少年编程22 分钟前
信奥赛C++提高组csp-s之并查集(案例实践)2
数据结构·c++·并查集·csp·信奥赛·csp-s·提高组
白驹过隙^^34 分钟前
VitrualBox及ubuntu系统安装
linux·运维·ubuntu
PoppyBu36 分钟前
Ubuntu20.04版本上安装最新版本的scrcpy工具
android·ubuntu
满天星83035771 小时前
【C++】特殊类设计
c++·windows
烤鱼骑不快1 小时前
ubuntu系统安装以及设置
linux·数据库·ubuntu
Ljubim.te1 小时前
inline介绍,宏定义的注意事项以及nullptr
c语言·开发语言·c++
HIT_Weston1 小时前
89、【Ubuntu】【Hugo】搭建私人博客:侧边导航栏(三)
linux·运维·ubuntu
苦藤新鸡1 小时前
6.三数之和
c语言·c++·算法·力扣