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

运行结果如下

相关推荐
鲁Q同志1 分钟前
VMware虚拟机安装Ubuntu22
ubuntu·vmware
实在太懒于是不想取名44 分钟前
STM32N6的开发日记(7):摄像头+NPU联动,完成 YOLO 实时目标检测与显示
stm32·嵌入式硬件·yolo
CoderCodingNo1 小时前
【信奥业余科普】C++ 的奇妙之旅 | 12:程序的交互与加工——数据的输入与算术运算
开发语言·c++
yx868xy1 小时前
Cuda加速直线拟合
c++·cuda
Joseph Cooper1 小时前
STM32MP157 Linux驱动学习笔记(四):典型总线与设备模型(SPI/USB)
linux·stm32·学习
蜗牛在听雨1 小时前
基于 C++ 的 UG/NX 二次开发环境配置
c++·二次开发·ug
SimpleLearingAI2 小时前
C++虚函数详解
开发语言·c++
小柯博客2 小时前
STM32MP2安全启动技术深度解析
c语言·c++·stm32·嵌入式硬件·安全·开源·github
cpp_25012 小时前
P1832 A+B Problem(再升级)
数据结构·c++·算法·动态规划·题解·洛谷·背包dp
结衣结衣.3 小时前
手把手教你实现文档搜索引擎
linux·c++·搜索引擎·开源·c++11