// boostSerialPort.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <boost/asio.hpp>
using namespace std;
//using namespace boost::asio;
int _tmain(int argc, _TCHAR* argv[])
{
try
{
boost::asio::io_service io;
boost::asio::serial_port sp(io,"COM2");
//设置串口参数
sp.set_option(boost::asio::serial_port::baud_rate(9600));
sp.set_option(boost::asio::serial_port::flow_control());
sp.set_option(boost::asio::serial_port::parity());
sp.set_option(boost::asio::serial_port::stop_bits());
sp.set_option(boost::asio::serial_port::character_size(8));
boost::system::error_code err;
while(true)
{
char buf[]="hello";
int nWrite = sp.write_some(boost::asio::buffer(buf),err);
if(err)
{
cout<<"write_some err,errmessage:"<<err.message()<<endl;
break;
}
else
{
char buf[1024];
sp.read_some(boost::asio::buffer(buf),err);
if(!err)
{
cout<<"recv data:"<<buf<<endl;
}
}
}
io.run();
}
catch (exception& err)
{
cout << "Exception Error: " << err.what() << endl;
}
return 0;
}
boost::asio::serial_port串口编程
最新推荐文章于 2026-04-04 10:18:39 发布
本文介绍了一个使用Boost库进行串口通信的C++示例程序。该程序通过Boost.Asio库实现了串口的基本读写操作,并设置了串口的各项参数如波特率等。

1万+

被折叠的 条评论
为什么被折叠?



