}
}
}
} // close if (bRead) if (!bRead) { }
bRead = TRUE;
bResult = GetOverlappedResult(hComm, // Handle to COMM port
&m_ov, // Overlapped structure
&BytesRead, // Stores number of bytes read TRUE); // Wait flag
WriteChar(BYTE* m_szWriteBuffer, DWORD m_nToSend) {
BOOL bWrite = TRUE; BOOL bResult = TRUE; DWORD BytesSent = 0; HANDLE m_hWriteEvent; ResetEvent(m_hWriteEvent); if (bWrite) {
m_ov.Offset = 0; m_ov.OffsetHigh = 0; // Clear buffer
bResult = WriteFile(hComm, // Handle to COMM Port {
DWORD dwError = GetLastError(); switch (dwError) {
case ERROR_IO_PENDING: { } default: {
// all other error codes
// continue to GetOverlappedResults() BytesSent = 0; bWrite = FALSE; break;
m_szWriteBuffer, // Pointer to message buffer in calling finction m_nToSend, // Length of message to send &BytesSent, // Where to store the number of bytes sent &m_ov); // Overlapped structure
if (!bResult)
}
}
} }
ProcessErrorMessage(\);
} // end if(bWrite) if (!bWrite) {
bWrite = TRUE;
bResult = GetOverlappedResult(hComm, // Handle to COMM port
&m_ov, // Overlapped structure
&BytesSent, // Stores number of bytes sent TRUE); // Wait flag
// deal with the error code if (!bResult) { }
ProcessErrorMessage(\);
} // end if (!bWrite)
// Verify that the data size send equals what we tried to send if (BytesSent != m_nToSend) { }
return true;
printf(\,
BytesSent, strlen((char*)m_szWriteBuffer));
//读线程
DWORD WINAPI MyThread1(LPVOID pParam) { } //写线程
DWORD WINAPI MyThread2(LPVOID pParam) {
while (hComm != INVALID_HANDLE_VALUE) // 串口已被成功打开 { } return 0;
Sleep(100);//等待100毫秒 if (sendflag){ }
WriteChar(&sendchar, 1); sendflag = false;//发送
ReceiveChar(); return 0;
}
/************** 函数名Entry 参数
comname:串口名 BaudRate:波特率 ***************/
void Entry(char *comname, int BaudRate, HWND rhbox) { }
/*****************设置显示******************/ void DisplayHex(int flag){ }
/*****************设置超时*************/
void SetTimeOut(int a, int b, int c, int d, int e){ }
/************发送数据*************/ void SendChar(unsigned char ch){ }
/*********关闭************/ void Close(){
sendchar = ch;
sendflag = true;//通知发送线程发送数据 if (setuptimeout(a, b, c, d, e))
printf(\); if (flag == 0){ } else{ }
DisplayHEX = true; DisplayHEX = false; hRbox = rhbox;
if (openport(comname))
printf(\); printf(\); printf(\); if (setupdcb(BaudRate))
if (setuptimeout(0, 0, 0, 0, 0)) //清空缓冲区
PurgeComm(hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT); hThread1 = CreateThread(NULL, 0, MyThread1, 0, 0, NULL); //读线程 hThread2 = CreateThread(NULL, 0, MyThread2, 0, 0, NULL); //写线程
} CloseHandle(hThread1);//关闭都线程 CloseHandle(hThread2);//关闭写线程 CloseHandle(hComm);//关闭串口 二、验证是否成功 把DLL放在EXE一起
三、验证串口库代码:
#pragma comment(lib,\) extern \_declspec(dllimport)void Entry(char *comname, int BaudRate, NULL); extern \_declspec(dllimport) void SendChar(unsigned char ch); extern \_declspec(dllimport) void Close(); extern \_declspec(dllimport) void DisplayHex(int flag); #include
可以看出不用MFC编写的串口程序体积非常小
五、单片机上的程序
#include