用VC++6.0實(shí)現(xiàn)PC機(jī)與單片機(jī)之間的數(shù)據(jù)交換
1 Windows API通信函數(shù)方法
與通信有關(guān)的Windows API函數(shù)共有26個(gè),但主要有關(guān)的有:
CreateFile() 用 “comn”(n為串口號(hào))作為文件名就可以打開(kāi)串口。
ReadFile() 讀串口。
WriteFile() 寫(xiě)串口。
CloseHandle() 關(guān)閉串口句柄。
初始化時(shí)應(yīng)注意CreateFile()函數(shù)中串口共享方式應(yīng)設(shè)為0,串口為不可共享設(shè)備,其它與一般文件讀寫(xiě)類(lèi)似。以下給出API實(shí)現(xiàn)的源代碼。
1.1 發(fā)送的例程
//聲明全局變量
HANDLE m_hIDComDev;
OVERLAPPED m_OverlappedRead, m_Over lappedWrite;
//初始化串口
void CSerialAPIView::OnInitialUpdate()
{
CView::OnInitialUpdate();
Char szComParams[50];
DCB dcb;
Memset(m_OverlappedRead, 0, sizeof (OVERLAPPED));
Memset(m_OverlappedWrite, 0, sizeof (OVERLAPPED));
m_hIDComDev = NULL;
m_hIDComDev = CreateFile(“COM2”, GENERIC_READ│GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL│FILE_FLAG_OVERLAPPED, NULL);
if (m_hIDComDev == NULL)
{
AfxMessageBox(“Can not open serial port!”);
goto endd;
}
memset(m_OverlappedRead, 0, sizeof (OVERLAPPED));
memset(m_OverlappedWrite, 0, sizeof (OVERLAPPED));
COMMTIMEOUTS CommTimeOuts;
CommTimeOuts.ReadIntervalTimeout=0×FFFFFFFF;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
CommTimeOuts.ReadTotalTimeoutConstant = 0;
CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutConstant = 5000;
SetCommTimeouts(m_hIDComDev, CommTimeOuts);
Wsprintf(szComparams, “COM2:9600, n, 8, 1”);
m_OverlappedRead. hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
m_OverlappedWrite. hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
dcb. DCBlength = sizeof(DCB);
GetCommState(m_hIDComDev, dcb);
dcb. BaudRate = 9600;
dcb. ByteSize= 8;
unsigned char ucSet;
ucSet = (unsigned char) ((FC_RTSCTSFC_DTRDSR) != 0);
ucSet = (unsigned char) ((FC_RTSCTSFC_RTSCTS) ! = 0);
ucSet = (unsigned char) ((FC_RTSCTSFC_XONXOFF) ! = 0);
if (!SetCommState(m_hIDComDev, dcb)‖
!SetupComm(m_hIDComDev,10000,10000)‖
m_OverlappedRead. hEvent ==NULL‖
m_OverlappedWrite. hEvent ==NULL)
{
DWORD dwError = GetLastError();
if (m_OverlappedRead. hEvent != NULL)
CloseHandle(m_OverlappedRead. hEvent);
if (m_OverlappedWrite. hEvent != NULL)
CloseHandle(m_OverlappedWrite. hEvent);
CloseHandle(m_hIDComDev);
}
endd:
;
}
//發(fā)送數(shù)據(jù)
void CSerialAPIView::OnSend()
{
char szMessage[20] = “thank you very much”;
DWORD dwBytesWritten;
for (int i=0; isizeof(szMessage); i++)
{
WriteFile(m_hIDComDev, (LPSTR)szMessage[i], 1, dwBytesWritten, m_OverlappedWrite);
if (WaitForSingleObject(m_OverlapperWrite, hEvent, 1000))dwBytesWritten = 0;
else
{
GentOverlappedResult(m_hIDComDev, m_OverlappedWrite, dwBytesWritten, FALSE);
m_OverlappedWrite. Offset += dwBytesWritten;
}
c語(yǔ)言相關(guān)文章:c語(yǔ)言教程
單片機(jī)相關(guān)文章:單片機(jī)教程
c++相關(guān)文章:c++教程
單片機(jī)相關(guān)文章:單片機(jī)視頻教程
單片機(jī)相關(guān)文章:單片機(jī)工作原理
評(píng)論