欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

c++串口使用类

程序员文章站 2022-07-03 21:02:07
使用例子 1 #include"ComHandle.h" ......
  1 #ifndef  _COMHANDLE_H_
  2 #define  _COMHANDLE_H_
  3 #endif
  4 #include<string>
  5 #include<windows.h>
  6 using namespace std;
  7 
  8 //string转LPCWSTR
  9 LPCWSTR stringToLPCWSTR(std::string orig)
 10 {
 11     size_t origsize = orig.length() + 1;
 12     const size_t newsize = 100;
 13     size_t convertedChars = 0;
 14     wchar_t *wcstring = (wchar_t *)malloc(sizeof(wchar_t)*(orig.length() - 1));
 15     mbstowcs_s(&convertedChars, wcstring, origsize, orig.c_str(), _TRUNCATE);
 16     return wcstring;
 17 }
 18 /////////////////////////
 19 //ComHandle.h
 20 //串口收发
 21 /////////////////////////
 22 #pragma once
 23 
 24 class COM
 25 {
 26 public:
 27     void Send(string str);
 28     void Receieve();
 29     static void GetCom();
 30     COM(unsigned int Com, unsigned int BaudRate, unsigned int ByteSize, BYTE StopBits, BYTE Parity);
 31     COM(unsigned int Com);
 32 private:
 33     HANDLE hcom;
 34 };
 35 
 36 //Com:端口号,如COM3
 37 COM::COM(unsigned int Com)
 38 {
 39     string str = "COM" + to_string(Com);  
 40     hcom = CreateFile(stringToLPCWSTR(str), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING
 41         , FILE_ATTRIBUTE_NORMAL, NULL);
 42     if (hcom == INVALID_HANDLE_VALUE)
 43     {
 44 
 45         printf("打开串口失败!\n");
 46         system("pause");
 47         exit(0);
 48     }
 49     SetupComm(hcom, 1024, 1024);
 50     DCB dcb;
 51     GetCommState(hcom, &dcb);
 52     dcb.BaudRate = 115200;
 53     dcb.ByteSize = 8;
 54     dcb.Parity = 0;
 55     dcb.StopBits = 1;
 56     SetCommState(hcom, &dcb);
 57 }
 58 
 59 
 60 //Com:端口号例如COM1;BaudRate:波特率;ByteSize:数据位;StopBits:停止位;Parity:奇偶校验
 61 COM::COM(unsigned int Com, unsigned int BaudRate, unsigned int ByteSize, BYTE StopBits, BYTE Parity)
 62 {
 63     string str = "COM" + to_string(Com);
 64     hcom = CreateFile(stringToLPCWSTR(str), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING
 65            , FILE_ATTRIBUTE_NORMAL, NULL);
 66     if (hcom == INVALID_HANDLE_VALUE)
 67     {
 68 
 69         printf("打开串口失败!\n");
 70         system("pause");
 71         exit(0);
 72     }
 73     SetupComm(hcom, 1024, 1024);
 74     DCB dcb;
 75     GetCommState(hcom, &dcb);
 76     dcb.BaudRate = BaudRate;
 77     dcb.ByteSize = ByteSize;
 78     dcb.Parity = Parity;
 79     dcb.StopBits = StopBits;
 80     SetCommState(hcom, &dcb);
 81 }
 82 
 83 //发送数据
 84 void COM::Send(string str)
 85 {
 86     string Message = str;
 87     //string Message = "dj1mcs(2,1)";
 88     string Wrap = Message + "\r\n";
 89     const char* data = Wrap.data();
 90     DWORD dwWrittenLen = 0;
 91     if (!WriteFile(hcom, data, strlen(data), &dwWrittenLen, NULL))
 92     {
 93         printf("发送数据失败!\n");
 94     }
 95     printf("往串口发送数据成功!");
 96 
 97 }
 98 
 99 
100 //接收数据
101 void COM::Receieve()
102 {
103     Sleep(500);
104     char Receive[1024] = {};
105     DWORD wCount;//读取的字节数 
106     BOOL bReadStat;
107     bReadStat = ReadFile(hcom, Receive, 1024, &wCount, NULL);
108     if (!bReadStat)
109     {
110         printf("读串口失败!");
111 
112     }
113     else
114     {
115         printf(Receive);
116         printf("\n");
117     }
118 
119 }
120 //获取端口状态
121 void COM::GetCom()
122 {
123     HANDLE hcom;
124     //默认检测COM端口的返回值
125     hcom = INVALID_HANDLE_VALUE;
126     BOOL ret = false;
127     //逐一进行COM   端口检测
128     for (int i = 1; i <= 32; i++)
129     {
130 
131         string   comname = "COM" + to_string(i);
132         //打开COM端口,并返回检测值
133         hcom = CreateFileA(comname.c_str(),     // 打开串口
134             GENERIC_READ | GENERIC_WRITE,  //读写方式
135             0, //不能共享
136             NULL, //安全属性,一般不用设为NULL
137             OPEN_EXISTING,   //打开已存在的设备
138             FILE_ATTRIBUTE_NORMAL,  //普通文件属性
139             0);       //无模板
140         //若无法打开指定COM端口
141         if (hcom == INVALID_HANDLE_VALUE)
142         {
143 
144             //取得错误信息
145             DWORD   err = ::GetLastError();
146             //若   err   为   2   ,即此COM端口尚未安装
147             if (err != 2)
148             {
149                 printf("端口%d未安装", i);
150             }
151         }
152         else
153         {
154             printf("端口%d正常\n", i);
155             ret = CloseHandle(hcom);
156             if (!ret)
157             {
158                 // TRACE("CLOSE_PORT_FAIL\n");
159                 printf("关闭串口失败!!");
160             }
161             //else
162             //{
163             //    printf("success");
164             //}
165         }
166 
167     }
168 }

使用例子 1 #include"ComHandle.h"

 2 using namespace std;
 3 
 4 
 5 
 6 int main()
 7 {
 8     COM::GetCom();  //查看端口状态
 9     unsigned int com = 0;10     string str = {};
11     cout << "请输入端口号:";
12     cin >> com;
13     COM com1(com);
14     cout << "请输入要发送的命令,输入list获取命令列表\n";
15     while (1)
16     {
17         cin >> str;
18         com1.Send(str);
19         com1.Receieve();
20     }
21     
22     system("pause");
23     return 0;
24 }