0

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

谢谢你。杰克。

4

1 回答 1

0

我暂时假设@rm5248 发布的问题是正确的,并且您正在谈论从您发布的代码编译的程序失败CreateFile failed with error The system cannot find file specified

因此,最可能的原因是您打开的 COM 端口不存在。如果您使用的是 Windows,请使用命令提示符,MODE | MORE其中将为您列出系统上可用的 Com 端口。请注意,如果使用了 com 端口,则此列表中不会显示该端口。

一旦你知道你有哪些可用的端口,改变你代码中的行hCom = CreateFile( L"COM1",

于 2013-09-18T10:00:20.103 回答