16,215
社区成员
发帖
与我相关
我的任务
分享
int SerialPort::connect(const char *port)
{
int error=-1;
DCB dcb;
serialPortHandle = CreateFileA(port,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (serialPortHandle != INVALID_HANDLE_VALUE)
{
error = 1;
OutputDebugString(L"Open com success!");
memset(&dcb,0,sizeof(dcb));
GetCommState(serialPortHandle,&dcb);
dcb.BaudRate = 115200;
dcb.Parity = NOPARITY;
dcb.fParity = 0;
dcb.StopBits = ONESTOPBIT;
dcb.ByteSize = 8;
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
SetCommState(serialPortHandle,&dcb);
SetupComm(serialPortHandle,SENDBUF,RECVBUF); //输入缓冲区和输出缓冲区的大小都是1024;
COMMTIMEOUTS TimeOuts;
////设定读超时;
//TimeOuts.ReadIntervalTimeout=1000; //读间隔超时;
//TimeOuts.ReadTotalTimeoutMultiplier=500; //读时间系数;
//TimeOuts.ReadTotalTimeoutConstant=5000; //读时间常量 ;
////设定写超时;
//TimeOuts.WriteTotalTimeoutMultiplier=500; //读时间常量;
//TimeOuts.WriteTotalTimeoutConstant=2000; //写时间常量;
//设定读超时;
//在读一次输入缓冲区的内容后读操作就立即返回;
//而不管是否读入了要求的字符;
TimeOuts.ReadIntervalTimeout=MAXDWORD; //读间隔超时;
TimeOuts.ReadTotalTimeoutMultiplier=0; //读时间系数;
TimeOuts.ReadTotalTimeoutConstant=0; //读时间常量;
//设定写超时;
TimeOuts.WriteTotalTimeoutMultiplier=100; //读时间常量;
TimeOuts.WriteTotalTimeoutConstant=500; //写时间常量;
SetCommTimeouts(serialPortHandle,&TimeOuts); //设置超时;
}
else
{
OutputDebugString(L"Open com fail!");
error=0;
}
if (error == 0) {
disconnect();
}
else {
clear();
OutputDebugString(L"clear called PurgeComm() function. ");
}
return error;
}