好吧,我去这个程序大概四个小时了。我一直在尝试创建一个小程序来读取我的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); }

最佳答案

问题出在代码的GetCommState行中

GetCommState code function

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

无论如何,非常感谢!

关于c - 从C中的串行端口读取,可能有ReadFile问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39507913/

10-12 07:36