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

运行结果如下

相关推荐
前进的程序员2 分钟前
C++ 在 Windows 和 Linux 平台上的开发差异及常见问题
linux·c++·windows
阿川!38 分钟前
嵌入式软件--stm32 DAY 6 USART串口通讯(下)
stm32·单片机·嵌入式硬件
daiwoliyunshang41 分钟前
哈希表实现(1):
数据结构·c++
pystraf1 小时前
模板分享:网络最小费用流
c++·算法·图论·网络流
thisiszdy1 小时前
<C++> MFC自动关闭对话框(MessageBoxTimeout)
c++·mfc
绯樱殇雪1 小时前
编程题 03-树2 List Leaves【PAT】
c++·pat考试
✿ ༺ ོIT技术༻2 小时前
笔试强训:Day5
c++·算法
努力的小帅2 小时前
C++_STL_map与set
开发语言·数据结构·c++·学习·leetcode·刷题
双叶8362 小时前
(C语言)超市管理系统 (正式版)(指针)(数据结构)(清屏操作)(文件读写)
c语言·开发语言·数据结构·c++·windows
繁星无法超越3 小时前
详解Windows(九)——系统性能优化
windows·stm32·性能优化