ze= 8;
unsigned char ucSet;
ucSet = (unsigned char) ((FC_RTSCTS&FC_DTRDSR) != 0);
ucSet = (unsigned char) ((FC_RTSCTS&FC_RTSCTS) ! = 0);
ucSet = (unsigned char) ((FC_RTSCTS&FC_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:
;
}
//发送数据
void CSerialAPIView::OnSend()
{
char szMessage[20] = “thank you very much”;
DWORD dwBytesWritten;
for (int i=0; i<sizeof(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;
}
dwBytesWritten++;
}
}
1.2 接收例程
DCB ComDcb; //设备控制块
HANDLE hCom; //global handle
hCom = CreateFile ("COM1",GENERIC_READ| GENERIC_WRITE,0,
NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if (hCom==INVALID_HANDLE_VALUE)
{
AfxMessageBox("无法打开串行口");
}
else
{
COMMTIMEOUTS CommTimeOuts ;
SetCommMask(hCom, EV_RXCHAR ) ;
SetupComm(hCom, 4096, 4096 ) ; /*设置收发缓冲区 尺寸为4K */
PurgeComm(hCom, PURGE_TXABORT| PURGE_RXABORT |
PURGE_TXCLEAR| PURGE_RXCLEAR ) ; //清收发缓冲区
//以下初始化结构变量CommTimeOuts, 设置超时参数 CommTimeOuts.ReadIntervalTimeout = 0×FFFFFFFF ;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
CommTimeOuts.ReadTotalTimeoutConstant = 4000 ;
CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutConstant = 4000 ;
SetCommTimeouts(hCom, &CommTimeOuts ); //设置超时参数
ComDcb.DCBlength = sizeof( DCB ) ;
GetCommState( hCom, &ComDcb ) ; //获取当前参数
ComDcb.BaudRate =9600; //波特率
ComDcb.ByteSize = 8; //数据位
ComDcb.Parity = 0; /*校验 0~4=no, odd, even, mark, space */
SetCommState(hCom, &ComDcb ) ;
} //设置新的通信参数
接收可用定时器或线程等
DWORD dRead,dReadNum;
unsigned char buff [200];
dRead=ReadFile(hCom, buff, 100, &dReadNum, NULL); //接收100个字符,
//dReadNum为实际接收字节数
2 利用端口函数直接操作
这种方式主要是采用两个端口函数_inp(), _outp()实现对串口的读写,其中读端口函数的原型为:
int _inp(unsigned shot port)
该函数从端口读取一个字节,端口号为0~65535。
写端口的函数原型为:
int _outp(unsigned shot port, int databyte)
该函数向指定端口写入一个字节。
不同的
计算机串口地址可能不一样,通过向串口的控制及收发寄存器进行读写,可以实现灵活的串口通信功能,由于涉及具体的硬件电路讨论比较复杂,在此不加赘述。
3 MSComm控件
MSComm控件是微软开发的专用通信控件,封装了串口的所有功能,使用很方便,但在实际应用中要小心对其属性进行配置。下面详细说明该类应用方法。
3.1 MSComm控件的属性
CommPort:设置串口号,类型 short :1-comm1 2-comm2.
Settings:设置串口通信参数,类型 CString :B波特率,P奇偶性(N无校验,E偶校验,O奇校验),D