簡體   English   中英

串行通訊在C中不起作用

[英]Serial Communication not working in C

我正在嘗試與通過USB轉串行電纜制作的同事的板進行通信。 當我使用teraterm或膩子時,它可以正常工作,但是當我使用示例代碼來完成時,它卻無法正常工作。

由於我不知道如何執行此操作-至少在幾年前,我還是最后一次這樣做-我正在使用github中的一段代碼: 使用Win32API進行Seerial編程

我知道,如果我發送命令:SB50G,則LED應該點亮。 但事實並非如此。 因此,我嘗試查看它是否發回錯誤(如果出現任何錯誤,應發送'E'char)。 雖然什么也沒收到。 然后,我嘗試傳輸命令“ 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");
}

有人可以向我解釋為什么它不起作用,或者以任何方式找出為什么它不起作用嗎? 澳元匯率和應有的水平。

最好的祝福。

問題似乎是由於董事會造成的。 安裝嗅探器后,我可以看到發送了正確的數據,但是沒有返回任何信息。 顯然,需要從數據中發送回車符,然后它才起作用。

非常感謝您的評論,我將認真考慮它們。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM