从C中的串口读取,有ReadFile问题可能吗?

时间:2016-09-15 09:44:58

标签: c winapi serial-port readfile

好吧,我已经参加了这个计划大概四个小时了。我一直试图创建一个小程序来读取我的arduino Uno通过串口吐出的内容。

我觉得奇怪的是,该程序仅在我推出了arduino IDE的内置串行监视器之后才能工作。也许这是正确初始化端口的问题?

如果有人可以帮助我,我会非常感激。该程序似乎在ReadFile期间挂起,所以可能存在权限问题......

 

#include Windows.h> #include stdio.h> #include tchar.h>//Removed to allow for stackoverflow format void printCommState(DCB d); int main() { DCB dcb = { 0 }; HANDLE hPort; BOOL success; TCHAR *commPort = TEXT("COM3"); char buffer[40] = { 0 }; DWORD dwBytesRead = 0; DWORD dwBytesWrite = 0; int l; /*COMMTIMEOUTS cTimeOut; cTimeOut.ReadIntervalTimeout = 50; cTimeOut.ReadTotalTimeoutConstant = 50; cTimeOut.ReadTotalTimeoutMultiplier = 10; cTimeOut.WriteTotalTimeoutConstant = 50; cTimeOut.WriteTotalTimeoutMultiplier = 10;*/ dcb.DCBlength = sizeof(DCB); dcb.BaudRate = CBR_9600;//Found on microsofts website dcb.ByteSize = DATABITS_8;// standardized number? dcb.Parity = NOPARITY;// found in comp management dcb.StopBits = 1; /*dcb.fBinary = 1; dcb.fDtrControl = 1; dcb.fTXContinueOnXoff = 1; dcb.fRtsControl = 1; dcb.XonLim = 2048; dcb.XoffLim = 512; dcb.XoffChar = 2;*/ //dcb.fDtrControl = DTR_CONTROL_DISABLE;//maybe unnecessary? printCommState(dcb); hPort = CreateFile(commPort, // This comm port is defined by TCHAR so that we can use TEXT() LPFILENAME GENERIC_READ | GENERIC_WRITE,//DesiredAccess 0,//dwShareMode NULL,//LPSecurity CREATE_NEW| OPEN_EXISTING,//dwCreationDisposition 0,//Flags and attributes NULL);//hTemplateFile if (hPort == INVALID_HANDLE_VALUE) { printf("CreateFile failed with the error %d.\n", GetLastError()); scanf_s("%d", &l); return 1; } success = GetCommState(hPort, &dcb); if (!success) { printf("GetCommState failed with the error %d.\n ", GetLastError()); scanf_s("%d", &l); return 2; } success = SetCommState(hPort, &dcb); if (!success) { printf("SetCommState failed with error %d.\n", GetLastError()); scanf_s("%d", &l); return 3; } /*TIME TO READ STUFF*/ while (GetCommState(hPort, &dcb)) { printf("We're in the while statement\n"); //+=+=+=+=+=+POSSIBLE PROBLEM? if (ReadFile(hPort, buffer, 39, &dwBytesRead, NULL)) { //hFile,lpBuffer,NumberofBytesToRead,LPnumberofbytestoread,lpOverlapped printf("We're in the ifReadFile Statement!\n"); for (int j = 0; j < sizeof(buffer); j++) { printf("in the for loop!\n"); printf("%c", buffer[j]); } printf("\n"); } if (!ReadFile(hPort, &buffer, 39, &dwBytesRead, NULL)) { printf("Error with ReadFile %d\n.", GetLastError()); } } scanf_s("%d", &l); CloseHandle(hPort); return 0; } void printCommState(DCB d) { printf("\nBaudRate: %d\tByteSize: %d\tParity: %d\tStopBits: %d\n", d.BaudRate, d.ByteSize, d.Parity, d.StopBits); }

1 个答案:

答案 0 :(得分:0)

问题在于代码的GetCommState行

GetCommState code function

这里我们将DCB设置为该函数返回的设置,因此通过添加另一个DCB(例如dcbRecieving,例如)作为一个错误捕获设备并让GetCommState指向其他DCB,我们可以保持我们的错误捕获DCB并将我们的原始设置为另一个,或在if语句后设置新参数。

无论如何,非常感谢!