Windows API 串口編程

來源:互聯網
上載者:User

如果需要封裝的串口程式,請到這裡進行下載:http://download.csdn.net/source/2890723

 

最近一直在研究串口的編程,在這裡寫下win32 API串口通訊編程的一般流程:

(1) 開啟串口:CreateFile函數

// get a handle to the port<br />m_hComm = CreateFile("szPort", // communication port string (COMX)<br />GENERIC_READ | GENERIC_WRITE,// read/write types<br />0,// comm devices must be opened with exclusive access<br />NULL,// no security attributes<br />OPEN_EXISTING,// comm devices must use OPEN_EXISTING<br />FILE_FLAG_OVERLAPPED,// Async I/O<br />0);// template must be 0 for comm devices

(2)建立串口通訊事件 CreateEvent函數

// create events<br />if (m_ov.hEvent != NULL)<br />ResetEvent(m_ov.hEvent);<br />else<br />m_ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);</p><p>if (m_hWriteEvent != NULL)<br />ResetEvent(m_hWriteEvent);<br />else<br />m_hWriteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);</p><p>if (m_hShutdownEvent != NULL)<br />ResetEvent(m_hShutdownEvent);<br />else<br />m_hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);<br />

解釋:ResetEvent函數將事件置為無訊號狀態,setEvent函數是將事件置為有訊號狀態。

(3)初始化串口,設定串口參數:SetCommState函數

// configure<br />if (SetCommTimeouts(m_hComm, &m_CommTimeouts))//設定逾時<br />{<br />if (SetCommMask(m_hComm, dwCommEvents))//設定通訊事件<br />{<br />if (GetCommState(m_hComm, &m_dcb))//擷取當前的DCB結構參數<br />{<br />m_dcb.EvtChar = 'q';<br />m_dcb.fRtsControl = RTS_CONTROL_ENABLE;// set RTS bit high!<br />if (BuildCommDCB(szBaud, &m_dcb))//填寫DCB結構<br />{<br />if (SetCommState(m_hComm, &m_dcb))//利用DCB配置<br />; // normal operation... continue<br />else<br />ProcessErrorMessage("SetCommState()");<br />}<br />else<br />ProcessErrorMessage("BuildCommDCB()");<br />}<br />else<br />ProcessErrorMessage("GetCommState()");<br />}<br />else<br />ProcessErrorMessage("SetCommMask()");<br />}<br />else<br />ProcessErrorMessage("SetCommTimeouts()");<br />

(4)建立讀資料的線程

一般我們是在主線程中寫資料,因為寫詩可以控制的,而讀的時候我們不知道資料什麼時候到,所以要建立一個線程專門用來讀資料。讀資料函數ReadFile;如果要檢測通訊狀態,如CTS訊號,RingIn等等, 則用setCommMask、WaitCommEvent、GetCommModemStatus函數。

(5)寫資料:用WriteFile函數。

(6)結束時關閉連接埠。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.