Windows串口类

最近又需要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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值