WIN32 API异步串口读写例子代码
时间: 2023-05-16 22:06:19 浏览: 82
以下是一个WIN32 API异步串口读写的例子代码:
```
#include <windows.h>
#include <stdio.h>
#define MAX_BUFFER_SIZE 1024
HANDLE hComm;
OVERLAPPED ovRead, ovWrite;
DWORD dwBytesRead, dwBytesWritten;
char szBuff[MAX_BUFFER_SIZE];
BOOL fWaitingOnRead = FALSE, fWaitingOnWrite = FALSE;
void WriteToPort(char* szMsg)
{
if (fWaitingOnWrite)
{
printf("Error: Write operation already in progress.\n");
return;
}
memset(szBuff, 0, MAX_BUFFER_SIZE);
strcpy_s(szBuff, MAX_BUFFER_SIZE, szMsg);
if (!WriteFile(hComm, szBuff, strlen(szBuff), &dwBytesWritten, &ovWrite))
{
if (GetLastError() != ERROR_IO_PENDING)
{
printf("Error: Failed to write to port.\n");
return;
}
else
{
fWaitingOnWrite = TRUE;
}
}
else
{
printf("Message sent: %s\n", szBuff);
}
}
void ReadFromPort()
{
if (fWaitingOnRead)
{
printf("Error: Read operation already in progress.\n");
return;
}
memset(szBuff, 0, MAX_BUFFER_SIZE);
if (!ReadFile(hComm, szBuff, MAX_BUFFER_SIZE, &dwBytesRead, &ovRead))
{
if (GetLastError() != ERROR_IO_PENDING)
{
printf("Error: Failed to read from port.\n");
return;
}
else
{
fWaitingOnRead = TRUE;
}
}
else
{
printf("Message received: %s\n", szBuff);
}
}
void CALLBACK ReadCompletion(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
{
fWaitingOnRead = FALSE;
if (dwErrorCode == 0 && dwNumberOfBytesTransfered > 0)
{
szBuff[dwNumberOfBytesTransfered] = 0;
printf("Message received: %s\n", szBuff);
}
else
{
printf("Error: Failed to read from port.\n");
}
}
void CALLBACK WriteCompletion(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
{
fWaitingOnWrite = FALSE;
if (dwErrorCode == 0 && dwNumberOfBytesTransfered > 0)
{
szBuff[dwNumberOfBytesTransfered] = 0;
printf("Message sent: %s\n", szBuff);
}
else
{
printf("Error: Failed to write to port.\n");
}
}
int main()
{
hComm = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
if (hComm == INVALID_HANDLE_VALUE)
{
printf("Error: Failed to open port.\n");
return 1;
}
memset(&ovRead, 0, sizeof(ovRead));
ovRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
memset(&ovWrite, 0, sizeof(ovWrite));
ovWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
SetCommMask(hComm, EV_RXCHAR);
while (1)
{
DWORD dwEventMask;
if (WaitCommEvent(hComm, &dwEventMask, NULL))
{
if (dwEventMask & EV_RXCHAR)
{
ReadFromPort();
}
}
if (fWaitingOnRead)
{
if (GetOverlappedResult(hComm, &ovRead, &dwBytesRead, TRUE))
{
ReadCompletion(0, dwBytesRead, &ovRead);
}
}
if (fWaitingOnWrite)
{
if (GetOverlappedResult(hComm, &ovWrite, &dwBytesWritten, TRUE))
{
WriteCompletion(0, dwBytesWritten, &ovWrite);
}
}
}
CloseHandle(hComm);
CloseHandle(ovRead.hEvent);
CloseHandle(ovWrite.hEvent);
return 0;
}
```
请注意,这是一个简单的例子,仅用于演示如何使用WIN32 API进行异步串口读写。实际应用中,您可能需要根据具体需求进行修改和优化。