gpt4 book ai didi

c - WriteFile 在没有调试的情况下无法工作

转载 作者:行者123 更新时间:2023-11-30 18:15:24 25 4
gpt4 key购买 nike

我正在尝试将参数发送到我的arduino。所以我编写了这段代码:

#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

HANDLE serialPortHandler;
char *comPort[8] = {"1", "2", "3", "4", "5", "6", "7", "8"};
char comPortName[5] = "COM";
int i = 1;

int openPort(char *name){

serialPortHandler = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if(serialPortHandler == INVALID_HANDLE_VALUE){
return -1;
}else{
DCB dcb;
FillMemory(&dcb, sizeof(dcb), 0);
if (!GetCommState(serialPortHandler, &dcb)){
return -1;
}

dcb.BaudRate = CBR_9600 ;

if (!SetCommState(serialPortHandler, &dcb)){
return -1;
}
}
return 1;
}

int writePort(char *lpBuf,DWORD dwToWrite){
DWORD dwWritten;
if(WriteFile(serialPortHandler, lpBuf, dwToWrite, &dwWritten, NULL)){
while(dwWritten < dwToWrite);
printf("User: %s, %d", lpBuf, dwWritten);
return 0;
}else{
printf("Error");
CloseHandle(serialPortHandler);
return 1;
}
return 0;
}




int main(int argc, char *argv[]){
if(argc != 2)
return 1;
strcat(comPortName, comPort[0]);
while(openPort(comPortName) < 0 && i < sizeof(comPort) / sizeof(int)){
comPortName[3] = *comPort[i];
//printf("%s", comPortName);
i++;
Sleep(0);
}if(i >= sizeof(comPort) / sizeof(int)){
printf("Cannot Find Port");
scanf("%d");
return 1;
}
printf("Port %s Is Opened - BaudRate 9600\n", comPortName);
printf("Sent Frequency: %s\n", argv[1]);
writePort(argv[1], strlen(argv[1]));
}

但只有当我在 Debug模式下运行它并在 WriteFile 处等待片刻时它才有效。如果我从 cmd 运行它,它不会输出到我的 arduino。

最佳答案

WriteFile 函数能够异步运行。您检查过这个案例吗?

来自:https://msdn.microsoft.com/en-us/library/windows/desktop/aa365747(v=vs.85).aspx

If the function fails, or is completing asynchronously, the return value is zero (FALSE). To get extended error information, call the GetLastError function.

当发生以下情况之一时,WriteFile 函数返回:

  • 写入请求的字节数。
  • 读取操作会释放管道读取端的缓冲区空间(如果写入被阻止)。有关详细信息,请参阅管道部分。
  • 正在使用异步句柄,并且写入是异步发生的。
  • 发生错误。

(元:我猜不能对项目符号列表进行 block 引用)

关于c - WriteFile 在没有调试的情况下无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28976082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com