最近又需要Windows下的串口,为了体验一下造轮子的乐趣,自己又写了一个串口类。
头文件:
#ifndef MYSERIAL_H
#define MYSERIAL_H
#include <Windows.h>
#include <iostream>
#include <thread>
class MySerial
{
public:
MySerial():hCom(INVALID_HANDLE_VALUE),listenThreadClose(false)
{}
~MySerial()
{
std::cout << "已调用析构函数" << std::endl;
CloseHandle(hCom);
listenThreadClose = true;
Sleep(10);
}
const int ESC = 27;
const int SPACE = 16;
int open(int com_num, int input_buffer = 1024, int ouput_buffer = 1024, int baud = 115200,
int byte_size = 8,int parity = 0, int stopbits = 0);
int auto_open(int input_buffer = 1024, int ouput_buffer = 1024, int baud = 115200,
int byte_size = 8,int parity = 0, int stopbits = 0);
int send(unsigned char *send_buf,unsigned long data_len) const;
void openListenThread();
void receive(const int data_len);
private:
HANDLE hCom;
std::thread::id listenThreadID;
bool listenThreadClose;
int init(int input_buffer, int ouput_buffer, int baud,
int byte_size,int parity, int stopbits) const;
int open_file(LPCWSTR file_name, int input_buffer, int ouput_buffer, int baud,
int byte_size, int parity, int stopbits);
};
#endif
cpp:
//c++标准库
#include <iostream>
#include <sstream>
#include <string>
#include <thread>
//windows平台库
#include <Windows.h>
#include <conio.h> //获取键盘操作
//用户头文件
#include "mySerial.h"
using namespace std;
/*************************************************
* 函数名称 : open_file
* 函数功能 : 打开指定的串口并初始化
* 形参 : file_name 串口号
input_buffer 接收缓冲区 默认1024
ouput_buffer 发送缓冲区 默认1024
baud 波特率 默认115200
byte_size 字节长 默认8
parity 检验位 默认无
stopbits 停止位 默认1
* 返回值 : 0 成功
-1 失败
****************************************************/
int MySerial::open_file(LPCWSTR file_name, int input_buffer, int ouput_buffer, int baud,
int byte_size, int parity, int stopbits)
{
hCom = CreateFile(file_name, GENERIC_READ | GENERIC_WRITE, //允许读写
0, //此项必须为0
NULL, //no security attrs
OPEN_EXISTING, //设置产生方式
FILE_FLAG_OVERLAPPED, //异步通信 FILE_FLAG_OVERLAPP