laistery
11/17/2017 - 4:17 PM

获取和设定串口状态

SetCommState() 用途:设置串口状态,包括常用的更改串口号、波特率、奇偶校验方式、数据位数等 原型:BOOL SetCommState(HANDLE hFile, LPDCB lpDCB); 参数说明: -hFile:串口句柄 -lpDCB:设备控制块(Device Control Block)结构地址。要更改的串口参数包含在此结构中。 操作举例:DCB ComDCB; GetCommState(hComm,&ComDCB);//取得当前串口状态 ComDCB.BaudRate=9600;//更改为9600bps,该值即为你要修改后的波特率 SetCommState(hComm,&ComDCB;//将更改后的参数写入串口

VOID try_com_state()
{
    DCB ComDCB;
    GetCommState(hComm,&ComDCB);
    ComDCB.BaudRate=9600; //波特率为9600
    ComDCB.ByteSize=8; //每个字节有8位
    ComDCB.Parity=NOPARITY; //无奇偶校验位
    ComDCB.StopBits=ONESTOPBIT; //1个停止位

    SetCommState(hComm, &ComDCB);

    COMMTIMEOUTS TimeOuts;
    //设定读超时
    TimeOuts.ReadIntervalTimeout=1000;
    TimeOuts.ReadTotalTimeoutMultiplier=0;
    TimeOuts.ReadTotalTimeoutConstant=0;
    //在读一次输入缓冲区的内容后读操作就立即返回,
    //而不管是否读入了要求的字符。
    //设定写超时
    TimeOuts.WriteTotalTimeoutMultiplier=100;
    TimeOuts.WriteTotalTimeoutConstant=500;
    SetCommTimeouts(hComm, &TimeOuts); //设置超时

    SetupComm(hComm, 2048, 2048);   //设置输入输出缓存区

 //   SetCommState(hComm, &ComDCB);
    PurgeComm(hComm, PURGE_TXCLEAR|PURGE_RXCLEAR);

    //printf("%d",ComDCB.BaudRate);
    //MessageBoxA(NULL, inttostr(ComDCB.BaudRate), "Playwav", MB_OK);
}