我正在尝试使用串行端口通信通过 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);
}
谢谢你。杰克。