windows串口编程C++ 下载本文

// 向串口写入数据,类内部使用

BOOL jeff_class::CMySerialPort::WriteCommByte ( unsigned char ucByte ) {

BOOL bWriteStat;

DWORD dwBytesWritten;

bWriteStat = WriteFile ( m_hIDComDev, ( LPSTR ) &ucByte, 1, &dwBytesWritten, &m_OverlappedWrite );

// 查询异步写入是否完成,未完成则挂起等待

if ( !bWriteStat && ( GetLastError() == ERROR_IO_PENDING ) ) { if ( WaitForSingleObject ( m_OverlappedWrite.hEvent, TIMEOUT_WRITECOMM_EVENT ) )

dwBytesWritten = 0; else {

GetOverlappedResult ( m_hIDComDev, &m_OverlappedWrite, &dwBytesWritten, FALSE );

m_OverlappedWrite.Offset += dwBytesWritten; } }

return ( TRUE ); }

// 向串口发送数据

int jeff_class::CMySerialPort::SendData ( const char *buffer, int size ) {

if ( !m_bOpened || m_hIDComDev == NULL ) return ( 0 );

DWORD dwBytesWritten = 0; int i;

for ( i=0; i

WriteCommByte ( buffer[i] ); dwBytesWritten++; }

return ( ( int ) dwBytesWritten ); }

// 查询接受缓冲区内是否有数据(只查询,不读取)

int jeff_class::CMySerialPort::ReadDataWaiting ( void ) {

if ( !m_bOpened || m_hIDComDev == NULL ) return ( 0 );

DWORD dwErrorFlags; COMSTAT ComStat;

ClearCommError ( m_hIDComDev, &dwErrorFlags, &ComStat );

return ( ( int ) ComStat.cbInQue ); }

// 读取来自串口的数据

int jeff_class::CMySerialPort::ReadData ( void *buffer, int limit ) {

if ( !m_bOpened || m_hIDComDev == NULL ) return ( 0 );

BOOL bReadStatus;

DWORD dwBytesRead, dwErrorFlags; COMSTAT ComStat;

// 读取之前须清楚错误信息

ClearCommError ( m_hIDComDev, &dwErrorFlags, &ComStat );

if ( !ComStat.cbInQue ) return ( 0 );

dwBytesRead = ( DWORD ) ComStat.cbInQue;

if ( limit < ( int ) dwBytesRead ) dwBytesRead = ( DWORD ) limit;

bReadStatus = ReadFile ( m_hIDComDev, buffer, dwBytesRead, &dwBytesRead, &m_OverlappedRead );

// 查询异步读取是否完成,未完成则挂起等待 if ( !bReadStatus ) {

if ( GetLastError() == ERROR_IO_PENDING ) {

WaitForSingleObject ( m_OverlappedRead.hEvent, TIMEOUT_READCOMM_EVENT );

return ( ( int ) dwBytesRead ); }

return ( 0 ); }

return ( ( int ) dwBytesRead );

}