win32 SetCommState

网页:

https://msdn.microsoft.com/en-us/library/aa363436(VS.85).aspx

SetCommState 函数
根据设备控制块(device-control block (a DCB structure))的规范,配置通信设备。
这个函数重新初始化所有的硬件和控制设置。
但是不会清空输出和输入队列。

BOOL WINAPI SetCommState(
  _In_ HANDLE hFile,
  _In_ LPDCB  lpDCB
);

参数:

hFile [in]

指向通信设备的句柄。CreateFile函数 返回的 句柄。
A handle to the communications device. The CreateFile function returns this handle.

lpDCB [in]

DCB结构体指针,该结构体包含对通信设备的配置信息。

Return value

函数成功,返回非0
函数失败,返回0

Remarks

SetCommState 函数 使用 DCB 结构体 指定希望的配置
GetCommState 函数 返回当前的配置
可以使用GetCommState 返回一个DCB结构体,然后修改需要修改的几个DCB结构体的变量。
这样可以确保DCB结构体中的其他的成员变量有合适的值。
如果DCB结构体的XonChar成员变量和XoffChar成员变量相等,SetCommState函数返回失败。
当SetCommState用来配置8250的时候,对于DCB结构体中的ByteSize 和StopBits 成员函数有如下的限制:
数据的位数必须是5到8位。

Examples

For an example, see Configuring a Communications Resource.

// serialTC.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <stdio.h>


#if 0
    myDCB.BaudRate = CBR_9600;   // 设置波特率9600  
    myDCB.fBinary = TRUE; // 设置二进制模式,此处必须设置TRUE  
    myDCB.fParity = FALSE; // 支持奇偶校验  
    myDCB.fOutxCtsFlow = FALSE;  // No CTS output flow control  
    myDCB.fOutxDsrFlow = FALSE;  // No DSR output flow control  
    myDCB.fDtrControl = DTR_CONTROL_DISABLE; // No DTR flow control  
    myDCB.fDsrSensitivity = FALSE; // DSR sensitivity  
    myDCB.fTXContinueOnXoff = TRUE; // XOFF continues Tx  
    myDCB.fOutX = FALSE;     // No XON/XOFF out flow control  
    myDCB.fInX = FALSE;        // No XON/XOFF in flow control  
    myDCB.fErrorChar = FALSE;    // Disable error replacement  
    myDCB.fNull = FALSE;  // Disable null stripping  
    myDCB.fRtsControl = RTS_CONTROL_DISABLE;   //No RTS flow control  
    myDCB.fAbortOnError = FALSE;  // 当串口发生错误,并不终止串口读写  
    myDCB.ByteSize = 8;   // 数据位,范围:4-8  
    myDCB.Parity = NOPARITY; // 校验模式  
    myDCB.StopBits = 0;   // 1位停止位  
#endif


void PrintCommState(DCB dcb)
{
    //  Print some of the DCB structure values
    _tprintf( TEXT("\n BaudRate = %d, \n ByteSize = %d, \n Parity = %d, \n StopBits = %d\n"), 
              dcb.BaudRate, 
              dcb.ByteSize, 
              dcb.Parity,
              dcb.StopBits );

    _tprintf( TEXT("\n fBinary = %d, \n fParity = %d, \n fOutxCtsFlow = %d, \n fDtrControl = %d\n"), 
              dcb.fBinary, 
              dcb.fParity, 
              dcb.fOutxCtsFlow,
              dcb.fDtrControl );


    _tprintf( TEXT("\n fDsrSensitivity = %d, \n fTXContinueOnXoff = %d, \n fOutX = %d, \n fInX = %d\n"), 
              dcb.fDsrSensitivity, 
              dcb.fTXContinueOnXoff, 
              dcb.fOutX,
              dcb.fInX );

    _tprintf( TEXT("\n fErrorChar = %d, \n fNull = %d, \n fRtsControl = %d, \n fAbortOnError = %d\n"), 
              dcb.fErrorChar, 
              dcb.fNull, 
              dcb.fRtsControl,
              dcb.fAbortOnError );
    printf("\r\n\r\n\r\n");
}




