我正在尝试向我的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]));
}
但它只有在我在调试模式下运行并在WriteFile上等待片刻时才有效。如果我从cmd运行它它不会输出到我的arduino。
答案 0 :(得分:-1)
WriteFile
函数具有异步运行的能力。你检查过这个案子了吗?
自:https://msdn.microsoft.com/en-us/library/windows/desktop/aa365747(v=vs.85).aspx
如果函数失败或异步完成,则返回值为零(FALSE)。要获取扩展错误信息,请调用GetLastError函数。
当出现下列情况之一时,WriteFile函数返回:
(Meta:我猜不能阻止一个子弹列表)
答案 1 :(得分:-1)
问题是启动这两件事需要时间: 1.SetCommState(serialPortHandler,&amp; dcb)
所以我之前添加了Sleep,它解决了问题。