#include #include void main(void) { HANDLE hComm; // Handle to the Serial port char ComPortName[] = "COM3"; // Name of the Serial port(May Change) to be opened, DWORD dwCommEvent; DWORD dwRead; char chRead; hComm = CreateFileA(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("Error! - Port %s can't be opened\n", ComPortName); return; } else { printf("Port %s Opened\n ", ComPortName); } DCB dcbSerialParams = { 0 }; dcbSerialParams.DCBlength = sizeof(dcbSerialParams); if (!GetCommState(hComm, &dcbSerialParams)) { printf("Error in GetCommState()"); CloseHandle(hComm); return; } dcbSerialParams.BaudRate = CBR_9600; dcbSerialParams.ByteSize = 8; dcbSerialParams.StopBits = ONESTOPBIT; dcbSerialParams.Parity = NOPARITY; if (!SetCommState(hComm, &dcbSerialParams)) { printf("Error!in Setting DCB Structure"); CloseHandle(hComm); return; } if (!SetCommMask(hComm, EV_RXCHAR)) { printf("Error setting communications event mask.\n"); CloseHandle(hComm); return; } // This loop of reading chars is the fixed version; second sample below the // the "Caveat" section in https://msdn.microsoft.com/en-us/library/ff802693.aspx. // while (TRUE) { if (WaitCommEvent(hComm, &dwCommEvent, NULL)) { do { if (ReadFile(hComm, &chRead, 1, &dwRead, NULL)) { printf("%c", chRead); } else { printf("Error in ReadFile.\n"); break; } } while (dwRead != 0); } else { printf("Error in WaitCommEvent.\n"); break; } } CloseHandle(hComm); }