【发布时间】:2017-01-23 06:59:24
【问题描述】:
嗯,我参加这个项目大概有四个小时了。我一直在尝试创建一个小程序来读取我的 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);
}
【问题讨论】:
-
你的
#includes 是可疑的顺便说一句。 -
“程序在读取文件期间似乎挂起,所以可能是权限问题...” - 如果您缺少权限,
ReadFile将立即返回错误代码.您在哪里读到,缺少权限会导致任意代码挂起? -
您似乎正在通过
GetCommState()读取端口的状态,然后在没有任何修改的情况下通过SetCommState()设置您读取的内容。真的是你想做的吗? -
我的猜测是IDE串行监视器会将速度设置为正确的值而您的程序没有,因此只有在打开监视器后才能通信成功。 (目前不作为答案发布,因为我不确定)
-
您是否想要将通过第二个
ReadFile读取的内容扔掉?
标签: c winapi serial-port readfile