在C下,可以使用outportb和inportb进行串口通讯,C++没有这两个函数,那就使用createfile吧
通过网上搜到读取打开串口的例子,如下:
#include<windows.h>
int main()
{
HANDLE hCom=CreateFile("COM1",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
}
发现报错:argument of type “char *” is incompatible with parameter of type “LPCWSTR”
原理是编码格式的问题,通过修改解决问题,代码如下:
#include<windows.h>
#include<tchar.h>
int main()
{
HANDLE hComm;
hComm=CreateFile(_T("COM1"), //串口号
GENERIC_READ|GENERIC_WRITE, //允许读写
0, //通讯设备必须以独占方式打开
NULL, //无安全属性
OPEN_EXISTING, //通讯设备已存在
FILE_FLAG_OVERLAPPED, //异步I/O
0); //通讯设备不能用模板打开
}
其他转换方法如下:
引入 #include<tchar.h>,才能使用TEXT等进行转换
LPCWSTR str1 = TEXT("Hello");
LPCWSTR str2 = L"Hello";
LPCWSTR str3 = _T("Hello"); //本文使用此方法
参考文献:错误argument of type “char *” is incompatible with parameter of type "LPCWSTR"的解决方法