{{indexmenu_n>4200}} ===== Sériový port ve Win API ====== Pokud je z nějakého důvodu nutné použít sériový port s rozhraním Win API liší se způsob oteření rozhraní, zápis a čtení je však identické až na jméno funkce. Jednoduché příkazy pro uložení/načtení jednoho bajtu lze zapozdřit podobně jako v [[courses:b3b36prg:tutorials:serial|]] např. #include "prg_serial_winapi.h" #ifndef BAUD_RATE #define BAUD_RATE B115200 #endif /// ---------------------------------------------------------------------------- HANDLE serialWinApi_open( LPCTSTR lpszDevice ) { DWORD dwInQueue = 16; DWORD dwOutQueue = 16; // Open the device HANDLE hFile = CreateFile(lpszDevice, GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if (hFile == INVALID_HANDLE_VALUE) { return NULL; } if (!SetupComm( hFile, dwInQueue, dwOutQueue)) { // error (void)serialWinApi_close( hFile ); return NULL; } // Obtain the DCB structure for the device { DCB dcb; if (!GetCommState(hFile,&dcb)) { // error (void)serialWinApi_close( hFile ); return NULL; } // Set the new data dcb.BaudRate = (DWORD)(CBR_115200); dcb.ByteSize = (BYTE)(8); dcb.Parity = (BYTE)(NOPARITY); dcb.StopBits = (BYTE)(ONESTOPBIT); // Set the new DCB structure if (!SetCommState(hFile,&dcb)) { // Obtain the error code (void)serialWinApi_close( hFile ); return NULL; } } // Return successful return hFile; } /// ---------------------------------------------------------------------------- int serialWinApi_close( HANDLE hSerial ) { // Close COM port CloseHandle( hSerial ); return 1; } /// ---------------------------------------------------------------------------- int serialWinApi_putc( HANDLE hSerial, char c) { DWORD dwWritten; DWORD dwRetVal; // Write the data dwRetVal = WriteFile(hSerial, &c, 1, &dwWritten, 0); return dwWritten; } /// ---------------------------------------------------------------------------- int serialWinApi_getc( HANDLE hSerial, char * c) { DWORD dwRead; DWORD dwRetVal; // Read the data dwRetVal = ReadFile(hSerial, c, 1, &dwRead, 0); return dwRetVal; } Příklad použít takové knihovny #include "stdafx.h" #include "windows.h" #include "prg_serial_winapi.h" int _tmain(int argc, _TCHAR* argv[]) { char cChar; int iRetVal = 0; LPCTSTR lpszDevice = _T("\\\\.\\COM12"); HANDLE hSerial = serialWinApi_open( lpszDevice ); iRetVal = serialWinApi_putc( hSerial, 'k' ); while( serialWinApi_getc( hSerial, &cChar ) == 0 ); if( cChar == 't' ) { printf( "receive ok"); } else { printf( "receive failed"); } iRetVal = serialWinApi_close( hSerial ); getchar(); return 0; } Zdrojové soubory modulu prg_serial_winapi jsou dostupné v archivu {{:courses:b3b36prg:tutorials:prg_serial_winapi.zip|}}.