我正在尝试使用串口通信来通过xBee发送数据,但它无法正常工作,我不知道为什么。它没有运行,它说无法启动程序并且“系统找不到指定的文件”。如果有人可以帮助我,我将不胜感激。
以下是我用来测试它的代码:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <commdlg.h>
#include <windows.h>
int main()
{
DCB dcb;
HANDLE hCom;
BOOL fSuccess;
COMMTIMEOUTS timeouts;
char *buffWrite;
DWORD dwBytesWritten = 0;
hCom = CreateFile( L"COM9",
GENERIC_WRITE,
0, // must be opened with exclusive-access
NULL, // no security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
FILE_ATTRIBUTE_NORMAL, // not overlapped I/O
NULL // hTemplate must be NULL for comm devices
);
if (hCom == INVALID_HANDLE_VALUE)
{
// Handle the error.
printf ("CreateFile failed with error %d.\n", GetLastError());
return (1);
}
// Build on the current configuration, and skip setting the size
// of the input and output buffers with SetupComm.
fSuccess = GetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
printf ("GetCommState failed with error %d.\n", GetLastError());
return (2);
}
// Fill in DCB: 9,600 bps, 8 data bits, no parity, and 1 stop bit.
dcb.BaudRate = CBR_9600; // set the baud rate
dcb.ByteSize = 8; // data size, xmit, and rcv
dcb.Parity = NOPARITY; // no parity bit
dcb.StopBits = ONESTOPBIT; // one stop bit
fSuccess = SetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
printf ("SetCommState failed with error %d.\n", GetLastError());
return (3);
}
GetCommTimeouts(hCom,&timeouts);
//COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutConstant = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 1000;
timeouts.WriteTotalTimeoutMultiplier= 10;
if(!SetCommTimeouts(hCom, &timeouts))
{
printf("error setting port state \n");
}
buffWrite = "Testing Serial Port!";
if (WriteFile(hCom, // handle to file to write to
buffWrite, // pointer to data to write to file
sizeof(buffWrite), // number of bytes to write
&dwBytesWritten,NULL) == 0) // pointer to number of bytes written
{
printf("Reading of serial communication has problem.");
return FALSE;
}
CloseHandle(hCom);
}
谢谢。 插孔。
答案 0 :(得分:0)
我将暂时假设@ rm5248发布的问题已经出现,并且您正在谈论从您发布的代码编译的程序失败CreateFile failed with error The system cannot find file specified
。
因此,最可能的原因是您打开的COM端口不存在。如果您使用的是Windows,请使用命令提示符和MODE | MORE
,它将列出您系统上可用的Com端口。请注意,如果使用com端口,则不会在此列表中显示。
了解可用的端口后,请更改代码hCom = CreateFile( L"COM1",