简体   繁体   中英

Serial Communication not working in C

I'm trying to communicate with a board a colleague made via a USB To serial cable. It works fine when I use teraterm or putty, but I can't get it to work, when I do it with a sample code.

Since I have no idea how to do this - or at least a couple of years ago I did it last - I'm using a piece of code from github: Seerial Programming with Win32API

I know that if I transmit the command: SB50G, an LED should light up. But it doesn't. So I tried to see, if it sends an error back (It should send an 'E' char in case of any error). Though nothing is received. I then tried to transmit the command 'G', which should return a an ASCII string of 8 hex'es.

I don't get any errors upon opening the port, unless I use it in teraterm at the same time.

The code is a merge of the transmitter and receive example:

#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");
}

Can someone explain to me why it's not working, or any way I can find out why it's not working? The BAUD-rate and such are as they should be.

Best regards.

The problem seemed to be due to the board. After installing a sniffer, i could see the correct data being sent out, but nothin was returned. Apparently the carriage return needed to be send separat from the data, and then it worked.

Many thanks for the comments, I'll take them in to serious consideration. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM