串行通信无法在C中工作

时间:2017-05-07 08:50:18

标签: c serial-port

我正在尝试与通过USB转串口线制作的同事通信。 当我使用teraterm或putty时,它工作正常,但是当我使用示例代码执行时,我无法使其工作。

因为我不知道怎么做 - 或者至少在几年前我做到了最后 - 我正在使用github的一段代码:Seerial Programming with Win32API

我知道如果我发送命令:SB50G,LED应该亮起。但事实并非如此。所以我试着看看,如果它发回一个错误(它应该发送'E'字符,以防任何错误)。虽然没有收到。然后我尝试发送命令'G',它应该返回一个8个十六进制的ASCII字符串。

打开端口时没有任何错误,除非我同时在teraterm中使用它。

代码是发送器和接收示例的合并:

#include <Windows.h>
#include <stdio.h>
#include <string.h>
void main(void)
{

    HANDLE hComm;                          // Handle to the Serial port
    char  ComPortName[] = "\\\\.\\COM3";  // Name of the Serial port(May Change) to be opened,
    BOOL  Status;                          // Status of the various operations 
    DWORD dwEventMask;                     // Event mask to trigger
    char  TempChar;                        // Temperory Character
    char  SerialBuffer[256];               // Buffer Containing Rxed Data
    DWORD NoBytesRead;                     // Bytes read by ReadFile()
    int i = 0;

    printf("\n\n +==========================================+");
    printf("\n |  Serial Transmission (Win32 API)         |");
    printf("\n +==========================================+\n");
    /*----------------------------------- Opening the Serial Port --------------------------------------------*/

    hComm = CreateFile(ComPortName,                       // Name of the Port to be Opened
        GENERIC_READ | GENERIC_WRITE,      // Read/Write Access
        0,                                 // No Sharing, ports cant be shared
        NULL,                              // No Security
        OPEN_EXISTING,                     // Open existing port only
        0,                                 // Non Overlapped I/O
        NULL);                             // Null for Comm Devices

    if (hComm == INVALID_HANDLE_VALUE)
        printf("\n   Error! - Port %s can't be opened", ComPortName);
    else
        printf("\n   Port %s Opened\n ", ComPortName);


    /*------------------------------- Setting the Parameters for the SerialPort ------------------------------*/

    DCB dcbSerialParams = { 0 };                        // Initializing DCB structure
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);

    Status = GetCommState(hComm, &dcbSerialParams);     //retreives  the current settings

    if (Status == FALSE)
        printf("\n   Error! in GetCommState()");

    dcbSerialParams.BaudRate = CBR_19200;      // Setting BaudRate = 9600
    dcbSerialParams.ByteSize = 8;             // Setting ByteSize = 8
    dcbSerialParams.StopBits = ONESTOPBIT;    // Setting StopBits = 1
    dcbSerialParams.Parity = NOPARITY;      // Setting Parity = None 

    Status = SetCommState(hComm, &dcbSerialParams);  //Configuring the port according to settings in DCB 

    if (Status == FALSE)
    {
        printf("\n   Error! in Setting DCB Structure");
    }
    else
    {
        printf("\n   Setting DCB Structure Successfull\n");
        printf("\n       Baudrate = %d", dcbSerialParams.BaudRate);
        printf("\n       ByteSize = %d", dcbSerialParams.ByteSize);
        printf("\n       StopBits = %d", dcbSerialParams.StopBits);
        printf("\n       Parity   = %d", dcbSerialParams.Parity);
    }

    Status = SetCommMask(hComm, EV_RXCHAR); //Configure Windows to Monitor the serial device for Character Reception

    if (Status == FALSE)
        printf("\n\n    Error! in Setting CommMask");
    else
        printf("\n\n    Setting CommMask successfull");


    /*------------------------------------ Setting Timeouts --------------------------------------------------*/

    COMMTIMEOUTS timeouts = { 0 };

    timeouts.ReadIntervalTimeout = 50;
    timeouts.ReadTotalTimeoutConstant = 50;
    timeouts.ReadTotalTimeoutMultiplier = 10;
    timeouts.WriteTotalTimeoutConstant = 50;
    timeouts.WriteTotalTimeoutMultiplier = 10;

    if (SetCommTimeouts(hComm, &timeouts) == FALSE)
        printf("\n   Error! in Setting Time Outs");
    else
        printf("\n\n   Setting Serial Port Timeouts Successfull");


    /*----------------------------- Writing a Character to Serial Port----------------------------------------*/
    char   lpBuffer[] = "G\r";             // lpBuffer should be  char or byte array, otherwise write wil fail
    DWORD  dNoOFBytestoWrite;              // No of bytes to write into the port
    DWORD  dNoOfBytesWritten = 0;          // No of bytes written to the port

    dNoOFBytestoWrite = sizeof(lpBuffer); // Calculating the no of bytes to write into the port

    Status = WriteFile(hComm,               // Handle to the Serialport
        lpBuffer,            // Data to be written to the port 
        dNoOFBytestoWrite,   // No of bytes to write into the port
        &dNoOfBytesWritten,  // No of bytes written to the port
        NULL);

    if (Status == TRUE)
        printf("\n\n    %s - Written to %s", lpBuffer, ComPortName);
    else
        printf("\n\n   Error %d in Writing to Serial Port", GetLastError());


    /*------------------------------------ Setting WaitComm() Event   ----------------------------------------*/

    printf("\n\n    Waiting for Data Reception");

    Status = WaitCommEvent(hComm, &dwEventMask, NULL); //Wait for the character to be received

                                                       /*-------------------------- Program will Wait here till a Character is received ------------------------*/

    if (Status == FALSE)
    {
        printf("\n    Error! in Setting WaitCommEvent()");
    }
    else //If  WaitCommEvent()==True Read the RXed data using ReadFile();
    {
        printf("\n\n    Characters Received");
        do
        {
            Status = ReadFile(hComm, &TempChar, sizeof(TempChar), &NoBytesRead, NULL);
            SerialBuffer[i] = TempChar;
            i++;
        } while (NoBytesRead > 0);



        /*------------Printing the RXed String to Console----------------------*/

        printf("\n\n    ");
        int j = 0;
        for (j = 0; j < i - 1; j++)     // j < i-1 to remove the dupliated last character
            printf("%c", SerialBuffer[j]);

    }

    CloseHandle(hComm);//Closing the Serial Port
    printf("\n +==========================================+\n");
}

有人可以向我解释为什么它不起作用,或者我能找出它为什么不起作用的任何方式? BAUD率和它们应该是这样的。

最好的问候。

1 个答案:

答案 0 :(得分:0)

这个问题似乎是由董事会决定的。安装嗅探器后,我可以看到正在发送的数据,但是没有返回。 显然,回车需要从数据中分离出来,然后就可以了。

非常感谢您的评论,我会认真考虑他们。 :)