1 Introduction
Asio is a cross-platform C++ library, commonly used for network programming, low-level I/O programming, etc. (low-level I/O). Its structural framework As follows:
2 Using Asio
##2.1 Download
Asio library is divided into Boost version and non-Boost version. Please go to the official website to download.2.2 Configuration
1) Using Qt 5.9.1, add the following configuration to its .pro project file: NoteASIO_STANDALONE In the non-Boost version,
INCLUDEPATH += $$PWD/../../serialport/asio-1.10.8/includeDEFINES += ASIO_STANDALONE
ASIO_STANDALONE is configured as follows Shown:
2.3 Code example
The following is a simple serial communication example. The main steps are:Create Serial port --> Configuration parameters --> Read and write data --> Enable event loop
#include <functional>#include "asio.hpp"#include <QDebug>using namespace asio;// 存储接收到的数据char kBuf[16];// 声明回调函数void PrintBuf();int main() { // 串口 COM1 io_service iosev; serial_port port(iosev, "COM1"); // 参数设置:波特率、流控、奇偶校验、停止位、数据位 port.set_option(serial_port::baud_rate(115200)); port.set_option(serial_port::flow_control(serial_port::flow_control::none)); port.set_option(serial_port::parity(serial_port::parity::none)); port.set_option(serial_port::stop_bits(serial_port::stop_bits::one)); port.set_option(serial_port::character_size(8)); // 向串口写数据 write(port, buffer("Hello Asio", 16)); // 从串口读数据(异步) port.async_read_some(buffer(kBuf),std::bind(PrintBuf)); // 开启事件循环 iosev.run(); }// 打印接收的数据void PrintBuf() { qDebug() << kBuf; }
3 DB9 serial port
When running the above program, you will find a problem: the program first sends/writesto the serial port COM1, "Hello Asio" data, and then go to to receive/read data. For a serial port, the data will not be received.
On the back of the desktop computer, the DB9 serial port pin numbers are as follows: Among them, 2 --> RxD, is the pin for receiving data; 3 --> TxD, is the pin for sending data. In order for the above program to run successfully, you canshort pin 2 and pin 3 before running the program. In this way, you can both send and receive data
4 Virtual serial port
If you use a laptop, there is generally no serial port. In this case, there are two options: First, use theUSB to serial port data cable and install the corresponding driver, then you can communicate with the device with a serial port;
Second, useVirtual Serial Port Software to create a virtual serial port, for example, Configure Virtual Serial Port Driver
and withSerial Port Debugging Tool, you can flexibly Debugging the serial port program
The above is the detailed content of Asio library for C++. For more information, please follow other related articles on the PHP Chinese website!