下面是一个使用Win32 API进行UART编程的简单示例。
1 #include <windows.h> 2 #include <stdio.h> 3 4 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) 5 { 6 HANDLE hCom; 7 DWORD dwError; 8 BYTE buf; 9 DWORD nBytes; 10 11 printf("%s\n", lpCmdLine); 12 13 hCom = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); 14 15 if (hCom == (HANDLE)-1) { 16 dwError = GetLastError(); 17 printf("Error = %d\n", dwError); 18 return 0; 19 } 20 21 DCB dcb; 22 GetCommState(hCom, &dcb); 23 dcb.BaudRate = 9600; 24 dcb.ByteSize = 8; 25 dcb.Parity = NOPARITY; 26 dcb.StopBits = 1; 27 dcb.fBinary = TRUE; 28 dcb.fParity = TRUE; 29 SetCommState(hCom, &dcb); 30 SetupComm(hCom, 1024, 1024); 31 PurgeComm(hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); 32 33 COMMTIMEOUTS to; 34 memset(&to, 0, sizeof(to)); 35 to.ReadIntervalTimeout = 10; 36 SetCommTimeouts(hCom, &to); 37 38 WriteFile(hCom, &buf, sizeof(buf), &nBytes, NULL); 39 ReadFile(hCom, &buf, sizeof(buf), &nBytes, NULL); 40 41 CloseHandle(hCom); 42 return 0; 43 }
时间: 2024-10-05 10:56:34