刚刚学习,望大神不吝赐教,主函数代码如下:
int main()
{
HANDLE hCom;
hCom = CreateFile(L"COM3",//COM1口
GENERIC_READ | GENERIC_WRITE, //允许读和写
0, //独占方式
NULL,
OPEN_EXISTING, //打开而不是创建
0, //同步方式
NULL);
if (hCom == (HANDLE)-1)
{
cout << "打开COM失败!"<<endl;
return FALSE;
}
else {
cout << "打开COM成功!"<<endl;
}
SetupComm(hCom, 1024, 1024);
DCB dcb;
GetCommState(hCom, &dcb);
dcb.BaudRate = 9600; //波特率为9600
dcb.ByteSize = 8; //每个字节有8位
dcb.Parity = NOPARITY; //无奇偶校验位
dcb.StopBits = TWOSTOPBITS; //两个停止位
SetCommState(hCom, &dcb);
char str[1000];
char dst[1000];
memset(str, '\0', 100);
DWORD wCount = 100;//读取的字节数
BOOL bReadStat;
bReadStat = ReadFile(hCom, str, wCount, &wCount, NULL);
if (!bReadStat) {
cout << "读串口失败!"<<endl;
}
else {
cout << "读串口成功!"<<endl;
}
Ascii2Hex(str,dst);
cout<< dst<<endl;
cout << "实际收到的数据个数:" <<dec<< wCount << '\n';
return 0;
}