#include #include #include int main (void) { //Asking for the COM port to use and attempting to open it char COMPort[5] = {'C','O','M','?','\0'}; HANDLE hSerial; printf("What COM port do you want to use ?\n"); scanf("%c",&COMPort[3]); hSerial = CreateFile(COMPort, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if(hSerial==INVALID_HANDLE_VALUE) { if(GetLastError()==ERROR_FILE_NOT_FOUND) { printf("Serial port does not exist\n");//serial port does not exist. Inform user. system("pause"); return -1; } printf("An error occured while trying to open the serial port\n");//some other error occurred. Inform user. system("pause"); return -1; } //Setting communication parameters DCB dcbSerialParams = {0}; dcbSerialParams.DCBlength=sizeof(dcbSerialParams); if (!GetCommState(hSerial, &dcbSerialParams)) { printf("An error occured while trying to control the COM port\n");//error getting state system("pause"); return -1; } dcbSerialParams.BaudRate=CBR_115200; dcbSerialParams.ByteSize=8; dcbSerialParams.StopBits=ONESTOPBIT; dcbSerialParams.Parity=NOPARITY; if(!SetCommState(hSerial, &dcbSerialParams)) { printf("An error occured while trying to apply communication settings\n");//error setting serial port state system("pause"); return -1; } //Setting tiemouts for reading and writing processes COMMTIMEOUTS timeouts={0}; timeouts.ReadIntervalTimeout=50; timeouts.ReadTotalTimeoutConstant=50; timeouts.ReadTotalTimeoutMultiplier=10; timeouts.WriteTotalTimeoutConstant=50; timeouts.WriteTotalTimeoutMultiplier=10; if(!SetCommTimeouts(hSerial, &timeouts)) { printf("An error occured while trying to apply timeout settings\n");//error occureed. Inform user system("pause"); return -1; } //Writing data to the COM port char c = 'a'; DWORD bytesWritten = 0; int again = 0; do { if(!WriteFile(hSerial, &c, sizeof(c), &bytesWritten, NULL)) { printf("An error uccured while trying to write data to the COM port\n");//error occurred. Report to user. system("pause"); return -1; } else { printf("Successful writing of %ld bytes\n",bytesWritten); } printf("Send another char ? Type 1, 0 otherwise\n"); scanf("%d",&again); } while(again == 1); //Closing the COM port we've just used CloseHandle(hSerial); system("pause"); return 0; }