int _tmain(int argc, _TCHAR* argv[])
{

   DCB dcb;
   HANDLE hCom;
   BOOL fSuccess;
   TCHAR *pcCommPort = TEXT("COM6"); //  Most systems have a COM1 port

   //  Open a handle to the specified com port.
   hCom = CreateFile( pcCommPort,
                      GENERIC_READ | GENERIC_WRITE,
                      0,      //  must be opened with exclusive-access
                      NULL,   //  default security attributes
                      OPEN_EXISTING, //  must use OPEN_EXISTING
                      0,      //  not overlapped I/O
                      NULL ); //  hTemplate must be NULL for comm devices

   if (hCom == INVALID_HANDLE_VALUE) 
   {
       //  Handle the error.
       printf ("CreateFile failed with error %d.\n", GetLastError());
       return (1);
   }

   //  Initialize the DCB structure.
   SecureZeroMemory(&dcb, sizeof(DCB));
   dcb.DCBlength = sizeof(DCB);

   //  Build on the current configuration by first retrieving all current
   //  settings.
   fSuccess = GetCommState(hCom, &dcb);

   if (!fSuccess) 
   {
      //  Handle the error.
      printf ("GetCommState failed with error %d.\n", GetLastError());
      return (2);
   }

   PrintCommState(dcb);       //  Output to console

   //  Fill in some DCB values and set the com state: 
   //  57,600 bps, 8 data bits, no parity, and 1 stop bit.
   dcb.BaudRate = CBR_9600;     //  baud rate
   dcb.ByteSize = 8;             //  data size, xmit and rcv
   dcb.Parity   = NOPARITY;      //  parity bit
   dcb.StopBits = ONESTOPBIT;    //  stop bit

   fSuccess = SetCommState(hCom, &dcb);

   if (!fSuccess) 
   {
      //  Handle the error.
      printf ("SetCommState failed with error %d.\n", GetLastError());
      return (3);
   }

   //  Get the comm config again.
   fSuccess = GetCommState(hCom, &dcb);

   if (!fSuccess) 
   {
      //  Handle the error.
      printf ("GetCommState failed with error %d.\n", GetLastError());
      return (2);
   }

   PrintCommState(dcb);       //  Output to console

   _tprintf (TEXT("Serial port %s successfully reconfigured.\n"), pcCommPort);

   return (0);
}

运行结果:


 BaudRate = 9600,
 ByteSize = 8,
 Parity = 0,
 StopBits = 0

 fBinary = 1,
 fParity = 0,
 fOutxCtsFlow = 0,
 fDtrControl = 1

 fDsrSensitivity = 0,
 fTXContinueOnXoff = 0,
 fOutX = 0,
 fInX = 0

 fErrorChar = 0,
 fNull = 0,
 fRtsControl = 1,
 fAbortOnError = 0


 BaudRate = 9600,
 ByteSize = 8,
 Parity = 0,
 StopBits = 0

 fBinary = 1,
 fParity = 0,
 fOutxCtsFlow = 0,
 fDtrControl = 1

 fDsrSensitivity = 0,
 fTXContinueOnXoff = 0,
 fOutX = 0,
 fInX = 0

 fErrorChar = 0,
 fNull = 0,
 fRtsControl = 1,
 fAbortOnError = 0

