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

运行结果如下

相关推荐
HL_LOVE_C1 分钟前
全面理解-回调函数CallBack
开发语言·c++
橘猫0.o10 分钟前
【STM32】内存管理
stm32·单片机·嵌入式硬件
深图智能18 分钟前
VS2022配置FFMPEG库基础教程
c++·计算机视觉·ffmpeg
楼台的春风3 小时前
【STM32 基于PID的闭环电机控制系统】
c语言·stm32·单片机·嵌入式硬件·mcu·物联网·算法
stm32发烧友3 小时前
基于STM32的智能电力监测与需求响应系统
stm32·单片机·嵌入式硬件
柠石榴4 小时前
【练习】【类似于子集问题】力扣491. 非递减子序列/递增子序列
c++·算法·leetcode·回溯
Ronin-Lotus4 小时前
程序代码篇---C/C++中的变量存储位置
c语言·c++···静态区·文字常量区·变量存储位置
人间打气筒(Ada)4 小时前
ubuntu网络及软件包管理
网络·ubuntu·php
Abdullah al-Sa4 小时前
Docker教程(喂饭级!)
c++·人工智能·docker·容器
进击的_鹏4 小时前
【C++】list 链表的使用+模拟实现
开发语言·c++·链表