1 概要
1.1 环境:vc++6.0 + windows xp
1.2 功能:串口通信
2 代码
2.1 读串口代码
void CTest5Dlg::OnButton1()
{
// TODO: Add your control notification handler code here
HANDLE hCom ; //全局变量,串口句柄
hCom = CreateFile ( "COM2" , //COM1口
GENERIC_READ | GENERIC_WRITE , //允许读和写
0, //独占方式
NULL ,
OPEN_EXISTING , //打开而不是创建
0 , //同步方式
NULL ) ;
if ( hCom == ( HANDLE ) - 1 )
{
AfxMessageBox ( "打开COM失败!" ) ;
//return FALSE ;
}
SetupComm ( hCom , 1024 , 1024 ) ; //输入缓冲区和输出缓冲区的大小都是1024
COMMTIMEOUTS TimeOuts ; //设定读超时
TimeOuts . ReadIntervalTimeout = 1000 ;
TimeOuts . ReadTotalTimeoutMultiplier = 500 ;
TimeOuts . ReadTotalTimeoutConstant = 5000 ; //设定写超时
TimeOuts . WriteTotalTimeoutMultiplier = 500 ;
TimeOuts . WriteTotalTimeoutConstant = 2000 ;
SetCommTimeouts ( hCom , & TimeOuts ) ; //设置超时
DCB dcb ;
GetCommState ( hCom , & dcb ) ;
dcb . BaudRate = 9600 ; //波特率为9600
dcb . ByteSize = 8 ; //每个字节有8位
dcb . Parity = NOPARITY ; //无奇偶校验位
dcb . StopBits = TWOSTOPBITS ; //两个停止位
SetCommState ( hCom , & dcb ) ;
PurgeComm ( hCom , PURGE_TXCLEAR | PURGE_RXCLEAR ) ;
//同步读串口
char str [ 100 ] ;
DWORD wCount ; //读取的字节数
BOOL bReadStat ;
bReadStat = ReadFile ( hCom , str , 100 , & wCount , NULL ) ;
if ( ! bReadStat )
{
AfxMessageBox ( "读串口失败!" ) ;
}
SetDlgItemText(IDC_EDIT1, str);
}
2.2 写串口代码
void CTest6Dlg::OnButton1()
{
// TODO: Add your control notification handler code here
// TODO: Add your control notification handler code here
HANDLE hCom ; //全局变量,串口句柄
hCom = CreateFile ( "COM3" , //COM1口
GENERIC_READ | GENERIC_WRITE , //允许读和写
0, //独占方式
NULL ,
OPEN_EXISTING , //打开而不是创建
0 , //同步方式
NULL ) ;
if ( hCom == ( HANDLE ) - 1 )
{
AfxMessageBox ( "打开COM失败!" ) ;
//return FALSE ;
}
SetupComm ( hCom , 1024 , 1024 ) ; //输入缓冲区和输出缓冲区的大小都是1024
COMMTIMEOUTS TimeOuts ; //设定读超时
TimeOuts . ReadIntervalTimeout = 1000 ;
TimeOuts . ReadTotalTimeoutMultiplier = 500 ;
TimeOuts . ReadTotalTimeoutConstant = 5000 ; //设定写超时
TimeOuts . WriteTotalTimeoutMultiplier = 500 ;
TimeOuts . WriteTotalTimeoutConstant = 2000 ;
SetCommTimeouts ( hCom , & TimeOuts ) ; //设置超时
DCB dcb ;
GetCommState ( hCom , & dcb ) ;
dcb . BaudRate = 9600 ; //波特率为9600
dcb . ByteSize = 8 ; //每个字节有8位
dcb . Parity = NOPARITY ; //无奇偶校验位
dcb . StopBits = TWOSTOPBITS ; //两个停止位
SetCommState ( hCom , & dcb ) ;
PurgeComm ( hCom , PURGE_TXCLEAR | PURGE_RXCLEAR ) ;
//同步xie串口
char lpOutBuffer [ 100 ] ;
DWORD dwBytesWrite = 100 ;
COMSTAT ComStat ;
DWORD dwErrorFlags ;
BOOL bWriteStat ;
ClearCommError ( hCom , & dwErrorFlags , & ComStat ) ;
bWriteStat = WriteFile ( hCom , lpOutBuffer , dwBytesWrite , & dwBytesWrite , NULL ) ;
if ( ! bWriteStat ) { AfxMessageBox ( "写串口失败!" ) ; }
}
3. 运行结果