Serial port COM6 successfully reconfigured.
请按任意键继续. . .
CSerialPort First Version by Remon Spekreijse on 2000-02-08 http://www.codeguru.com/cpp/i-n/network/serialcommunications/article.php/c2483/A-communication-class-for-serial-port.htm Second Version by mrlong on 2007-12-25 https://code.google.com/p/mycom/ 增加 ClosePort 增加 WriteToPort 两个方法 增加 SendData 与 RecvData 方法 by liquanhai on 2011-11-04 http://blog.csdn.net/liquanhai/article/details/4955253 增加 ClosePort 中交出控制权,防止死锁问题 by liquanhai on 2011-11-06 http://blog.csdn.net/liquanhai/article/details/6941574 增加 ReceiveChar 中防止线程死锁 by viruscamp on 2013-12-04 https://github.com/viruscamp/CSerialPort 增加 IsOpen 判断是否打开 修正 InitPort 中 parity Odd Even 参数取值错误 修改 InitPort 中 portnr 取值范围,portnr>9 时特殊处理 取消对 MFC 的依赖,使用 HWND 替代 CWnd,使用 win32 thread 函数而不是 MFC 的 增加用户消息编号自定义,方法来自 CnComm by itas109 on 2014-01-10 http://blog.csdn.net/itas109/article/details/18358297 解决COM10以上端口无法显示的问题 扩展可选择端口,最大值MaxSerialPortNum可以自定义 添加QueryKey()和Hkey2ComboBox两个方法,用于自动查询当前有效的串口号。 by liquanhai on 2014-12-18 增加一些处理措施,主要是对减少CPU占用率 by itas109 on 2016-05-07 http://blog.csdn.net/itas109 修复每次打开串口发送一次,当串口无应答时,需要关闭再打开或者接收完数据才能发送的问题。 解决办法:在m_hEventArray中调整m_hWriteEvent的优先级高于读的优先级。CommThread(LPVOID pParam)函数中读写的位置也调换。 参考:http://zhidao.baidu.com/link?url=RSrbPcfTZRULFFd2ziHZPBwnoXv1iCSu_Nmycb_yEw1mklT8gkoNZAkWpl3UDhk8L35DtRPo5VV5kEGpOx-Gea 修复停止位在头文件中定义成1导致SetCommState报错的问题,应为1对应的停止位是1.5。UINT stopsbits = ONESTOPBIT switch(stopbits)和switch(parity)增加默认情况,增强程序健壮性 by itas109 on 2016-06-22 http://blog.csdn.net/itas109 增加ReceiveStr方法,用于接收字符串(接收缓冲区有多少字符就接收多少字符)。 解决ReceiveChar只能接收单个字符的问题。 by itas109 on 2016-06-29 http://blog.csdn.net/itas109 解决RestartMonitoring方法和StopMonitoring方法命令不准确引起的歧义,根据实际作用。 将RestartMonitoring更改为ResumeMonitoring,将StopMonitoring更改为SuspendMonitoring。 增加IsThreadSuspend方法,用于判断线程是否挂起。 改进ClosePort方法,增加线程挂起判断,解决由于线程挂起导致串口关闭死锁的问题。 增加IsReceiveString宏定义,用于接收时采用单字节接收还是多字节接收 by itas109 on 2016-08-02 http://blog.csdn.net/itas109 https://github.com/itas109 改进IsOpen方法,m_hComm增加INVALID_HANDLE_VALUE的情况,因为CreateFile方法失败返回的是INVALID_HANDLE_VALUE,不是NULL 改进ClosePort方法:增加串口句柄无效的判断(防止关闭死锁);m_hWriteEvent不使用CloseHandle关闭 改进CommThread、ReceiveChar、ReceiveStr和WriteChar方法中异常处理的判断,增加三种判断:串口打开失败(error code:ERROR_INVALID_HANDLE)、连接过程中非法断开(error code:ERROR_BAD_COMMAND)和拒绝访问(error code:ERROR_ACCESS_DENIED) 采用安全函数sprintf_s和strcpy_s函数替换掉sprintf和strcpy 改进QueryKey方法,用于查询注册表的可用串口值,可以搜索到任意的可用串口 改进InitPort方法,串口打开失败,增加提示信息:串口不存在(error code:ERROR_FILE_NOT_FOUND)和串口拒绝访问(error code:ERROR_ACCESS_DENIED) 加入viruscamp 取消对 MFC 的依赖 改进InitPort方法,如果上次串口是打开,再次调用InitPort方法,关闭串口需要做一定的延时,否则有几率导致ERROR_ACCESS_DENIED拒绝访问,也就是串口占用问题 初始化默认波特率修改为9600 修复一些释放的BUG 规范了一些错误信息,参考winerror.h -- error code definitions for the Win32 API functions 删除SendData和RecvData方法 by itas109 on 2016-08-10 http://blog.csdn.net/itas109 https://github.com/itas109 改进ReceiveStr方法,comstat.cbInQue = 0xcccccccc的情况(如串口异常断开),会导致RXBuff初始化失败 by itas109 on 2017-02-14 http://blog.csdn.net/itas109 https://github.com/itas109 兼容ASCII和UNICODE编码 ReceiveStr函数中发送函数SendMessage的第二个参数采用结构体形式,包括portNr串口号和bytesRead读取的字节数,可以处理16进制的时候0x00截断问题 精简不必要的函数SendData和RecvData 尽量的取消对 MFC 的依赖,Hkey2ComboBox函数暂时保留 其他小问题修改 博客:blog.csdn.net/itas109 Email:itas109@qq.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值