Home > Blockchain >  Win32 C writing to serial freezes the program after a while
Win32 C writing to serial freezes the program after a while

Time:01-28

I added a serial port writing to my code and now it freezes after few tenths of iterations. Few minutes it works just it should. If I remove serial port related lines, it will run smoothly forever. Im using Visualstudio. Can anyone spot the problem?

int main() {
    HANDLE hSerial;
    DCB dcbSerialParams = { 0 };
    
    // Open the serial port
    hSerial = CreateFile(L"COM1", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hSerial == INVALID_HANDLE_VALUE) {
        std::cout << "Error opening serial port" << std::endl;
        return 1;
    }

    // Set the serial port parameters
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
    if (GetCommState(hSerial, &dcbSerialParams) == 0) {
        std::cout << "Error getting serial port state" << std::endl;
        CloseHandle(hSerial);
        return 1;
    }
    dcbSerialParams.BaudRate = CBR_9600;
    dcbSerialParams.ByteSize = 8;
    dcbSerialParams.StopBits = ONESTOPBIT;
    dcbSerialParams.Parity = NOPARITY;
    if (SetCommState(hSerial, &dcbSerialParams) == 0) {
        std::cout << "Error setting serial port state" << std::endl;
        CloseHandle(hSerial);
        return 1;
    }

    // Send the serial message
    DWORD dwBytesWritten;
    char message[] = "c";
    WriteFile(hSerial, message, sizeof(message) - 1, &dwBytesWritten, NULL);  

    

    while (stop == 0) {
        
        WriteFile(hSerial, "x", sizeof(message) - 1, &dwBytesWritten, NULL);

        int i = 0;
        while (i < 7) {
            i  ;
            //some code that works fine without serial port writings
        }
        
        WriteFile(hSerial, "y", sizeof(message) - 1, &dwBytesWritten, NULL);

        i = 0;
        while (i < 7) {
            i  ;
            //some code that works fine without serial port writings
        }
    }
    }    
    return 0;
}

I have made the code as simple as I possible can. Still it has some serious problem.

CodePudding user response:

Probably you will try to write before the first call is not finished; the buffer can be full, check PurgeComm function. Try also to implement an event sequence. (WaitCommEvent)

CodePudding user response:

Are you reading the values on the other side of the serial? I know that for example on a lot of the cheaper knockoff FTDI USB-Serial chips which are common on Arduino-likes, they have a small (4kB) buffer, and will simply block the call if the buffer is full.

Another thing to consider if the blocking itself is your biggest issue might be to check out the FILE_FLAG_OVERLAPPED flag in CreateFile. It won't solve the issue of communication ceasing, but if your biggest concern is simply not blocking other parts of the program until communication is ready that might be an option.

  • Related