genoveseV
genoveseV

Reputation: 61

WriteFile to serial port is working but the number of bytes written is zero

The issue: my console application (Microsoft Visual Studio C++ 2019) sends data via a USB virtual serial port. All works fine until the WriteFile (see my code snipet) function reports zero bytes written even if the function does not fail (WriteFile returns TRUE). The GetLastError() returns 1. Please take in account that the COMM setup was properly executed (including read/write timeouts).

I understand that very similar cases have been raised in the past but really I have not found a clear explanation about the issue.

Any idea?

            if (!WriteFile(hPort, (LPCVOID)serout, 1 * sizeof(uint16_t), &byteswritten, NULL)) {
                printf("Error writing COMM port\n");
                return;
            }
            if (!byteswritten) {
                printf("Error bytes written COMM port %d", GetLastError()); 
            }
            FlushFileBuffers(hPort);

// COM SETUP
DCB dcb;
HANDLE hport;
std::string strport = "COM1";
TCHAR pcCommPort[16];
COMMTIMEOUTS timeouts;
_tcscpy_s(pcCommPort, CA2T(strport.c_str()));

hPort = CreateFile(
    pcCommPort,
    GENERIC_READ | GENERIC_WRITE,
    0,      //  must be opened with exclusive-access
    NULL,   //  default security attributes
    OPEN_EXISTING, //  must use OPEN_EXISTING
    0,      //  not overlapped I/O
    NULL); //  hTemplate must be NULL for comm devices

if (!GetCommState(hPort, &dcb))
    printf("CreateFile failed with error %d.\n", GetLastError());

//  Initialize the DCB structure.
SecureZeroMemory(&dcb, sizeof(DCB));
dcb.DCBlength = sizeof(DCB);

dcb.BaudRate = 921600; //256000 Baud
dcb.ByteSize = 8; //8 data bits
dcb.Parity = NOPARITY; //no parity
dcb.StopBits = ONESTOPBIT; //1 stop
if (!SetCommState(hPort, &dcb))
    printf("Fail setting serial port\n");

PrintCommState(dcb);

timeouts.ReadIntervalTimeout = 1;
timeouts.ReadTotalTimeoutMultiplier = 1;
timeouts.ReadTotalTimeoutConstant = 1;
timeouts.WriteTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 10;
if (!SetCommTimeouts(hPort, &timeouts))
    printf("Fail setting tineout on serial port\n");// setting timeouts failed.

PurgeComm(hPort, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);

Upvotes: 1

Views: 1146

Answers (0)

Related Questions